ueditor.all.js 827 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296
  1. (function(){
  2. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  3. var baidu = window.baidu || {};
  4. window.baidu = baidu;
  5. window.UE = baidu.editor = window.UE || {};
  6. UE.plugins = {};
  7. UE.commands = {};
  8. UE.instants = {};
  9. UE.I18N = {};
  10. UE.version = "1.3.6";
  11. var dom = UE.dom = {};
  12. /**
  13. * 浏览器判断模块
  14. * @file
  15. * @module UE.browser
  16. * @since 1.2.6.1
  17. */
  18. /**
  19. * 提供浏览器检测的模块
  20. * @unfile
  21. * @module UE.browser
  22. */
  23. var browser = UE.browser = function(){
  24. var agent = navigator.userAgent.toLowerCase(),
  25. opera = window.opera,
  26. browser = {
  27. /**
  28. * @property {boolean} ie 检测当前浏览器是否为IE
  29. * @example
  30. * ```javascript
  31. * if ( UE.browser.ie ) {
  32. * console.log( '当前浏览器是IE' );
  33. * }
  34. * ```
  35. */
  36. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  37. /**
  38. * @property {boolean} opera 检测当前浏览器是否为Opera
  39. * @example
  40. * ```javascript
  41. * if ( UE.browser.opera ) {
  42. * console.log( '当前浏览器是Opera' );
  43. * }
  44. * ```
  45. */
  46. opera : ( !!opera && opera.version ),
  47. /**
  48. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  49. * @example
  50. * ```javascript
  51. * if ( UE.browser.webkit ) {
  52. * console.log( '当前浏览器是webkit内核浏览器' );
  53. * }
  54. * ```
  55. */
  56. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  57. /**
  58. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  59. * @example
  60. * ```javascript
  61. * if ( UE.browser.mac ) {
  62. * console.log( '当前浏览器运行在mac平台下' );
  63. * }
  64. * ```
  65. */
  66. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  67. /**
  68. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  69. * @example
  70. * ```javascript
  71. * if ( UE.browser.quirks ) {
  72. * console.log( '当前浏览器运行处于“怪异模式”' );
  73. * }
  74. * ```
  75. */
  76. quirks : ( document.compatMode == 'BackCompat' )
  77. };
  78. /**
  79. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  80. * @example
  81. * ```javascript
  82. * if ( UE.browser.gecko ) {
  83. * console.log( '当前浏览器内核是gecko内核' );
  84. * }
  85. * ```
  86. */
  87. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  88. var version = 0;
  89. // Internet Explorer 6.0+
  90. if ( browser.ie ){
  91. version = (agent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2] || 0) * 1;
  92. browser.ie11Compat = document.documentMode == 11;
  93. /**
  94. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  95. * @warning 如果浏览器不是IE, 则该值为undefined
  96. * @example
  97. * ```javascript
  98. * if ( UE.browser.ie9Compat ) {
  99. * console.log( '当前浏览器运行在IE9兼容模式下' );
  100. * }
  101. * ```
  102. */
  103. browser.ie9Compat = document.documentMode == 9;
  104. /**
  105. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  106. * @warning 如果浏览器不是IE, 则该值为undefined
  107. * @example
  108. * ```javascript
  109. * if ( UE.browser.ie8 ) {
  110. * console.log( '当前浏览器是IE8浏览器' );
  111. * }
  112. * ```
  113. */
  114. browser.ie8 = !!document.documentMode;
  115. /**
  116. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  117. * @warning 如果浏览器不是IE, 则该值为undefined
  118. * @example
  119. * ```javascript
  120. * if ( UE.browser.ie8Compat ) {
  121. * console.log( '当前浏览器运行在IE8兼容模式下' );
  122. * }
  123. * ```
  124. */
  125. browser.ie8Compat = document.documentMode == 8;
  126. /**
  127. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  128. * @warning 如果浏览器不是IE, 则该值为undefined
  129. * @example
  130. * ```javascript
  131. * if ( UE.browser.ie7Compat ) {
  132. * console.log( '当前浏览器运行在IE7兼容模式下' );
  133. * }
  134. * ```
  135. */
  136. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  137. || document.documentMode == 7 );
  138. /**
  139. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  140. * @warning 如果浏览器不是IE, 则该值为undefined
  141. * @example
  142. * ```javascript
  143. * if ( UE.browser.ie6Compat ) {
  144. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  145. * }
  146. * ```
  147. */
  148. browser.ie6Compat = ( version < 7 || browser.quirks );
  149. browser.ie9above = version > 8;
  150. browser.ie9below = version < 9;
  151. }
  152. // Gecko.
  153. if ( browser.gecko ){
  154. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  155. if ( geckoRelease )
  156. {
  157. geckoRelease = geckoRelease[1].split( '.' );
  158. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  159. }
  160. }
  161. /**
  162. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  163. * @warning 如果浏览器不是chrome, 则该值为undefined
  164. * @example
  165. * ```javascript
  166. * if ( UE.browser.chrome ) {
  167. * console.log( '当前浏览器是Chrome' );
  168. * }
  169. * ```
  170. */
  171. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  172. browser.chrome = + RegExp['\x241'];
  173. }
  174. /**
  175. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  176. * @warning 如果浏览器不是safari, 则该值为undefined
  177. * @example
  178. * ```javascript
  179. * if ( UE.browser.safari ) {
  180. * console.log( '当前浏览器是Safari' );
  181. * }
  182. * ```
  183. */
  184. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  185. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  186. }
  187. // Opera 9.50+
  188. if ( browser.opera )
  189. version = parseFloat( opera.version() );
  190. // WebKit 522+ (Safari 3+)
  191. if ( browser.webkit )
  192. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  193. /**
  194. * @property { Number } version 检测当前浏览器版本号
  195. * @remind
  196. * <ul>
  197. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  198. * <li>gecko系列会返回10900,158900等</li>
  199. * <li>webkit系列会返回其build号 (如 522等)</li>
  200. * </ul>
  201. * @example
  202. * ```javascript
  203. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  204. * ```
  205. */
  206. browser.version = version;
  207. /**
  208. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  209. * @example
  210. * ```javascript
  211. * if ( UE.browser.isCompatible ) {
  212. * console.log( '浏览器与UEditor能够良好兼容' );
  213. * }
  214. * ```
  215. */
  216. browser.isCompatible =
  217. !browser.mobile && (
  218. ( browser.ie && version >= 6 ) ||
  219. ( browser.gecko && version >= 10801 ) ||
  220. ( browser.opera && version >= 9.5 ) ||
  221. ( browser.air && version >= 1 ) ||
  222. ( browser.webkit && version >= 522 ) ||
  223. false );
  224. return browser;
  225. }();
  226. //快捷方式
  227. var ie = browser.ie,
  228. webkit = browser.webkit,
  229. gecko = browser.gecko,
  230. opera = browser.opera;
  231. /**
  232. * 工具函数包
  233. * @file
  234. * @module UE.utils
  235. * @since 1.2.6.1
  236. */
  237. /**
  238. * UEditor封装使用的静态工具函数
  239. * @module UE.utils
  240. * @unfile
  241. */
  242. var utils = UE.utils = {
  243. /**
  244. * 用给定的迭代器遍历对象
  245. * @method each
  246. * @param { Object } obj 需要遍历的对象
  247. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  248. * @example
  249. * ```javascript
  250. * var demoObj = {
  251. * key1: 1,
  252. * key2: 2
  253. * };
  254. *
  255. * //output: key1: 1, key2: 2
  256. * UE.utils.each( demoObj, funciton ( value, key ) {
  257. *
  258. * console.log( key + ":" + value );
  259. *
  260. * } );
  261. * ```
  262. */
  263. /**
  264. * 用给定的迭代器遍历数组或类数组对象
  265. * @method each
  266. * @param { Array } array 需要遍历的数组或者类数组
  267. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  268. * @example
  269. * ```javascript
  270. * var divs = document.getElmentByTagNames( "div" );
  271. *
  272. * //output: 0: DIV, 1: DIV ...
  273. * UE.utils.each( divs, funciton ( value, key ) {
  274. *
  275. * console.log( key + ":" + value.tagName );
  276. *
  277. * } );
  278. * ```
  279. */
  280. each : function(obj, iterator, context) {
  281. if (obj == null) return;
  282. if (obj.length === +obj.length) {
  283. for (var i = 0, l = obj.length; i < l; i++) {
  284. if(iterator.call(context, obj[i], i, obj) === false)
  285. return false;
  286. }
  287. } else {
  288. for (var key in obj) {
  289. if (obj.hasOwnProperty(key)) {
  290. if(iterator.call(context, obj[key], key, obj) === false)
  291. return false;
  292. }
  293. }
  294. }
  295. },
  296. /**
  297. * 以给定对象作为原型创建一个新对象
  298. * @method makeInstance
  299. * @param { Object } protoObject 该对象将作为新创建对象的原型
  300. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  301. * @example
  302. * ```javascript
  303. *
  304. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  305. *
  306. * var newObject = UE.utils.makeInstance( protoObject );
  307. * //output: Hello UEditor!
  308. * newObject.sayHello();
  309. * ```
  310. */
  311. makeInstance:function (obj) {
  312. var noop = new Function();
  313. noop.prototype = obj;
  314. obj = new noop;
  315. noop.prototype = null;
  316. return obj;
  317. },
  318. /**
  319. * 将source对象中的属性扩展到target对象上
  320. * @method extend
  321. * @remind 该方法将强制把source对象上的属性复制到target对象上
  322. * @see UE.utils.extend(Object,Object,Boolean)
  323. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  324. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  325. * @return { Object } 返回target对象
  326. * @example
  327. * ```javascript
  328. *
  329. * var target = { name: 'target', sex: 1 },
  330. * source = { name: 'source', age: 17 };
  331. *
  332. * UE.utils.extend( target, source );
  333. *
  334. * //output: { name: 'source', sex: 1, age: 17 }
  335. * console.log( target );
  336. *
  337. * ```
  338. */
  339. /**
  340. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  341. * 源对象属性名相同的属性值。
  342. * @method extend
  343. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  344. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  345. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  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, true );
  354. *
  355. * //output: { name: 'target', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. extend:function (t, s, b) {
  361. if (s) {
  362. for (var k in s) {
  363. if (!b || !t.hasOwnProperty(k)) {
  364. t[k] = s[k];
  365. }
  366. }
  367. }
  368. return t;
  369. },
  370. /**
  371. * 将给定的多个对象的属性复制到目标对象target上
  372. * @method extend2
  373. * @remind 该方法将强制把源对象上的属性复制到target对象上
  374. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  375. * 将会覆盖掉之前的值。
  376. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  377. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  378. * @return { Object } 返回target对象
  379. * @example
  380. * ```javascript
  381. *
  382. * var target = {},
  383. * source1 = { name: 'source', age: 17 },
  384. * source2 = { title: 'dev' };
  385. *
  386. * UE.utils.extend2( target, source1, source2 );
  387. *
  388. * //output: { name: 'source', age: 17, title: 'dev' }
  389. * console.log( target );
  390. *
  391. * ```
  392. */
  393. extend2:function (t) {
  394. var a = arguments;
  395. for (var i = 1; i < a.length; i++) {
  396. var x = a[i];
  397. for (var k in x) {
  398. if (!t.hasOwnProperty(k)) {
  399. t[k] = x[k];
  400. }
  401. }
  402. }
  403. return t;
  404. },
  405. /**
  406. * 模拟继承机制, 使得subClass继承自superClass
  407. * @method inherits
  408. * @param { Object } subClass 子类对象
  409. * @param { Object } superClass 超类对象
  410. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  411. * @return { Object } 继承superClass后的子类对象
  412. * @example
  413. * ```javascript
  414. * function SuperClass(){
  415. * this.name = "小李";
  416. * }
  417. *
  418. * SuperClass.prototype = {
  419. * hello:function(str){
  420. * console.log(this.name + str);
  421. * }
  422. * }
  423. *
  424. * function SubClass(){
  425. * this.name = "小张";
  426. * }
  427. *
  428. * UE.utils.inherits(SubClass,SuperClass);
  429. *
  430. * var sub = new SubClass();
  431. * //output: '小张早上好!
  432. * sub.hello("早上好!");
  433. * ```
  434. */
  435. inherits:function (subClass, superClass) {
  436. var oldP = subClass.prototype,
  437. newP = utils.makeInstance(superClass.prototype);
  438. utils.extend(newP, oldP, true);
  439. subClass.prototype = newP;
  440. return (newP.constructor = subClass);
  441. },
  442. /**
  443. * 用指定的context对象作为函数fn的上下文
  444. * @method bind
  445. * @param { Function } fn 需要绑定上下文的函数对象
  446. * @param { Object } content 函数fn新的上下文对象
  447. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  448. * @example
  449. * ```javascript
  450. *
  451. * var name = 'window',
  452. * newTest = null;
  453. *
  454. * function test () {
  455. * console.log( this.name );
  456. * }
  457. *
  458. * newTest = UE.utils.bind( test, { name: 'object' } );
  459. *
  460. * //output: object
  461. * newTest();
  462. *
  463. * //output: window
  464. * test();
  465. *
  466. * ```
  467. */
  468. bind:function (fn, context) {
  469. return function () {
  470. return fn.apply(context, arguments);
  471. };
  472. },
  473. /**
  474. * 创建延迟指定时间后执行的函数fn
  475. * @method defer
  476. * @param { Function } fn 需要延迟执行的函数对象
  477. * @param { int } delay 延迟的时间, 单位是毫秒
  478. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  479. * 而不能保证刚好到达延迟时间时执行。
  480. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  481. * @example
  482. * ```javascript
  483. * var start = 0;
  484. *
  485. * function test(){
  486. * console.log( new Date() - start );
  487. * }
  488. *
  489. * var testDefer = UE.utils.defer( test, 1000 );
  490. * //
  491. * start = new Date();
  492. * //output: (大约在1000毫秒之后输出) 1000
  493. * testDefer();
  494. * ```
  495. */
  496. /**
  497. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  498. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  499. * @method defer
  500. * @param { Function } fn 需要延迟执行的函数对象
  501. * @param { int } delay 延迟的时间, 单位是毫秒
  502. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  503. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  504. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  505. * 而不能保证刚好到达延迟时间时执行。
  506. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  507. * @example
  508. * ```javascript
  509. *
  510. * function test(){
  511. * console.log(1);
  512. * }
  513. *
  514. * var testDefer = UE.utils.defer( test, 1000, true );
  515. *
  516. * //output: (两次调用仅有一次输出) 1
  517. * testDefer();
  518. * testDefer();
  519. * ```
  520. */
  521. defer:function (fn, delay, exclusion) {
  522. var timerID;
  523. return function () {
  524. if (exclusion) {
  525. clearTimeout(timerID);
  526. }
  527. timerID = setTimeout(fn, delay);
  528. };
  529. },
  530. /**
  531. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  532. * @method indexOf
  533. * @remind 该方法的匹配过程使用的是恒等“===”
  534. * @param { Array } array 需要查找的数组对象
  535. * @param { * } item 需要在目标数组中查找的值
  536. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  537. * @example
  538. * ```javascript
  539. * var item = 1,
  540. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  541. *
  542. * //output: 4
  543. * console.log( UE.utils.indexOf( arr, item ) );
  544. * ```
  545. */
  546. /**
  547. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  548. * @method indexOf
  549. * @remind 该方法的匹配过程使用的是恒等“===”
  550. * @param { Array } array 需要查找的数组对象
  551. * @param { * } item 需要在目标数组中查找的值
  552. * @param { int } start 搜索的起始位置
  553. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  554. * @example
  555. * ```javascript
  556. * var item = 1,
  557. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  558. *
  559. * //output: 9
  560. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  561. * ```
  562. */
  563. indexOf:function (array, item, start) {
  564. var index = -1;
  565. start = this.isNumber(start) ? start : 0;
  566. this.each(array, function (v, i) {
  567. if (i >= start && v === item) {
  568. index = i;
  569. return false;
  570. }
  571. });
  572. return index;
  573. },
  574. /**
  575. * 移除数组array中所有的元素item
  576. * @method removeItem
  577. * @param { Array } array 要移除元素的目标数组
  578. * @param { * } item 将要被移除的元素
  579. * @remind 该方法的匹配过程使用的是恒等“===”
  580. * @example
  581. * ```javascript
  582. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  583. *
  584. * UE.utils.removeItem( arr, 4 );
  585. * //output: [ 5, 7, 1, 3, 6 ]
  586. * console.log( arr );
  587. *
  588. * ```
  589. */
  590. removeItem:function (array, item) {
  591. for (var i = 0, l = array.length; i < l; i++) {
  592. if (array[i] === item) {
  593. array.splice(i, 1);
  594. i--;
  595. }
  596. }
  597. },
  598. /**
  599. * 删除字符串str的首尾空格
  600. * @method trim
  601. * @param { String } str 需要删除首尾空格的字符串
  602. * @return { String } 删除了首尾的空格后的字符串
  603. * @example
  604. * ```javascript
  605. *
  606. * var str = " UEdtior ";
  607. *
  608. * //output: 9
  609. * console.log( str.length );
  610. *
  611. * //output: 7
  612. * console.log( UE.utils.trim( " UEdtior " ).length );
  613. *
  614. * //output: 9
  615. * console.log( str.length );
  616. *
  617. * ```
  618. */
  619. trim:function (str) {
  620. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  621. },
  622. /**
  623. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  624. * @method listToMap
  625. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  626. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  627. * @return { Object } 转化之后的hash对象
  628. * @example
  629. * ```javascript
  630. *
  631. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  632. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  633. *
  634. * ```
  635. */
  636. /**
  637. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  638. * @method listToMap
  639. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  640. * @param { Array } arr 字符串数组
  641. * @return { Object } 转化之后的hash对象
  642. * @example
  643. * ```javascript
  644. *
  645. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  646. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  647. *
  648. * ```
  649. */
  650. listToMap:function (list) {
  651. if (!list)return {};
  652. list = utils.isArray(list) ? list : list.split(',');
  653. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  654. obj[ci.toUpperCase()] = obj[ci] = 1;
  655. }
  656. return obj;
  657. },
  658. /**
  659. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  660. * @method unhtml
  661. * @param { String } str 需要转义的字符串
  662. * @return { String } 转义后的字符串
  663. * @example
  664. * ```javascript
  665. * var html = '<body>&</body>';
  666. *
  667. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  668. * console.log( UE.utils.unhtml( html ) );
  669. *
  670. * ```
  671. */
  672. unhtml:function (str, reg) {
  673. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  674. if (b) {
  675. return a;
  676. } else {
  677. return {
  678. '<':'&lt;',
  679. '&':'&amp;',
  680. '"':'&quot;',
  681. '>':'&gt;',
  682. "'":'&#39;'
  683. }[a]
  684. }
  685. }) : '';
  686. },
  687. /**
  688. * 将str中的转义字符还原成html字符
  689. * @see UE.utils.unhtml(String);
  690. * @method html
  691. * @param { String } str 需要逆转义的字符串
  692. * @return { String } 逆转义后的字符串
  693. * @example
  694. * ```javascript
  695. *
  696. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  697. *
  698. * //output: <body>&</body>
  699. * console.log( UE.utils.html( str ) );
  700. *
  701. * ```
  702. */
  703. html:function (str) {
  704. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  705. return {
  706. '&lt;':'<',
  707. '&amp;':'&',
  708. '&quot;':'"',
  709. '&gt;':'>',
  710. '&#39;':"'",
  711. '&nbsp;':' '
  712. }[m]
  713. }) : '';
  714. },
  715. /**
  716. * 将css样式转换为驼峰的形式
  717. * @method cssStyleToDomStyle
  718. * @param { String } cssName 需要转换的css样式名
  719. * @return { String } 转换成驼峰形式后的css样式名
  720. * @example
  721. * ```javascript
  722. *
  723. * var str = 'border-top';
  724. *
  725. * //output: borderTop
  726. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  727. *
  728. * ```
  729. */
  730. cssStyleToDomStyle:function () {
  731. var test = document.createElement('div').style,
  732. cache = {
  733. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  734. };
  735. return function (cssName) {
  736. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  737. return match.charAt(1).toUpperCase();
  738. }));
  739. };
  740. }(),
  741. /**
  742. * 动态加载文件到doc中
  743. * @method loadFile
  744. * @param { DomDocument } document 需要加载资源文件的文档对象
  745. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  746. * @example
  747. * ```javascript
  748. *
  749. * UE.utils.loadFile( document, {
  750. * src:"test.js",
  751. * tag:"script",
  752. * type:"text/javascript",
  753. * defer:"defer"
  754. * } );
  755. *
  756. * ```
  757. */
  758. /**
  759. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  760. * @method loadFile
  761. * @param { DomDocument } document 需要加载资源文件的文档对象
  762. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  763. * @param { Function } fn 资源文件加载成功之后执行的回调
  764. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  765. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  766. * @example
  767. * ```javascript
  768. *
  769. * UE.utils.loadFile( document, {
  770. * src:"test.js",
  771. * tag:"script",
  772. * type:"text/javascript",
  773. * defer:"defer"
  774. * }, function () {
  775. * console.log('加载成功');
  776. * } );
  777. *
  778. * ```
  779. */
  780. loadFile:function () {
  781. var tmpList = [];
  782. function getItem(doc, obj) {
  783. try {
  784. for (var i = 0, ci; ci = tmpList[i++];) {
  785. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  786. return ci;
  787. }
  788. }
  789. } catch (e) {
  790. return null;
  791. }
  792. }
  793. return function (doc, obj, fn) {
  794. var item = getItem(doc, obj);
  795. if (item) {
  796. if (item.ready) {
  797. fn && fn();
  798. } else {
  799. item.funs.push(fn)
  800. }
  801. return;
  802. }
  803. tmpList.push({
  804. doc:doc,
  805. url:obj.src || obj.href,
  806. funs:[fn]
  807. });
  808. if (!doc.body) {
  809. var html = [];
  810. for (var p in obj) {
  811. if (p == 'tag')continue;
  812. html.push(p + '="' + obj[p] + '"')
  813. }
  814. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  815. return;
  816. }
  817. if (obj.id && doc.getElementById(obj.id)) {
  818. return;
  819. }
  820. var element = doc.createElement(obj.tag);
  821. delete obj.tag;
  822. for (var p in obj) {
  823. element.setAttribute(p, obj[p]);
  824. }
  825. element.onload = element.onreadystatechange = function () {
  826. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  827. item = getItem(doc, obj);
  828. if (item.funs.length > 0) {
  829. item.ready = 1;
  830. for (var fi; fi = item.funs.pop();) {
  831. fi();
  832. }
  833. }
  834. element.onload = element.onreadystatechange = null;
  835. }
  836. };
  837. element.onerror = function () {
  838. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  839. };
  840. doc.getElementsByTagName("head")[0].appendChild(element);
  841. }
  842. }(),
  843. /**
  844. * 判断obj对象是否为空
  845. * @method isEmptyObject
  846. * @param { * } obj 需要判断的对象
  847. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  848. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  849. * @return { Boolean } 对象是否为空
  850. * @example
  851. * ```javascript
  852. *
  853. * //output: true
  854. * console.log( UE.utils.isEmptyObject( {} ) );
  855. *
  856. * //output: true
  857. * console.log( UE.utils.isEmptyObject( [] ) );
  858. *
  859. * //output: true
  860. * console.log( UE.utils.isEmptyObject( "" ) );
  861. *
  862. * //output: false
  863. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  864. *
  865. * //output: false
  866. * console.log( UE.utils.isEmptyObject( [1] ) );
  867. *
  868. * //output: false
  869. * console.log( UE.utils.isEmptyObject( "1" ) );
  870. *
  871. * ```
  872. */
  873. isEmptyObject:function (obj) {
  874. if (obj == null) return true;
  875. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  876. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  877. return true;
  878. },
  879. /*
  880. * 把rgb格式的颜色值转换成16进制格式
  881. * @method fixColor
  882. * @param { String } rgb格式的颜色值
  883. * @param { String }
  884. * @example
  885. * rgb(255,255,255) => "#ffffff"
  886. */
  887. fixColor:function (name, value) {
  888. if (/color/i.test(name) && /rgba?/.test(value)) {
  889. var array = value.split(",");
  890. if (array.length > 3)
  891. return "";
  892. value = "#";
  893. for (var i = 0, color; color = array[i++];) {
  894. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  895. value += color.length == 1 ? "0" + color : color;
  896. }
  897. value = value.toUpperCase();
  898. }
  899. return value;
  900. },
  901. /*
  902. * 只针对border,padding,margin做了处理,因为性能问题
  903. * @public
  904. * @function
  905. * @param {String} val style字符串
  906. */
  907. optCss:function (val) {
  908. var padding, margin, border;
  909. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  910. if (val.split(' ').length == 1) {
  911. switch (key) {
  912. case 'padding':
  913. !padding && (padding = {});
  914. padding[name] = val;
  915. return '';
  916. case 'margin':
  917. !margin && (margin = {});
  918. margin[name] = val;
  919. return '';
  920. case 'border':
  921. return val == 'initial' ? '' : str;
  922. }
  923. }
  924. return str;
  925. });
  926. function opt(obj, name) {
  927. if (!obj) {
  928. return '';
  929. }
  930. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  931. if (!t || !l || !b || !r) {
  932. for (var p in obj) {
  933. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  934. }
  935. } else {
  936. val += ';' + name + ':' +
  937. (t == b && b == l && l == r ? t :
  938. t == b && l == r ? (t + ' ' + l) :
  939. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  940. }
  941. return val;
  942. }
  943. val += opt(padding, 'padding') + opt(margin, 'margin');
  944. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  945. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  946. return b ? b + ";;" : ';'
  947. });
  948. },
  949. /**
  950. * 克隆对象
  951. * @method clone
  952. * @param { Object } source 源对象
  953. * @return { Object } source的一个副本
  954. */
  955. /**
  956. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  957. * @method clone
  958. * @param { Object } source 源对象
  959. * @param { Object } target 目标对象
  960. * @return { Object } 附加了source对象所有属性的target对象
  961. */
  962. clone:function (source, target) {
  963. var tmp;
  964. target = target || {};
  965. for (var i in source) {
  966. if (source.hasOwnProperty(i)) {
  967. tmp = source[i];
  968. if (typeof tmp == 'object') {
  969. target[i] = utils.isArray(tmp) ? [] : {};
  970. utils.clone(source[i], target[i])
  971. } else {
  972. target[i] = tmp;
  973. }
  974. }
  975. }
  976. return target;
  977. },
  978. /**
  979. * 把cm/pt为单位的值转换为px为单位的值
  980. * @method transUnitToPx
  981. * @param { String } 待转换的带单位的字符串
  982. * @return { String } 转换为px为计量单位的值的字符串
  983. * @example
  984. * ```javascript
  985. *
  986. * //output: 500px
  987. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  988. *
  989. * //output: 27px
  990. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  991. *
  992. * ```
  993. */
  994. transUnitToPx:function (val) {
  995. if (!/(pt|cm)/.test(val)) {
  996. return val
  997. }
  998. var unit;
  999. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1000. val = v;
  1001. unit = u;
  1002. });
  1003. switch (unit) {
  1004. case 'cm':
  1005. val = parseFloat(val) * 25;
  1006. break;
  1007. case 'pt':
  1008. val = Math.round(parseFloat(val) * 96 / 72);
  1009. }
  1010. return val + (val ? 'px' : '');
  1011. },
  1012. /**
  1013. * 在dom树ready之后执行给定的回调函数
  1014. * @method domReady
  1015. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1016. * @param { Function } fn dom树ready之后的回调函数
  1017. * @example
  1018. * ```javascript
  1019. *
  1020. * UE.utils.domReady( function () {
  1021. *
  1022. * console.log('123');
  1023. *
  1024. * } );
  1025. *
  1026. * ```
  1027. */
  1028. domReady:function () {
  1029. var fnArr = [];
  1030. function doReady(doc) {
  1031. //确保onready只执行一次
  1032. doc.isReady = true;
  1033. for (var ci; ci = fnArr.pop(); ci()) {
  1034. }
  1035. }
  1036. return function (onready, win) {
  1037. win = win || window;
  1038. var doc = win.document;
  1039. onready && fnArr.push(onready);
  1040. if (doc.readyState === "complete") {
  1041. doReady(doc);
  1042. } else {
  1043. doc.isReady && doReady(doc);
  1044. if (browser.ie && browser.version != 11) {
  1045. (function () {
  1046. if (doc.isReady) return;
  1047. try {
  1048. doc.documentElement.doScroll("left");
  1049. } catch (error) {
  1050. setTimeout(arguments.callee, 0);
  1051. return;
  1052. }
  1053. doReady(doc);
  1054. })();
  1055. win.attachEvent('onload', function () {
  1056. doReady(doc)
  1057. });
  1058. } else {
  1059. doc.addEventListener("DOMContentLoaded", function () {
  1060. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1061. doReady(doc);
  1062. }, false);
  1063. win.addEventListener('load', function () {
  1064. doReady(doc)
  1065. }, false);
  1066. }
  1067. }
  1068. }
  1069. }(),
  1070. /*
  1071. * 动态添加css样式
  1072. * @method cssRule
  1073. * @param { String } 节点名称
  1074. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1075. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1076. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1077. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1078. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1079. */
  1080. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1081. var indexList, index;
  1082. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1083. //获取样式
  1084. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1085. indexList = doc.indexList || (doc.indexList = {});
  1086. index = indexList[key];
  1087. if(index !== undefined){
  1088. return doc.styleSheets[index].cssText
  1089. }
  1090. return undefined;
  1091. }
  1092. doc = doc || document;
  1093. indexList = doc.indexList || (doc.indexList = {});
  1094. index = indexList[key];
  1095. //清除样式
  1096. if(style === ''){
  1097. if(index!== undefined){
  1098. doc.styleSheets[index].cssText = '';
  1099. delete indexList[key];
  1100. return true
  1101. }
  1102. return false;
  1103. }
  1104. //添加样式
  1105. if(index!== undefined){
  1106. sheetStyle = doc.styleSheets[index];
  1107. }else{
  1108. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1109. indexList[key] = index;
  1110. }
  1111. sheetStyle.cssText = style;
  1112. }: function (key, style, doc) {
  1113. var head, node;
  1114. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1115. //获取样式
  1116. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1117. node = doc.getElementById(key);
  1118. return node ? node.innerHTML : undefined;
  1119. }
  1120. doc = doc || document;
  1121. node = doc.getElementById(key);
  1122. //清除样式
  1123. if(style === ''){
  1124. if(node){
  1125. node.parentNode.removeChild(node);
  1126. return true
  1127. }
  1128. return false;
  1129. }
  1130. //添加样式
  1131. if(node){
  1132. node.innerHTML = style;
  1133. }else{
  1134. node = doc.createElement('style');
  1135. node.id = key;
  1136. node.innerHTML = style;
  1137. doc.getElementsByTagName('head')[0].appendChild(node);
  1138. }
  1139. },
  1140. sort:function(array,compareFn){
  1141. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1142. for(var i= 0,len = array.length; i<len; i++){
  1143. for(var j = i,length = array.length; j<length; j++){
  1144. if(compareFn(array[i], array[j]) > 0){
  1145. var t = array[i];
  1146. array[i] = array[j];
  1147. array[j] = t;
  1148. }
  1149. }
  1150. }
  1151. return array;
  1152. },
  1153. clearEmptyAttrs : function(obj){
  1154. for(var p in obj){
  1155. if(obj[p] === ''){
  1156. delete obj[p]
  1157. }
  1158. }
  1159. return obj;
  1160. }
  1161. };
  1162. /**
  1163. * 判断给定的对象是否是字符串
  1164. * @method isString
  1165. * @param { * } object 需要判断的对象
  1166. * @return { Boolean } 给定的对象是否是字符串
  1167. */
  1168. /**
  1169. * 判断给定的对象是否是数组
  1170. * @method isArray
  1171. * @param { * } object 需要判断的对象
  1172. * @return { Boolean } 给定的对象是否是数组
  1173. */
  1174. /**
  1175. * 判断给定的对象是否是一个Function
  1176. * @method isFunction
  1177. * @param { * } object 需要判断的对象
  1178. * @return { Boolean } 给定的对象是否是Function
  1179. */
  1180. /**
  1181. * 判断给定的对象是否是Number
  1182. * @method isNumber
  1183. * @param { * } object 需要判断的对象
  1184. * @return { Boolean } 给定的对象是否是Number
  1185. */
  1186. /**
  1187. * 判断给定的对象是否是一个正则表达式
  1188. * @method isRegExp
  1189. * @param { * } object 需要判断的对象
  1190. * @return { Boolean } 给定的对象是否是正则表达式
  1191. */
  1192. /**
  1193. * 判断给定的对象是否是一个普通对象
  1194. * @method isObject
  1195. * @param { * } object 需要判断的对象
  1196. * @return { Boolean } 给定的对象是否是普通对象
  1197. */
  1198. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) {
  1199. UE.utils['is' + v] = function (obj) {
  1200. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1201. }
  1202. });
  1203. /**
  1204. * UE采用的事件基类
  1205. * @file
  1206. * @module UE
  1207. * @class EventBase
  1208. * @since 1.2.6.1
  1209. */
  1210. /**
  1211. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1212. * @unfile
  1213. * @module UE
  1214. */
  1215. /**
  1216. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1217. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1218. * @unfile
  1219. * @module UE
  1220. * @class EventBase
  1221. */
  1222. /**
  1223. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1224. * @constructor
  1225. * @example
  1226. * ```javascript
  1227. * UE.EventBase.call(editor);
  1228. * ```
  1229. */
  1230. var EventBase = UE.EventBase = function () {};
  1231. EventBase.prototype = {
  1232. /**
  1233. * 注册事件监听器
  1234. * @method addListener
  1235. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1236. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1237. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1238. * @example
  1239. * ```javascript
  1240. * editor.addListener('selectionchange',function(){
  1241. * console.log("选区已经变化!");
  1242. * })
  1243. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1244. * if(type == 'beforegetcontent'){
  1245. * //do something
  1246. * }else{
  1247. * //do something
  1248. * }
  1249. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1250. * })
  1251. * ```
  1252. * @see UE.EventBase:fireEvent(String)
  1253. */
  1254. addListener:function (types, listener) {
  1255. types = utils.trim(types).split(/\s+/);
  1256. for (var i = 0, ti; ti = types[i++];) {
  1257. getListener(this, ti, true).push(listener);
  1258. }
  1259. },
  1260. on : function(types, listener){
  1261. return this.addListener(types,listener);
  1262. },
  1263. off : function(types, listener){
  1264. return this.removeListener(types, listener)
  1265. },
  1266. trigger:function(){
  1267. return this.fireEvent.apply(this,arguments);
  1268. },
  1269. /**
  1270. * 移除事件监听器
  1271. * @method removeListener
  1272. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1273. * @param { Function } fn 移除监听事件的函数引用
  1274. * @example
  1275. * ```javascript
  1276. * //changeCallback为方法体
  1277. * editor.removeListener("selectionchange",changeCallback);
  1278. * ```
  1279. */
  1280. removeListener:function (types, listener) {
  1281. types = utils.trim(types).split(/\s+/);
  1282. for (var i = 0, ti; ti = types[i++];) {
  1283. utils.removeItem(getListener(this, ti) || [], listener);
  1284. }
  1285. },
  1286. /**
  1287. * 触发事件
  1288. * @method fireEvent
  1289. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1290. * @remind 该方法会触发addListener
  1291. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1292. * @example
  1293. * ```javascript
  1294. * editor.fireEvent("selectionchange");
  1295. * ```
  1296. */
  1297. /**
  1298. * 触发事件
  1299. * @method fireEvent
  1300. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1301. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1302. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1303. * @example
  1304. * ```javascript
  1305. *
  1306. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1307. *
  1308. * console.log( arg1 + " " + arg2 );
  1309. *
  1310. * } );
  1311. *
  1312. * //触发selectionchange事件, 会执行上面的事件监听器
  1313. * //output: Hello World
  1314. * editor.fireEvent("selectionchange", "Hello", "World");
  1315. * ```
  1316. */
  1317. fireEvent:function () {
  1318. var types = arguments[0];
  1319. types = utils.trim(types).split(' ');
  1320. for (var i = 0, ti; ti = types[i++];) {
  1321. var listeners = getListener(this, ti),
  1322. r, t, k;
  1323. if (listeners) {
  1324. k = listeners.length;
  1325. while (k--) {
  1326. if(!listeners[k])continue;
  1327. t = listeners[k].apply(this, arguments);
  1328. if(t === true){
  1329. return t;
  1330. }
  1331. if (t !== undefined) {
  1332. r = t;
  1333. }
  1334. }
  1335. }
  1336. if (t = this['on' + ti.toLowerCase()]) {
  1337. r = t.apply(this, arguments);
  1338. }
  1339. }
  1340. return r;
  1341. }
  1342. };
  1343. /**
  1344. * 获得对象所拥有监听类型的所有监听器
  1345. * @unfile
  1346. * @module UE
  1347. * @since 1.2.6.1
  1348. * @method getListener
  1349. * @public
  1350. * @param { Object } obj 查询监听器的对象
  1351. * @param { String } type 事件类型
  1352. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1353. * @return { Array } 监听器数组
  1354. */
  1355. function getListener(obj, type, force) {
  1356. var allListeners;
  1357. type = type.toLowerCase();
  1358. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1359. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1360. }
  1361. ///import editor.js
  1362. ///import core/dom/dom.js
  1363. ///import core/utils.js
  1364. /*
  1365. * dtd html语义化的体现类
  1366. * @constructor
  1367. * @namespace dtd
  1368. */
  1369. var dtd = dom.dtd = (function() {
  1370. function _( s ) {
  1371. for (var k in s) {
  1372. s[k.toUpperCase()] = s[k];
  1373. }
  1374. return s;
  1375. }
  1376. var X = utils.extend2;
  1377. var A = _({isindex:1,fieldset:1}),
  1378. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1379. C = X( _({a:1}), B ),
  1380. D = X( {iframe:1}, C ),
  1381. 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}),
  1382. F = _({ins:1,del:1,script:1,style:1}),
  1383. 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 ),
  1384. 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 ),
  1385. I = X( _({p:1}), H ),
  1386. J = X( _({iframe:1}), H, B ),
  1387. 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}),
  1388. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1389. M = _({tr:1}),
  1390. N = _({'#':1}),
  1391. O = X( _({param:1}), K ),
  1392. P = X( _({form:1}), A, D, E, I ),
  1393. Q = _({li:1,ol:1,ul:1}),
  1394. R = _({style:1,script:1}),
  1395. S = _({base:1,link:1,meta:1,title:1}),
  1396. T = X( S, R ),
  1397. U = _({head:1,body:1}),
  1398. V = _({html:1});
  1399. 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}),
  1400. 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});
  1401. return _({
  1402. // $ 表示自定的属性
  1403. // body外的元素列表.
  1404. $nonBodyContent: X( V, U, S ),
  1405. //块结构元素列表
  1406. $block : block,
  1407. //内联元素列表
  1408. $inline : L,
  1409. $inlineWithA : X(_({a:1}),L),
  1410. $body : X( _({script:1,style:1}), block ),
  1411. $cdata : _({script:1,style:1}),
  1412. //自闭和元素
  1413. $empty : empty,
  1414. //不是自闭合,但不能让range选中里边
  1415. $nonChild : _({iframe:1,textarea:1}),
  1416. //列表元素列表
  1417. $listItem : _({dd:1,dt:1,li:1}),
  1418. //列表根元素列表
  1419. $list: _({ul:1,ol:1,dl:1}),
  1420. //不能认为是空的元素
  1421. $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}),
  1422. //如果没有子节点就可以删除的元素列表,像span,a
  1423. $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}),
  1424. $removeEmptyBlock : _({'p':1,'div':1}),
  1425. //在table元素里的元素列表
  1426. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1427. //不转换的标签
  1428. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1429. html: U,
  1430. head: T,
  1431. style: N,
  1432. script: N,
  1433. body: P,
  1434. base: {},
  1435. link: {},
  1436. meta: {},
  1437. title: N,
  1438. col : {},
  1439. tr : _({td:1,th:1}),
  1440. img : {},
  1441. embed: {},
  1442. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1443. noscript : P,
  1444. td : P,
  1445. br : {},
  1446. th : P,
  1447. center : P,
  1448. kbd : L,
  1449. button : X( I, E ),
  1450. basefont : {},
  1451. h5 : L,
  1452. h4 : L,
  1453. samp : L,
  1454. h6 : L,
  1455. ol : Q,
  1456. h1 : L,
  1457. h3 : L,
  1458. option : N,
  1459. h2 : L,
  1460. form : X( A, D, E, I ),
  1461. select : _({optgroup:1,option:1}),
  1462. font : L,
  1463. ins : L,
  1464. menu : Q,
  1465. abbr : L,
  1466. label : L,
  1467. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1468. code : L,
  1469. tfoot : M,
  1470. cite : L,
  1471. li : P,
  1472. input : {},
  1473. iframe : P,
  1474. strong : L,
  1475. textarea : N,
  1476. noframes : P,
  1477. big : L,
  1478. small : L,
  1479. //trace:
  1480. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1481. hr : L,
  1482. dt : L,
  1483. sub : L,
  1484. optgroup : _({option:1}),
  1485. param : {},
  1486. bdo : L,
  1487. 'var' : L,
  1488. div : P,
  1489. object : O,
  1490. sup : L,
  1491. dd : P,
  1492. strike : L,
  1493. area : {},
  1494. dir : Q,
  1495. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1496. applet : O,
  1497. dl : _({dt:1,dd:1}),
  1498. del : L,
  1499. isindex : {},
  1500. fieldset : X( _({legend:1}), K ),
  1501. thead : M,
  1502. ul : Q,
  1503. acronym : L,
  1504. b : L,
  1505. a : X( _({a:1}), J ),
  1506. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1507. caption : L,
  1508. i : L,
  1509. u : L,
  1510. tbody : M,
  1511. s : L,
  1512. address : X( D, I ),
  1513. tt : L,
  1514. legend : L,
  1515. q : L,
  1516. pre : X( G, C ),
  1517. p : X(_({'a':1}),L),
  1518. em :L,
  1519. dfn : L
  1520. });
  1521. })();
  1522. /**
  1523. * Dom操作工具包
  1524. * @file
  1525. * @module UE.dom.domUtils
  1526. * @since 1.2.6.1
  1527. */
  1528. /**
  1529. * Dom操作工具包
  1530. * @unfile
  1531. * @module UE.dom.domUtils
  1532. */
  1533. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1534. var tmpNode = startFromChild && node[start],
  1535. parent;
  1536. !tmpNode && (tmpNode = node[ltr]);
  1537. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1538. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1539. return null;
  1540. }
  1541. tmpNode = parent[ltr];
  1542. }
  1543. if (tmpNode && fn && !fn(tmpNode)) {
  1544. return getDomNode(tmpNode, start, ltr, false, fn);
  1545. }
  1546. return tmpNode;
  1547. }
  1548. var attrFix = ie && browser.version < 9 ? {
  1549. tabindex:"tabIndex",
  1550. readonly:"readOnly",
  1551. "for":"htmlFor",
  1552. "class":"className",
  1553. maxlength:"maxLength",
  1554. cellspacing:"cellSpacing",
  1555. cellpadding:"cellPadding",
  1556. rowspan:"rowSpan",
  1557. colspan:"colSpan",
  1558. usemap:"useMap",
  1559. frameborder:"frameBorder"
  1560. } : {
  1561. tabindex:"tabIndex",
  1562. readonly:"readOnly"
  1563. },
  1564. styleBlock = utils.listToMap([
  1565. '-webkit-box', '-moz-box', 'block' ,
  1566. 'list-item' , 'table' , 'table-row-group' ,
  1567. 'table-header-group', 'table-footer-group' ,
  1568. 'table-row' , 'table-column-group' , 'table-column' ,
  1569. 'table-cell' , 'table-caption'
  1570. ]);
  1571. var domUtils = dom.domUtils = {
  1572. //节点常量
  1573. NODE_ELEMENT:1,
  1574. NODE_DOCUMENT:9,
  1575. NODE_TEXT:3,
  1576. NODE_COMMENT:8,
  1577. NODE_DOCUMENT_FRAGMENT:11,
  1578. //位置关系
  1579. POSITION_IDENTICAL:0,
  1580. POSITION_DISCONNECTED:1,
  1581. POSITION_FOLLOWING:2,
  1582. POSITION_PRECEDING:4,
  1583. POSITION_IS_CONTAINED:8,
  1584. POSITION_CONTAINS:16,
  1585. //ie6使用其他的会有一段空白出现
  1586. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1587. //-------------------------Node部分--------------------------------
  1588. keys:{
  1589. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1590. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1591. 37:1, 38:1, 39:1, 40:1,
  1592. 13:1 /*enter*/
  1593. },
  1594. /**
  1595. * 获取节点A相对于节点B的位置关系
  1596. * @method getPosition
  1597. * @param { Node } nodeA 需要查询位置关系的节点A
  1598. * @param { Node } nodeB 需要查询位置关系的节点B
  1599. * @return { Number } 节点A与节点B的关系
  1600. * @example
  1601. * ```javascript
  1602. * //output: 20
  1603. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1604. *
  1605. * switch ( position ) {
  1606. *
  1607. * //0
  1608. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1609. * console.log('元素相同');
  1610. * break;
  1611. * //1
  1612. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1613. * console.log('两个节点在不同的文档中');
  1614. * break;
  1615. * //2
  1616. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1617. * console.log('节点A在节点B之后');
  1618. * break;
  1619. * //4
  1620. * case UE.dom.domUtils.POSITION_PRECEDING;
  1621. * console.log('节点A在节点B之前');
  1622. * break;
  1623. * //8
  1624. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1625. * console.log('节点A被节点B包含');
  1626. * break;
  1627. * case 10:
  1628. * console.log('节点A被节点B包含且节点A在节点B之后');
  1629. * break;
  1630. * //16
  1631. * case UE.dom.domUtils.POSITION_CONTAINS:
  1632. * console.log('节点A包含节点B');
  1633. * break;
  1634. * case 20:
  1635. * console.log('节点A包含节点B且节点A在节点B之前');
  1636. * break;
  1637. *
  1638. * }
  1639. * ```
  1640. */
  1641. getPosition:function (nodeA, nodeB) {
  1642. // 如果两个节点是同一个节点
  1643. if (nodeA === nodeB) {
  1644. // domUtils.POSITION_IDENTICAL
  1645. return 0;
  1646. }
  1647. var node,
  1648. parentsA = [nodeA],
  1649. parentsB = [nodeB];
  1650. node = nodeA;
  1651. while (node = node.parentNode) {
  1652. // 如果nodeB是nodeA的祖先节点
  1653. if (node === nodeB) {
  1654. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1655. return 10;
  1656. }
  1657. parentsA.push(node);
  1658. }
  1659. node = nodeB;
  1660. while (node = node.parentNode) {
  1661. // 如果nodeA是nodeB的祖先节点
  1662. if (node === nodeA) {
  1663. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1664. return 20;
  1665. }
  1666. parentsB.push(node);
  1667. }
  1668. parentsA.reverse();
  1669. parentsB.reverse();
  1670. if (parentsA[0] !== parentsB[0]) {
  1671. // domUtils.POSITION_DISCONNECTED
  1672. return 1;
  1673. }
  1674. var i = -1;
  1675. while (i++, parentsA[i] === parentsB[i]) {
  1676. }
  1677. nodeA = parentsA[i];
  1678. nodeB = parentsB[i];
  1679. while (nodeA = nodeA.nextSibling) {
  1680. if (nodeA === nodeB) {
  1681. // domUtils.POSITION_PRECEDING
  1682. return 4
  1683. }
  1684. }
  1685. // domUtils.POSITION_FOLLOWING
  1686. return 2;
  1687. },
  1688. /**
  1689. * 检测节点node在父节点中的索引位置
  1690. * @method getNodeIndex
  1691. * @param { Node } node 需要检测的节点对象
  1692. * @return { Number } 该节点在父节点中的位置
  1693. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1694. */
  1695. /**
  1696. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1697. * @method getNodeIndex
  1698. * @param { Node } node 需要检测的节点对象
  1699. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1700. * @return { Number } 该节点在父节点中的位置
  1701. * @example
  1702. * ```javascript
  1703. *
  1704. * var node = document.createElement("div");
  1705. *
  1706. * node.appendChild( document.createTextNode( "hello" ) );
  1707. * node.appendChild( document.createTextNode( "world" ) );
  1708. * node.appendChild( node = document.createElement( "div" ) );
  1709. *
  1710. * //output: 2
  1711. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1712. *
  1713. * //output: 1
  1714. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1715. *
  1716. * ```
  1717. */
  1718. getNodeIndex:function (node, ignoreTextNode) {
  1719. var preNode = node,
  1720. i = 0;
  1721. while (preNode = preNode.previousSibling) {
  1722. if (ignoreTextNode && preNode.nodeType == 3) {
  1723. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1724. i++;
  1725. }
  1726. continue;
  1727. }
  1728. i++;
  1729. }
  1730. return i;
  1731. },
  1732. /**
  1733. * 检测节点node是否在给定的document对象上
  1734. * @method inDoc
  1735. * @param { Node } node 需要检测的节点对象
  1736. * @param { DomDocument } doc 需要检测的document对象
  1737. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1738. * @example
  1739. * ```javascript
  1740. *
  1741. * var node = document.createElement("div");
  1742. *
  1743. * //output: false
  1744. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1745. *
  1746. * document.body.appendChild( node );
  1747. *
  1748. * //output: true
  1749. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1750. *
  1751. * ```
  1752. */
  1753. inDoc:function (node, doc) {
  1754. return domUtils.getPosition(node, doc) == 10;
  1755. },
  1756. /**
  1757. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1758. * 查找的起点是给定node节点的父节点。
  1759. * @method findParent
  1760. * @param { Node } node 需要查找的节点
  1761. * @param { Function } filterFn 自定义的过滤方法。
  1762. * @warning 查找的终点是到body节点为止
  1763. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1764. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1765. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1766. * @example
  1767. * ```javascript
  1768. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1769. *
  1770. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1771. * return node.tagName === "HTML";
  1772. *
  1773. * } );
  1774. *
  1775. * //output: true
  1776. * console.log( filterNode === null );
  1777. * ```
  1778. */
  1779. /**
  1780. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1781. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1782. * @method findParent
  1783. * @param { Node } node 需要查找的节点
  1784. * @param { Function } filterFn 自定义的过滤方法。
  1785. * @param { Boolean } includeSelf 查找过程是否包含自身
  1786. * @warning 查找的终点是到body节点为止
  1787. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1788. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1789. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1790. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1791. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1792. * @example
  1793. * ```html
  1794. * <body>
  1795. *
  1796. * <div id="test">
  1797. * </div>
  1798. *
  1799. * <script type="text/javascript">
  1800. *
  1801. * //output: DIV, BODY
  1802. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1803. *
  1804. * console.log( node.tagName );
  1805. * return false;
  1806. *
  1807. * }, true );
  1808. *
  1809. * </script>
  1810. * </body>
  1811. * ```
  1812. */
  1813. findParent:function (node, filterFn, includeSelf) {
  1814. if (node && !domUtils.isBody(node)) {
  1815. node = includeSelf ? node : node.parentNode;
  1816. while (node) {
  1817. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1818. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1819. }
  1820. node = node.parentNode;
  1821. }
  1822. }
  1823. return null;
  1824. },
  1825. /**
  1826. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  1827. * @method findParentByTagName
  1828. * @param { Node } node 需要查找的节点对象
  1829. * @param { Array } tagNames 需要查找的父节点的名称数组
  1830. * @warning 查找的终点是到body节点为止
  1831. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1832. * @example
  1833. * ```javascript
  1834. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  1835. * //output: BODY
  1836. * console.log( node.tagName );
  1837. * ```
  1838. */
  1839. /**
  1840. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  1841. * 否则, 起点是node的父节点。
  1842. * @method findParentByTagName
  1843. * @param { Node } node 需要查找的节点对象
  1844. * @param { Array } tagNames 需要查找的父节点的名称数组
  1845. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  1846. * @warning 查找的终点是到body节点为止
  1847. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1848. * @example
  1849. * ```javascript
  1850. * var queryTarget = document.getElementsByTagName("div")[0];
  1851. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  1852. * //output: true
  1853. * console.log( queryTarget === node );
  1854. * ```
  1855. */
  1856. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1857. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1858. return domUtils.findParent(node, function (node) {
  1859. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1860. }, includeSelf);
  1861. },
  1862. /**
  1863. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  1864. * @method findParents
  1865. * @param { Node } node 需要查找的节点对象
  1866. * @return { Array } 给定节点的祖先节点数组
  1867. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1868. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1869. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1870. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1871. */
  1872. /**
  1873. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  1874. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  1875. * @method findParents
  1876. * @param { Node } node 需要查找的节点对象
  1877. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  1878. * @return { Array } 给定节点的祖先节点数组
  1879. */
  1880. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1881. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1882. while (node = domUtils.findParent(node, filterFn)) {
  1883. parents.push(node);
  1884. }
  1885. return closerFirst ? parents : parents.reverse();
  1886. },
  1887. /**
  1888. * 在节点node后面插入新节点newNode
  1889. * @method insertAfter
  1890. * @param { Node } node 目标节点
  1891. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  1892. * @return { Node } 新插入的节点
  1893. */
  1894. insertAfter:function (node, newNode) {
  1895. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  1896. node.parentNode.appendChild(newNode);
  1897. },
  1898. /**
  1899. * 删除节点node及其下属的所有节点
  1900. * @method remove
  1901. * @param { Node } node 需要删除的节点对象
  1902. * @return { Node } 返回刚删除的节点对象
  1903. * @example
  1904. * ```html
  1905. * <div id="test">
  1906. * <div id="child">你好</div>
  1907. * </div>
  1908. * <script>
  1909. * UE.dom.domUtils.remove( document.body, false );
  1910. * //output: false
  1911. * console.log( document.getElementById( "child" ) !== null );
  1912. * </script>
  1913. * ```
  1914. */
  1915. /**
  1916. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  1917. * @method remove
  1918. * @param { Node } node 需要删除的节点对象
  1919. * @param { Boolean } keepChildren 是否需要保留子节点
  1920. * @return { Node } 返回刚删除的节点对象
  1921. * @example
  1922. * ```html
  1923. * <div id="test">
  1924. * <div id="child">你好</div>
  1925. * </div>
  1926. * <script>
  1927. * UE.dom.domUtils.remove( document.body, true );
  1928. * //output: true
  1929. * console.log( document.getElementById( "child" ) !== null );
  1930. * </script>
  1931. * ```
  1932. */
  1933. remove:function (node, keepChildren) {
  1934. var parent = node.parentNode,
  1935. child;
  1936. if (parent) {
  1937. if (keepChildren && node.hasChildNodes()) {
  1938. while (child = node.firstChild) {
  1939. parent.insertBefore(child, node);
  1940. }
  1941. }
  1942. parent.removeChild(node);
  1943. }
  1944. return node;
  1945. },
  1946. /**
  1947. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  1948. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  1949. * @method getNextDomNode
  1950. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1951. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1952. * @example
  1953. * ```html
  1954. * <body>
  1955. * <div id="test">
  1956. * <span></span>
  1957. * </div>
  1958. * <i>xxx</i>
  1959. * </body>
  1960. * <script>
  1961. *
  1962. * //output: i节点
  1963. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1964. *
  1965. * </script>
  1966. * ```
  1967. * @example
  1968. * ```html
  1969. * <body>
  1970. * <div>
  1971. * <span></span>
  1972. * <i id="test">xxx</i>
  1973. * </div>
  1974. * <b>xxx</b>
  1975. * </body>
  1976. * <script>
  1977. *
  1978. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  1979. * //output: b节点
  1980. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1981. *
  1982. * </script>
  1983. * ```
  1984. */
  1985. /**
  1986. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  1987. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  1988. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  1989. * @method getNextDomNode
  1990. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1991. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  1992. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1993. * @see UE.dom.domUtils.getNextDomNode(Node)
  1994. */
  1995. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  1996. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  1997. },
  1998. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  1999. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2000. },
  2001. /**
  2002. * 检测节点node是否属是UEditor定义的bookmark节点
  2003. * @method isBookmarkNode
  2004. * @private
  2005. * @param { Node } node 需要检测的节点对象
  2006. * @return { Boolean } 是否是bookmark节点
  2007. * @example
  2008. * ```html
  2009. * <span id="_baidu_bookmark_1"></span>
  2010. * <script>
  2011. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2012. * //output: true
  2013. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2014. * </script>
  2015. * ```
  2016. */
  2017. isBookmarkNode:function (node) {
  2018. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2019. },
  2020. /**
  2021. * 获取节点node所属的window对象
  2022. * @method getWindow
  2023. * @param { Node } node 节点对象
  2024. * @return { Window } 当前节点所属的window对象
  2025. * @example
  2026. * ```javascript
  2027. * //output: true
  2028. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2029. * ```
  2030. */
  2031. getWindow:function (node) {
  2032. var doc = node.ownerDocument || node;
  2033. return doc.defaultView || doc.parentWindow;
  2034. },
  2035. /**
  2036. * 获取离nodeA与nodeB最近的公共的祖先节点
  2037. * @method getCommonAncestor
  2038. * @param { Node } nodeA 第一个节点
  2039. * @param { Node } nodeB 第二个节点
  2040. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2041. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2042. * @example
  2043. * ```javascript
  2044. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2045. * //output: true
  2046. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2047. * ```
  2048. */
  2049. getCommonAncestor:function (nodeA, nodeB) {
  2050. if (nodeA === nodeB)
  2051. return nodeA;
  2052. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2053. while (parent = parent.parentNode) {
  2054. if (parent === nodeB) {
  2055. return parent;
  2056. }
  2057. parentsA.push(parent);
  2058. }
  2059. parent = nodeB;
  2060. while (parent = parent.parentNode) {
  2061. if (parent === nodeA)
  2062. return parent;
  2063. parentsB.push(parent);
  2064. }
  2065. parentsA.reverse();
  2066. parentsB.reverse();
  2067. while (i++, parentsA[i] === parentsB[i]) {
  2068. }
  2069. return i == 0 ? null : parentsA[i - 1];
  2070. },
  2071. /**
  2072. * 清除node节点左右连续为空的兄弟inline节点
  2073. * @method clearEmptySibling
  2074. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2075. * 则这些兄弟节点将被删除
  2076. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2077. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2078. * @example
  2079. * ```html
  2080. * <body>
  2081. * <div></div>
  2082. * <span id="test"></span>
  2083. * <i></i>
  2084. * <b></b>
  2085. * <em>xxx</em>
  2086. * <span></span>
  2087. * </body>
  2088. * <script>
  2089. *
  2090. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2091. *
  2092. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2093. * console.log( document.body.innerHTML );
  2094. *
  2095. * </script>
  2096. * ```
  2097. */
  2098. /**
  2099. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2100. * 则忽略对右边兄弟节点的操作。
  2101. * @method clearEmptySibling
  2102. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2103. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2104. * 则这些兄弟节点将被删除
  2105. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2106. */
  2107. /**
  2108. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2109. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2110. * @method clearEmptySibling
  2111. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2112. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2113. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2114. * 则这些兄弟节点将被删除
  2115. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2116. */
  2117. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2118. function clear(next, dir) {
  2119. var tmpNode;
  2120. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2121. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2122. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2123. tmpNode = next[dir];
  2124. domUtils.remove(next);
  2125. next = tmpNode;
  2126. }
  2127. }
  2128. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2129. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2130. },
  2131. /**
  2132. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2133. * @method split
  2134. * @param { Node } textNode 需要拆分的文本节点对象
  2135. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2136. * @return { Node } 拆分后形成的新节点
  2137. * @example
  2138. * ```html
  2139. * <div id="test">abcdef</div>
  2140. * <script>
  2141. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2142. * //output: def
  2143. * console.log( newNode.nodeValue );
  2144. * </script>
  2145. * ```
  2146. */
  2147. split:function (node, offset) {
  2148. var doc = node.ownerDocument;
  2149. if (browser.ie && offset == node.nodeValue.length) {
  2150. var next = doc.createTextNode('');
  2151. return domUtils.insertAfter(node, next);
  2152. }
  2153. var retval = node.splitText(offset);
  2154. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2155. if (browser.ie8) {
  2156. var tmpNode = doc.createTextNode('');
  2157. domUtils.insertAfter(retval, tmpNode);
  2158. domUtils.remove(tmpNode);
  2159. }
  2160. return retval;
  2161. },
  2162. /**
  2163. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2164. * @method isWhitespace
  2165. * @param { Node } node 需要检测的节点对象
  2166. * @return { Boolean } 检测的节点是否为空
  2167. * @example
  2168. * ```html
  2169. * <div id="test">
  2170. *
  2171. * </div>
  2172. * <script>
  2173. * //output: true
  2174. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2175. * </script>
  2176. * ```
  2177. */
  2178. isWhitespace:function (node) {
  2179. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2180. },
  2181. /**
  2182. * 获取元素element相对于viewport的位置坐标
  2183. * @method getXY
  2184. * @param { Node } element 需要计算位置的节点对象
  2185. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2186. * y代表垂直偏移距离。
  2187. *
  2188. * @example
  2189. * ```javascript
  2190. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2191. * //output: test的坐标为: 12, 24
  2192. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2193. * ```
  2194. */
  2195. getXY:function (element) {
  2196. var x = 0, y = 0;
  2197. while (element.offsetParent) {
  2198. y += element.offsetTop;
  2199. x += element.offsetLeft;
  2200. element = element.offsetParent;
  2201. }
  2202. return { 'x':x, 'y':y};
  2203. },
  2204. /**
  2205. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2206. * @method on
  2207. * @param { Node } element 需要绑定事件的节点对象
  2208. * @param { String } type 绑定的事件类型
  2209. * @param { Function } handler 事件处理器
  2210. * @example
  2211. * ```javascript
  2212. * UE.dom.domUtils.on(document.body,"click",function(e){
  2213. * //e为事件对象,this为被点击元素对戏那个
  2214. * });
  2215. * ```
  2216. */
  2217. /**
  2218. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2219. * @method on
  2220. * @param { Node } element 需要绑定事件的节点对象
  2221. * @param { Array } type 绑定的事件类型数组
  2222. * @param { Function } handler 事件处理器
  2223. * @example
  2224. * ```javascript
  2225. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2226. * //evt为事件对象,this为被点击元素对象
  2227. * });
  2228. * ```
  2229. */
  2230. on:function (element, type, handler) {
  2231. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2232. k = types.length;
  2233. if (k) while (k--) {
  2234. type = types[k];
  2235. if (element.addEventListener) {
  2236. element.addEventListener(type, handler, false);
  2237. } else {
  2238. if (!handler._d) {
  2239. handler._d = {
  2240. els : []
  2241. };
  2242. }
  2243. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2244. if (!handler._d[key] || index == -1) {
  2245. if(index == -1){
  2246. handler._d.els.push(element);
  2247. }
  2248. if(!handler._d[key]){
  2249. handler._d[key] = function (evt) {
  2250. return handler.call(evt.srcElement, evt || window.event);
  2251. };
  2252. }
  2253. element.attachEvent('on' + type, handler._d[key]);
  2254. }
  2255. }
  2256. }
  2257. element = null;
  2258. },
  2259. /**
  2260. * 解除DOM事件绑定
  2261. * @method un
  2262. * @param { Node } element 需要解除事件绑定的节点对象
  2263. * @param { String } type 需要接触绑定的事件类型
  2264. * @param { Function } handler 对应的事件处理器
  2265. * @example
  2266. * ```javascript
  2267. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2268. * //evt为事件对象,this为被点击元素对象
  2269. * });
  2270. * ```
  2271. */
  2272. /**
  2273. * 解除DOM事件绑定
  2274. * @method un
  2275. * @param { Node } element 需要解除事件绑定的节点对象
  2276. * @param { Array } type 需要接触绑定的事件类型数组
  2277. * @param { Function } handler 对应的事件处理器
  2278. * @example
  2279. * ```javascript
  2280. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2281. * //evt为事件对象,this为被点击元素对象
  2282. * });
  2283. * ```
  2284. */
  2285. un:function (element, type, handler) {
  2286. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2287. k = types.length;
  2288. if (k) while (k--) {
  2289. type = types[k];
  2290. if (element.removeEventListener) {
  2291. element.removeEventListener(type, handler, false);
  2292. } else {
  2293. var key = type + handler.toString();
  2294. try{
  2295. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2296. }catch(e){}
  2297. if (handler._d && handler._d[key]) {
  2298. var index = utils.indexOf(handler._d.els,element);
  2299. if(index!=-1){
  2300. handler._d.els.splice(index,1);
  2301. }
  2302. handler._d.els.length == 0 && delete handler._d[key];
  2303. }
  2304. }
  2305. }
  2306. },
  2307. /**
  2308. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2309. * @method isSameElement
  2310. * @param { Node } nodeA 需要比较的节点
  2311. * @param { Node } nodeB 需要比较的节点
  2312. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2313. * @example
  2314. * ```html
  2315. * <span style="font-size:12px">ssss</span>
  2316. * <span style="font-size:12px">bbbbb</span>
  2317. * <span style="font-size:13px">ssss</span>
  2318. * <span style="font-size:14px">bbbbb</span>
  2319. *
  2320. * <script>
  2321. *
  2322. * var nodes = document.getElementsByTagName( "span" );
  2323. *
  2324. * //output: true
  2325. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2326. *
  2327. * //output: false
  2328. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2329. *
  2330. * </script>
  2331. * ```
  2332. */
  2333. isSameElement:function (nodeA, nodeB) {
  2334. if (nodeA.tagName != nodeB.tagName) {
  2335. return false;
  2336. }
  2337. var thisAttrs = nodeA.attributes,
  2338. otherAttrs = nodeB.attributes;
  2339. if (!ie && thisAttrs.length != otherAttrs.length) {
  2340. return false;
  2341. }
  2342. var attrA, attrB, al = 0, bl = 0;
  2343. for (var i = 0; attrA = thisAttrs[i++];) {
  2344. if (attrA.nodeName == 'style') {
  2345. if (attrA.specified) {
  2346. al++;
  2347. }
  2348. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2349. continue;
  2350. } else {
  2351. return false;
  2352. }
  2353. }
  2354. if (ie) {
  2355. if (attrA.specified) {
  2356. al++;
  2357. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2358. } else {
  2359. continue;
  2360. }
  2361. } else {
  2362. attrB = nodeB.attributes[attrA.nodeName];
  2363. }
  2364. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2365. return false;
  2366. }
  2367. }
  2368. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2369. if (ie) {
  2370. for (i = 0; attrB = otherAttrs[i++];) {
  2371. if (attrB.specified) {
  2372. bl++;
  2373. }
  2374. }
  2375. if (al != bl) {
  2376. return false;
  2377. }
  2378. }
  2379. return true;
  2380. },
  2381. /**
  2382. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2383. * @method isSameStyle
  2384. * @param { Node } nodeA 需要比较的节点
  2385. * @param { Node } nodeB 需要比较的节点
  2386. * @return { Boolean } 两个节点是否具有相同的style属性值
  2387. * @example
  2388. * ```html
  2389. * <span style="font-size:12px">ssss</span>
  2390. * <span style="font-size:12px">bbbbb</span>
  2391. * <span style="font-size:13px">ssss</span>
  2392. * <span style="font-size:14px">bbbbb</span>
  2393. *
  2394. * <script>
  2395. *
  2396. * var nodes = document.getElementsByTagName( "span" );
  2397. *
  2398. * //output: true
  2399. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2400. *
  2401. * //output: false
  2402. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2403. *
  2404. * </script>
  2405. * ```
  2406. */
  2407. isSameStyle:function (nodeA, nodeB) {
  2408. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2409. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2410. if (browser.opera) {
  2411. styleA = nodeA.style;
  2412. styleB = nodeB.style;
  2413. if (styleA.length != styleB.length)
  2414. return false;
  2415. for (var p in styleA) {
  2416. if (/^(\d+|csstext)$/i.test(p)) {
  2417. continue;
  2418. }
  2419. if (styleA[p] != styleB[p]) {
  2420. return false;
  2421. }
  2422. }
  2423. return true;
  2424. }
  2425. if (!styleA || !styleB) {
  2426. return styleA == styleB;
  2427. }
  2428. styleA = styleA.split(';');
  2429. styleB = styleB.split(';');
  2430. if (styleA.length != styleB.length) {
  2431. return false;
  2432. }
  2433. for (var i = 0, ci; ci = styleA[i++];) {
  2434. if (utils.indexOf(styleB, ci) == -1) {
  2435. return false;
  2436. }
  2437. }
  2438. return true;
  2439. },
  2440. /**
  2441. * 检查节点node是否为block元素
  2442. * @method isBlockElm
  2443. * @param { Node } node 需要检测的节点对象
  2444. * @return { Boolean } 是否是block元素节点
  2445. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2446. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2447. * @example
  2448. * ```html
  2449. * <span id="test1" style="display: block"></span>
  2450. * <span id="test2"></span>
  2451. * <div id="test3" style="display: inline"></div>
  2452. *
  2453. * <script>
  2454. *
  2455. * //output: true
  2456. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2457. *
  2458. * //output: false
  2459. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2460. *
  2461. * //output: true
  2462. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2463. *
  2464. * </script>
  2465. * ```
  2466. */
  2467. isBlockElm:function (node) {
  2468. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2469. },
  2470. /**
  2471. * 检测node节点是否为body节点
  2472. * @method isBody
  2473. * @param { Element } node 需要检测的dom元素
  2474. * @return { Boolean } 给定的元素是否是body元素
  2475. * @example
  2476. * ```javascript
  2477. * //output: true
  2478. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2479. * ```
  2480. */
  2481. isBody:function (node) {
  2482. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2483. },
  2484. /**
  2485. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2486. * 拆分形成的两个节点之间是node节点
  2487. * @method breakParent
  2488. * @param { Node } node 作为分界的节点对象
  2489. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2490. * @return { Node } 给定的node分界节点
  2491. * @example
  2492. * ```javascript
  2493. *
  2494. * var node = document.createElement("span"),
  2495. * wrapNode = document.createElement( "div" ),
  2496. * parent = document.createElement("p");
  2497. *
  2498. * parent.appendChild( node );
  2499. * wrapNode.appendChild( parent );
  2500. *
  2501. * //拆分前
  2502. * //output: <p><span></span></p>
  2503. * console.log( wrapNode.innerHTML );
  2504. *
  2505. *
  2506. * UE.dom.domUtils.breakParent( node, parent );
  2507. * //拆分后
  2508. * //output: <p></p><span></span><p></p>
  2509. * console.log( wrapNode.innerHTML );
  2510. *
  2511. * ```
  2512. */
  2513. breakParent:function (node, parent) {
  2514. var tmpNode,
  2515. parentClone = node,
  2516. clone = node,
  2517. leftNodes,
  2518. rightNodes;
  2519. do {
  2520. parentClone = parentClone.parentNode;
  2521. if (leftNodes) {
  2522. tmpNode = parentClone.cloneNode(false);
  2523. tmpNode.appendChild(leftNodes);
  2524. leftNodes = tmpNode;
  2525. tmpNode = parentClone.cloneNode(false);
  2526. tmpNode.appendChild(rightNodes);
  2527. rightNodes = tmpNode;
  2528. } else {
  2529. leftNodes = parentClone.cloneNode(false);
  2530. rightNodes = leftNodes.cloneNode(false);
  2531. }
  2532. while (tmpNode = clone.previousSibling) {
  2533. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2534. }
  2535. while (tmpNode = clone.nextSibling) {
  2536. rightNodes.appendChild(tmpNode);
  2537. }
  2538. clone = parentClone;
  2539. } while (parent !== parentClone);
  2540. tmpNode = parent.parentNode;
  2541. tmpNode.insertBefore(leftNodes, parent);
  2542. tmpNode.insertBefore(rightNodes, parent);
  2543. tmpNode.insertBefore(node, rightNodes);
  2544. domUtils.remove(parent);
  2545. return node;
  2546. },
  2547. /**
  2548. * 检查节点node是否是空inline节点
  2549. * @method isEmptyInlineElement
  2550. * @param { Node } node 需要检测的节点对象
  2551. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2552. * @example
  2553. * ```html
  2554. * <b><i></i></b> => 1
  2555. * <b><i></i><u></u></b> => 1
  2556. * <b></b> => 1
  2557. * <b>xx<i></i></b> => 0
  2558. * ```
  2559. */
  2560. isEmptyInlineElement:function (node) {
  2561. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2562. return 0;
  2563. }
  2564. node = node.firstChild;
  2565. while (node) {
  2566. //如果是创建的bookmark就跳过
  2567. if (domUtils.isBookmarkNode(node)) {
  2568. return 0;
  2569. }
  2570. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2571. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2572. ) {
  2573. return 0;
  2574. }
  2575. node = node.nextSibling;
  2576. }
  2577. return 1;
  2578. },
  2579. /**
  2580. * 删除node节点下首尾两端的空白文本子节点
  2581. * @method trimWhiteTextNode
  2582. * @param { Element } node 需要执行删除操作的元素对象
  2583. * @example
  2584. * ```javascript
  2585. * var node = document.createElement("div");
  2586. *
  2587. * node.appendChild( document.createTextNode( "" ) );
  2588. *
  2589. * node.appendChild( document.createElement("div") );
  2590. *
  2591. * node.appendChild( document.createTextNode( "" ) );
  2592. *
  2593. * //3
  2594. * console.log( node.childNodes.length );
  2595. *
  2596. * UE.dom.domUtils.trimWhiteTextNode( node );
  2597. *
  2598. * //1
  2599. * console.log( node.childNodes.length );
  2600. * ```
  2601. */
  2602. trimWhiteTextNode:function (node) {
  2603. function remove(dir) {
  2604. var child;
  2605. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2606. node.removeChild(child);
  2607. }
  2608. }
  2609. remove('firstChild');
  2610. remove('lastChild');
  2611. },
  2612. /*
  2613. * 合并node节点下相同的子节点
  2614. * @name mergeChild
  2615. * @desc
  2616. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2617. * @example
  2618. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2619. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2620. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2621. */
  2622. mergeChild:function (node, tagName, attrs) {
  2623. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2624. for (var i = 0, ci; ci = list[i++];) {
  2625. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2626. continue;
  2627. }
  2628. //span单独处理
  2629. if (ci.tagName.toLowerCase() == 'span') {
  2630. if (node === ci.parentNode) {
  2631. domUtils.trimWhiteTextNode(node);
  2632. if (node.childNodes.length == 1) {
  2633. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2634. domUtils.remove(ci, true);
  2635. continue;
  2636. }
  2637. }
  2638. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2639. if (attrs) {
  2640. var style = attrs.style;
  2641. if (style) {
  2642. style = style.split(';');
  2643. for (var j = 0, s; s = style[j++];) {
  2644. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2645. }
  2646. }
  2647. }
  2648. if (domUtils.isSameStyle(ci, node)) {
  2649. domUtils.remove(ci, true);
  2650. }
  2651. continue;
  2652. }
  2653. if (domUtils.isSameElement(node, ci)) {
  2654. domUtils.remove(ci, true);
  2655. }
  2656. }
  2657. },
  2658. /**
  2659. * 原生方法getElementsByTagName的封装
  2660. * @method getElementsByTagName
  2661. * @param { Node } node 目标节点对象
  2662. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2663. * @return { Array } 符合条件的节点集合
  2664. */
  2665. getElementsByTagName:function (node, name,filter) {
  2666. if(filter && utils.isString(filter)){
  2667. var className = filter;
  2668. filter = function(node){return domUtils.hasClass(node,className)}
  2669. }
  2670. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2671. var arr = [];
  2672. for(var n = 0,ni;ni=name[n++];){
  2673. var list = node.getElementsByTagName(ni);
  2674. for (var i = 0, ci; ci = list[i++];) {
  2675. if(!filter || filter(ci))
  2676. arr.push(ci);
  2677. }
  2678. }
  2679. return arr;
  2680. },
  2681. /**
  2682. * 将节点node提取到父节点上
  2683. * @method mergeToParent
  2684. * @param { Element } node 需要提取的元素对象
  2685. * @example
  2686. * ```html
  2687. * <div id="parent">
  2688. * <div id="sub">
  2689. * <span id="child"></span>
  2690. * </div>
  2691. * </div>
  2692. *
  2693. * <script>
  2694. *
  2695. * var child = document.getElementById( "child" );
  2696. *
  2697. * //output: sub
  2698. * console.log( child.parentNode.id );
  2699. *
  2700. * UE.dom.domUtils.mergeToParent( child );
  2701. *
  2702. * //output: parent
  2703. * console.log( child.parentNode.id );
  2704. *
  2705. * </script>
  2706. * ```
  2707. */
  2708. mergeToParent:function (node) {
  2709. var parent = node.parentNode;
  2710. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2711. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2712. domUtils.trimWhiteTextNode(parent);
  2713. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2714. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2715. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2716. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2717. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2718. parent = parent.parentNode;
  2719. continue;
  2720. } else {
  2721. parent.style.cssText += ";" + node.style.cssText;
  2722. //trace:952 a标签要保持下划线
  2723. if (parent.tagName == 'A') {
  2724. parent.style.textDecoration = 'underline';
  2725. }
  2726. }
  2727. }
  2728. if (parent.tagName != 'A') {
  2729. parent === node.parentNode && domUtils.remove(node, true);
  2730. break;
  2731. }
  2732. }
  2733. parent = parent.parentNode;
  2734. }
  2735. },
  2736. /**
  2737. * 合并节点node的左右兄弟节点
  2738. * @method mergeSibling
  2739. * @param { Element } node 需要合并的目标节点
  2740. * @example
  2741. * ```html
  2742. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2743. *
  2744. * <script>
  2745. * var demoNode = document.getElementById("test");
  2746. * UE.dom.domUtils.mergeSibling( demoNode );
  2747. * //output: xxxxoooxxxx
  2748. * console.log( demoNode.innerHTML );
  2749. * </script>
  2750. * ```
  2751. */
  2752. /**
  2753. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2754. * @method mergeSibling
  2755. * @param { Element } node 需要合并的目标节点
  2756. * @param { Boolean } ignorePre 是否忽略合并左节点
  2757. * @example
  2758. * ```html
  2759. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2760. *
  2761. * <script>
  2762. * var demoNode = document.getElementById("test");
  2763. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2764. * //output: oooxxxx
  2765. * console.log( demoNode.innerHTML );
  2766. * </script>
  2767. * ```
  2768. */
  2769. /**
  2770. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2771. * @method mergeSibling
  2772. * @param { Element } node 需要合并的目标节点
  2773. * @param { Boolean } ignorePre 是否忽略合并左节点
  2774. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2775. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2776. * @example
  2777. * ```html
  2778. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2779. *
  2780. * <script>
  2781. * var demoNode = document.getElementById("test");
  2782. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2783. * //output: xxxxooo
  2784. * console.log( demoNode.innerHTML );
  2785. * </script>
  2786. * ```
  2787. */
  2788. mergeSibling:function (node, ignorePre, ignoreNext) {
  2789. function merge(rtl, start, node) {
  2790. var next;
  2791. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2792. while (next.firstChild) {
  2793. if (start == 'firstChild') {
  2794. node.insertBefore(next.lastChild, node.firstChild);
  2795. } else {
  2796. node.appendChild(next.firstChild);
  2797. }
  2798. }
  2799. domUtils.remove(next);
  2800. }
  2801. }
  2802. !ignorePre && merge('previousSibling', 'firstChild', node);
  2803. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2804. },
  2805. /**
  2806. * 设置节点node及其子节点不会被选中
  2807. * @method unSelectable
  2808. * @param { Element } node 需要执行操作的dom元素
  2809. * @remind 执行该操作后的节点, 将不能被鼠标选中
  2810. * @example
  2811. * ```javascript
  2812. * UE.dom.domUtils.unSelectable( document.body );
  2813. * ```
  2814. */
  2815. unSelectable:ie || browser.opera ? function (node) {
  2816. //for ie9
  2817. node.onselectstart = function () {
  2818. return false;
  2819. };
  2820. node.onclick = node.onkeyup = node.onkeydown = function () {
  2821. return false;
  2822. };
  2823. node.unselectable = 'on';
  2824. node.setAttribute("unselectable", "on");
  2825. for (var i = 0, ci; ci = node.all[i++];) {
  2826. switch (ci.tagName.toLowerCase()) {
  2827. case 'iframe' :
  2828. case 'textarea' :
  2829. case 'input' :
  2830. case 'select' :
  2831. break;
  2832. default :
  2833. ci.unselectable = 'on';
  2834. node.setAttribute("unselectable", "on");
  2835. }
  2836. }
  2837. } : function (node) {
  2838. node.style.MozUserSelect =
  2839. node.style.webkitUserSelect =
  2840. node.style.KhtmlUserSelect = 'none';
  2841. },
  2842. /**
  2843. * 删除节点node上的指定属性名称的属性
  2844. * @method removeAttributes
  2845. * @param { Node } node 需要删除属性的节点对象
  2846. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  2847. * @example
  2848. * ```html
  2849. * <div id="wrap">
  2850. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2851. * </div>
  2852. *
  2853. * <script>
  2854. *
  2855. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  2856. *
  2857. * //output: <span style="font-size:14px;">xxxxx</span>
  2858. * console.log( document.getElementById("wrap").innerHTML );
  2859. *
  2860. * </script>
  2861. * ```
  2862. */
  2863. /**
  2864. * 删除节点node上的指定属性名称的属性
  2865. * @method removeAttributes
  2866. * @param { Node } node 需要删除属性的节点对象
  2867. * @param { Array } attrNames 需要删除的属性名数组
  2868. * @example
  2869. * ```html
  2870. * <div id="wrap">
  2871. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2872. * </div>
  2873. *
  2874. * <script>
  2875. *
  2876. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  2877. *
  2878. * //output: <span style="font-size:14px;">xxxxx</span>
  2879. * console.log( document.getElementById("wrap").innerHTML );
  2880. *
  2881. * </script>
  2882. * ```
  2883. */
  2884. removeAttributes:function (node, attrNames) {
  2885. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  2886. for (var i = 0, ci; ci = attrNames[i++];) {
  2887. ci = attrFix[ci] || ci;
  2888. switch (ci) {
  2889. case 'className':
  2890. node[ci] = '';
  2891. break;
  2892. case 'style':
  2893. node.style.cssText = '';
  2894. !browser.ie && node.removeAttribute(node.getAttribute('style'));
  2895. }
  2896. node.removeAttribute(ci);
  2897. }
  2898. },
  2899. /**
  2900. * 在doc下创建一个标签名为tag,属性为attrs的元素
  2901. * @method createElement
  2902. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  2903. * @param { String } tagName 需要创建的元素的标签名
  2904. * @param { Object } attrs 新创建的元素的属性key-value集合
  2905. * @return { Element } 新创建的元素对象
  2906. * @example
  2907. * ```javascript
  2908. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  2909. * id: 'test'
  2910. * } );
  2911. *
  2912. * //output: DIV
  2913. * console.log( ele.tagName );
  2914. *
  2915. * //output: test
  2916. * console.log( ele.id );
  2917. *
  2918. * ```
  2919. */
  2920. createElement:function (doc, tag, attrs) {
  2921. return domUtils.setAttributes(doc.createElement(tag), attrs)
  2922. },
  2923. /**
  2924. * 为节点node添加属性attrs,attrs为属性键值对
  2925. * @method setAttributes
  2926. * @param { Element } node 需要设置属性的元素对象
  2927. * @param { Object } attrs 需要设置的属性名-值对
  2928. * @return { Element } 设置属性的元素对象
  2929. * @example
  2930. * ```html
  2931. * <span id="test"></span>
  2932. *
  2933. * <script>
  2934. *
  2935. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  2936. * id: 'demo'
  2937. * } );
  2938. *
  2939. * //output: demo
  2940. * console.log( testNode.id );
  2941. *
  2942. * </script>
  2943. *
  2944. */
  2945. setAttributes:function (node, attrs) {
  2946. for (var attr in attrs) {
  2947. if(attrs.hasOwnProperty(attr)){
  2948. var value = attrs[attr];
  2949. switch (attr) {
  2950. case 'class':
  2951. //ie下要这样赋值,setAttribute不起作用
  2952. node.className = value;
  2953. break;
  2954. case 'style' :
  2955. node.style.cssText = node.style.cssText + ";" + value;
  2956. break;
  2957. case 'innerHTML':
  2958. node[attr] = value;
  2959. break;
  2960. case 'value':
  2961. node.value = value;
  2962. break;
  2963. default:
  2964. node.setAttribute(attrFix[attr] || attr, value);
  2965. }
  2966. }
  2967. }
  2968. return node;
  2969. },
  2970. /**
  2971. * 获取元素element经过计算后的样式值
  2972. * @method getComputedStyle
  2973. * @param { Element } element 需要获取样式的元素对象
  2974. * @param { String } styleName 需要获取的样式名
  2975. * @return { String } 获取到的样式值
  2976. * @example
  2977. * ```html
  2978. * <style type="text/css">
  2979. * #test {
  2980. * font-size: 15px;
  2981. * }
  2982. * </style>
  2983. *
  2984. * <span id="test"></span>
  2985. *
  2986. * <script>
  2987. * //output: 15px
  2988. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  2989. * </script>
  2990. * ```
  2991. */
  2992. getComputedStyle:function (element, styleName) {
  2993. //一下的属性单独处理
  2994. var pros = 'width height top left';
  2995. if(pros.indexOf(styleName) > -1){
  2996. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  2997. }
  2998. //忽略文本节点
  2999. if (element.nodeType == 3) {
  3000. element = element.parentNode;
  3001. }
  3002. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3003. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3004. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3005. var span = element.ownerDocument.createElement('span');
  3006. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3007. span.innerHTML = '.';
  3008. element.appendChild(span);
  3009. var result = span.offsetHeight;
  3010. element.removeChild(span);
  3011. span = null;
  3012. return result + 'px';
  3013. }
  3014. try {
  3015. var value = domUtils.getStyle(element, styleName) ||
  3016. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3017. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3018. } catch (e) {
  3019. return "";
  3020. }
  3021. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3022. },
  3023. /**
  3024. * 删除元素element指定的className
  3025. * @method removeClasses
  3026. * @param { Element } ele 需要删除class的元素节点
  3027. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3028. * @example
  3029. * ```html
  3030. * <span id="test" class="test1 test2 test3">xxx</span>
  3031. *
  3032. * <script>
  3033. *
  3034. * var testNode = document.getElementById( "test" );
  3035. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3036. *
  3037. * //output: test3
  3038. * console.log( testNode.className );
  3039. *
  3040. * </script>
  3041. * ```
  3042. */
  3043. /**
  3044. * 删除元素element指定的className
  3045. * @method removeClasses
  3046. * @param { Element } ele 需要删除class的元素节点
  3047. * @param { Array } classNames 需要删除的className数组
  3048. * @example
  3049. * ```html
  3050. * <span id="test" class="test1 test2 test3">xxx</span>
  3051. *
  3052. * <script>
  3053. *
  3054. * var testNode = document.getElementById( "test" );
  3055. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3056. *
  3057. * //output: test3
  3058. * console.log( testNode.className );
  3059. *
  3060. * </script>
  3061. * ```
  3062. */
  3063. removeClasses:function (elm, classNames) {
  3064. classNames = utils.isArray(classNames) ? classNames :
  3065. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3066. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3067. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3068. }
  3069. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3070. if(cls){
  3071. elm.className = cls;
  3072. }else{
  3073. domUtils.removeAttributes(elm,['class']);
  3074. }
  3075. },
  3076. /**
  3077. * 给元素element添加className
  3078. * @method addClass
  3079. * @param { Node } ele 需要增加className的元素
  3080. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3081. * @remind 相同的类名不会被重复添加
  3082. * @example
  3083. * ```html
  3084. * <span id="test" class="cls1 cls2"></span>
  3085. *
  3086. * <script>
  3087. * var testNode = document.getElementById("test");
  3088. *
  3089. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3090. *
  3091. * //output: cl1 cls2 cls3 cls4
  3092. * console.log( testNode.className );
  3093. *
  3094. * <script>
  3095. * ```
  3096. */
  3097. /**
  3098. * 给元素element添加className
  3099. * @method addClass
  3100. * @param { Node } ele 需要增加className的元素
  3101. * @param { Array } classNames 需要添加的className的数组
  3102. * @remind 相同的类名不会被重复添加
  3103. * @example
  3104. * ```html
  3105. * <span id="test" class="cls1 cls2"></span>
  3106. *
  3107. * <script>
  3108. * var testNode = document.getElementById("test");
  3109. *
  3110. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3111. *
  3112. * //output: cl1 cls2 cls3 cls4
  3113. * console.log( testNode.className );
  3114. *
  3115. * <script>
  3116. * ```
  3117. */
  3118. addClass:function (elm, classNames) {
  3119. if(!elm)return;
  3120. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3121. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3122. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3123. cls += ' ' + ci;
  3124. }
  3125. }
  3126. elm.className = utils.trim(cls);
  3127. },
  3128. /**
  3129. * 判断元素element是否包含给定的样式类名className
  3130. * @method hasClass
  3131. * @param { Node } ele 需要检测的元素
  3132. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3133. * @return { Boolean } 元素是否包含所有给定的className
  3134. * @example
  3135. * ```html
  3136. * <span id="test1" class="cls1 cls2"></span>
  3137. *
  3138. * <script>
  3139. * var test1 = document.getElementById("test1");
  3140. *
  3141. * //output: false
  3142. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3143. *
  3144. * //output: true
  3145. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3146. * </script>
  3147. * ```
  3148. */
  3149. /**
  3150. * 判断元素element是否包含给定的样式类名className
  3151. * @method hasClass
  3152. * @param { Node } ele 需要检测的元素
  3153. * @param { Array } classNames 需要检测的className数组
  3154. * @return { Boolean } 元素是否包含所有给定的className
  3155. * @example
  3156. * ```html
  3157. * <span id="test1" class="cls1 cls2"></span>
  3158. *
  3159. * <script>
  3160. * var test1 = document.getElementById("test1");
  3161. *
  3162. * //output: false
  3163. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3164. *
  3165. * //output: true
  3166. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3167. * </script>
  3168. * ```
  3169. */
  3170. hasClass:function (element, className) {
  3171. if(utils.isRegExp(className)){
  3172. return className.test(element.className)
  3173. }
  3174. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3175. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3176. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3177. return false;
  3178. }
  3179. }
  3180. return i - 1 == className.length;
  3181. },
  3182. /**
  3183. * 阻止事件默认行为
  3184. * @method preventDefault
  3185. * @param { Event } evt 需要阻止默认行为的事件对象
  3186. * @example
  3187. * ```javascript
  3188. * UE.dom.domUtils.preventDefault( evt );
  3189. * ```
  3190. */
  3191. preventDefault:function (evt) {
  3192. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3193. },
  3194. /**
  3195. * 删除元素element指定的样式
  3196. * @method removeStyle
  3197. * @param { Element } element 需要删除样式的元素
  3198. * @param { String } styleName 需要删除的样式名
  3199. * @example
  3200. * ```html
  3201. * <span id="test" style="color: red; background: blue;"></span>
  3202. *
  3203. * <script>
  3204. *
  3205. * var testNode = document.getElementById("test");
  3206. *
  3207. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3208. *
  3209. * //output: background: blue;
  3210. * console.log( testNode.style.cssText );
  3211. *
  3212. * </script>
  3213. * ```
  3214. */
  3215. removeStyle:function (element, name) {
  3216. if(browser.ie ){
  3217. //针对color先单独处理一下
  3218. if(name == 'color'){
  3219. name = '(^|;)' + name;
  3220. }
  3221. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3222. }else{
  3223. if (element.style.removeProperty) {
  3224. element.style.removeProperty (name);
  3225. }else {
  3226. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3227. }
  3228. }
  3229. if (!element.style.cssText) {
  3230. domUtils.removeAttributes(element, ['style']);
  3231. }
  3232. },
  3233. /**
  3234. * 获取元素element的style属性的指定值
  3235. * @method getStyle
  3236. * @param { Element } element 需要获取属性值的元素
  3237. * @param { String } styleName 需要获取的style的名称
  3238. * @warning 该方法仅获取元素style属性中所标明的值
  3239. * @return { String } 该元素包含指定的style属性值
  3240. * @example
  3241. * ```html
  3242. * <div id="test" style="color: red;"></div>
  3243. *
  3244. * <script>
  3245. *
  3246. * var testNode = document.getElementById( "test" );
  3247. *
  3248. * //output: red
  3249. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3250. *
  3251. * //output: ""
  3252. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3253. *
  3254. * </script>
  3255. * ```
  3256. */
  3257. getStyle:function (element, name) {
  3258. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3259. return utils.fixColor(name, value);
  3260. },
  3261. /**
  3262. * 为元素element设置样式属性值
  3263. * @method setStyle
  3264. * @param { Element } element 需要设置样式的元素
  3265. * @param { String } styleName 样式名
  3266. * @param { String } styleValue 样式值
  3267. * @example
  3268. * ```html
  3269. * <div id="test"></div>
  3270. *
  3271. * <script>
  3272. *
  3273. * var testNode = document.getElementById( "test" );
  3274. *
  3275. * //output: ""
  3276. * console.log( testNode.style.color );
  3277. *
  3278. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3279. * //output: "red"
  3280. * console.log( testNode.style.color );
  3281. *
  3282. * </script>
  3283. * ```
  3284. */
  3285. setStyle:function (element, name, value) {
  3286. element.style[utils.cssStyleToDomStyle(name)] = value;
  3287. if(!utils.trim(element.style.cssText)){
  3288. this.removeAttributes(element,'style')
  3289. }
  3290. },
  3291. /**
  3292. * 为元素element设置多个样式属性值
  3293. * @method setStyles
  3294. * @param { Element } element 需要设置样式的元素
  3295. * @param { Object } styles 样式名值对
  3296. * @example
  3297. * ```html
  3298. * <div id="test"></div>
  3299. *
  3300. * <script>
  3301. *
  3302. * var testNode = document.getElementById( "test" );
  3303. *
  3304. * //output: ""
  3305. * console.log( testNode.style.color );
  3306. *
  3307. * UE.dom.domUtils.setStyles( testNode, {
  3308. * 'color': 'red'
  3309. * } );
  3310. * //output: "red"
  3311. * console.log( testNode.style.color );
  3312. *
  3313. * </script>
  3314. * ```
  3315. */
  3316. setStyles:function (element, styles) {
  3317. for (var name in styles) {
  3318. if (styles.hasOwnProperty(name)) {
  3319. domUtils.setStyle(element, name, styles[name]);
  3320. }
  3321. }
  3322. },
  3323. /**
  3324. * 删除_moz_dirty属性
  3325. * @private
  3326. * @method removeDirtyAttr
  3327. */
  3328. removeDirtyAttr:function (node) {
  3329. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3330. ci.removeAttribute('_moz_dirty');
  3331. }
  3332. node.removeAttribute('_moz_dirty');
  3333. },
  3334. /**
  3335. * 获取子节点的数量
  3336. * @method getChildCount
  3337. * @param { Element } node 需要检测的元素
  3338. * @return { Number } 给定的node元素的子节点数量
  3339. * @example
  3340. * ```html
  3341. * <div id="test">
  3342. * <span></span>
  3343. * </div>
  3344. *
  3345. * <script>
  3346. *
  3347. * //output: 3
  3348. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3349. *
  3350. * </script>
  3351. * ```
  3352. */
  3353. /**
  3354. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3355. * @method getChildCount
  3356. * @param { Element } node 需要检测的元素
  3357. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3358. * @return { Number } 符合过滤条件的node元素的子节点数量
  3359. * @example
  3360. * ```html
  3361. * <div id="test">
  3362. * <span></span>
  3363. * </div>
  3364. *
  3365. * <script>
  3366. *
  3367. * //output: 1
  3368. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3369. *
  3370. * return node.nodeType === 1;
  3371. *
  3372. * } ) );
  3373. *
  3374. * </script>
  3375. * ```
  3376. */
  3377. getChildCount:function (node, fn) {
  3378. var count = 0, first = node.firstChild;
  3379. fn = fn || function () {
  3380. return 1;
  3381. };
  3382. while (first) {
  3383. if (fn(first)) {
  3384. count++;
  3385. }
  3386. first = first.nextSibling;
  3387. }
  3388. return count;
  3389. },
  3390. /**
  3391. * 判断给定节点是否为空节点
  3392. * @method isEmptyNode
  3393. * @param { Node } node 需要检测的节点对象
  3394. * @return { Boolean } 节点是否为空
  3395. * @example
  3396. * ```javascript
  3397. * UE.dom.domUtils.isEmptyNode( document.body );
  3398. * ```
  3399. */
  3400. isEmptyNode:function (node) {
  3401. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3402. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3403. }) == 0
  3404. },
  3405. clearSelectedArr:function (nodes) {
  3406. var node;
  3407. while (node = nodes.pop()) {
  3408. domUtils.removeAttributes(node, ['class']);
  3409. }
  3410. },
  3411. /**
  3412. * 将显示区域滚动到指定节点的位置
  3413. * @method scrollToView
  3414. * @param {Node} node 节点
  3415. * @param {window} win window对象
  3416. * @param {Number} offsetTop 距离上方的偏移量
  3417. */
  3418. scrollToView:function (node, win, offsetTop) {
  3419. var getViewPaneSize = function () {
  3420. var doc = win.document,
  3421. mode = doc.compatMode == 'CSS1Compat';
  3422. return {
  3423. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3424. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3425. };
  3426. },
  3427. getScrollPosition = function (win) {
  3428. if ('pageXOffset' in win) {
  3429. return {
  3430. x:win.pageXOffset || 0,
  3431. y:win.pageYOffset || 0
  3432. };
  3433. }
  3434. else {
  3435. var doc = win.document;
  3436. return {
  3437. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3438. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3439. };
  3440. }
  3441. };
  3442. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3443. offset += (node.offsetHeight || 0);
  3444. var elementPosition = domUtils.getXY(node);
  3445. offset += elementPosition.y;
  3446. var currentScroll = getScrollPosition(win).y;
  3447. // offset += 50;
  3448. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3449. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3450. }
  3451. },
  3452. /**
  3453. * 判断给定节点是否为br
  3454. * @method isBr
  3455. * @param { Node } node 需要判断的节点对象
  3456. * @return { Boolean } 给定的节点是否是br节点
  3457. */
  3458. isBr:function (node) {
  3459. return node.nodeType == 1 && node.tagName == 'BR';
  3460. },
  3461. /**
  3462. * 判断给定的节点是否是一个“填充”节点
  3463. * @private
  3464. * @method isFillChar
  3465. * @param { Node } node 需要判断的节点
  3466. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3467. * @returns { Boolean } 节点是否是填充节点
  3468. */
  3469. isFillChar:function (node,isInStart) {
  3470. if(node.nodeType != 3)
  3471. return false;
  3472. var text = node.nodeValue;
  3473. if(isInStart){
  3474. return new RegExp('^' + domUtils.fillChar).test(text)
  3475. }
  3476. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3477. },
  3478. isStartInblock:function (range) {
  3479. var tmpRange = range.cloneRange(),
  3480. flag = 0,
  3481. start = tmpRange.startContainer,
  3482. tmp;
  3483. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3484. start = start.childNodes[tmpRange.startOffset];
  3485. var pre = start.previousSibling;
  3486. while(pre && domUtils.isFillChar(pre)){
  3487. start = pre;
  3488. pre = pre.previousSibling;
  3489. }
  3490. }
  3491. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3492. tmpRange.setStartBefore(start);
  3493. start = tmpRange.startContainer;
  3494. }
  3495. while (start && domUtils.isFillChar(start)) {
  3496. tmp = start;
  3497. start = start.previousSibling
  3498. }
  3499. if (tmp) {
  3500. tmpRange.setStartBefore(tmp);
  3501. start = tmpRange.startContainer;
  3502. }
  3503. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3504. tmpRange.setStart(start, 0).collapse(true);
  3505. }
  3506. while (!tmpRange.startOffset) {
  3507. start = tmpRange.startContainer;
  3508. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3509. flag = 1;
  3510. break;
  3511. }
  3512. var pre = tmpRange.startContainer.previousSibling,
  3513. tmpNode;
  3514. if (!pre) {
  3515. tmpRange.setStartBefore(tmpRange.startContainer);
  3516. } else {
  3517. while (pre && domUtils.isFillChar(pre)) {
  3518. tmpNode = pre;
  3519. pre = pre.previousSibling;
  3520. }
  3521. if (tmpNode) {
  3522. tmpRange.setStartBefore(tmpNode);
  3523. } else {
  3524. tmpRange.setStartBefore(tmpRange.startContainer);
  3525. }
  3526. }
  3527. }
  3528. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3529. },
  3530. /**
  3531. * 判断给定的元素是否是一个空元素
  3532. * @method isEmptyBlock
  3533. * @param { Element } node 需要判断的元素
  3534. * @return { Boolean } 是否是空元素
  3535. * @example
  3536. * ```html
  3537. * <div id="test"></div>
  3538. *
  3539. * <script>
  3540. * //output: true
  3541. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3542. * </script>
  3543. * ```
  3544. */
  3545. /**
  3546. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3547. * @method isEmptyBlock
  3548. * @param { Element } node 需要判断的元素
  3549. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3550. * @return { Boolean } 是否是空元素
  3551. */
  3552. isEmptyBlock:function (node,reg) {
  3553. if(node.nodeType != 1)
  3554. return 0;
  3555. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  3556. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3557. return 0;
  3558. }
  3559. for (var n in dtd.$isNotEmpty) {
  3560. if (node.getElementsByTagName(n).length) {
  3561. return 0;
  3562. }
  3563. }
  3564. return 1;
  3565. },
  3566. /**
  3567. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3568. * @method setViewportOffset
  3569. * @param { Element } element 需要设置偏移量的元素
  3570. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3571. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3572. * offset.top的距离
  3573. * @example
  3574. * ```html
  3575. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3576. *
  3577. * <script>
  3578. *
  3579. * var testNode = document.getElementById("test");
  3580. *
  3581. * UE.dom.domUtils.setViewportOffset( testNode, {
  3582. * left: 200,
  3583. * top: 50
  3584. * } );
  3585. *
  3586. * //output: top: 300px; left: 100px; position: absolute;
  3587. * console.log( testNode.style.cssText );
  3588. *
  3589. * </script>
  3590. * ```
  3591. */
  3592. setViewportOffset:function (element, offset) {
  3593. var left = parseInt(element.style.left) | 0;
  3594. var top = parseInt(element.style.top) | 0;
  3595. var rect = element.getBoundingClientRect();
  3596. var offsetLeft = offset.left - rect.left;
  3597. var offsetTop = offset.top - rect.top;
  3598. if (offsetLeft) {
  3599. element.style.left = left + offsetLeft + 'px';
  3600. }
  3601. if (offsetTop) {
  3602. element.style.top = top + offsetTop + 'px';
  3603. }
  3604. },
  3605. /**
  3606. * 用“填充字符”填充节点
  3607. * @method fillNode
  3608. * @private
  3609. * @param { DomDocument } doc 填充的节点所在的docment对象
  3610. * @param { Node } node 需要填充的节点对象
  3611. * @example
  3612. * ```html
  3613. * <div id="test"></div>
  3614. *
  3615. * <script>
  3616. * var testNode = document.getElementById("test");
  3617. *
  3618. * //output: 0
  3619. * console.log( testNode.childNodes.length );
  3620. *
  3621. * UE.dom.domUtils.fillNode( document, testNode );
  3622. *
  3623. * //output: 1
  3624. * console.log( testNode.childNodes.length );
  3625. *
  3626. * </script>
  3627. * ```
  3628. */
  3629. fillNode:function (doc, node) {
  3630. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3631. node.innerHTML = '';
  3632. node.appendChild(tmpNode);
  3633. },
  3634. /**
  3635. * 把节点src的所有子节点追加到另一个节点tag上去
  3636. * @method moveChild
  3637. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3638. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3639. * @example
  3640. * ```html
  3641. * <div id="test1">
  3642. * <span></span>
  3643. * </div>
  3644. * <div id="test2">
  3645. * <div></div>
  3646. * </div>
  3647. *
  3648. * <script>
  3649. *
  3650. * var test1 = document.getElementById("test1"),
  3651. * test2 = document.getElementById("test2");
  3652. *
  3653. * UE.dom.domUtils.moveChild( test1, test2 );
  3654. *
  3655. * //output: ""(空字符串)
  3656. * console.log( test1.innerHTML );
  3657. *
  3658. * //output: "<div></div><span></span>"
  3659. * console.log( test2.innerHTML );
  3660. *
  3661. * </script>
  3662. * ```
  3663. */
  3664. /**
  3665. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3666. * @method moveChild
  3667. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3668. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3669. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3670. * @example
  3671. * ```html
  3672. * <div id="test1">
  3673. * <span></span>
  3674. * </div>
  3675. * <div id="test2">
  3676. * <div></div>
  3677. * </div>
  3678. *
  3679. * <script>
  3680. *
  3681. * var test1 = document.getElementById("test1"),
  3682. * test2 = document.getElementById("test2");
  3683. *
  3684. * UE.dom.domUtils.moveChild( test1, test2, true );
  3685. *
  3686. * //output: ""(空字符串)
  3687. * console.log( test1.innerHTML );
  3688. *
  3689. * //output: "<span></span><div></div>"
  3690. * console.log( test2.innerHTML );
  3691. *
  3692. * </script>
  3693. * ```
  3694. */
  3695. moveChild:function (src, tag, dir) {
  3696. while (src.firstChild) {
  3697. if (dir && tag.firstChild) {
  3698. tag.insertBefore(src.lastChild, tag.firstChild);
  3699. } else {
  3700. tag.appendChild(src.firstChild);
  3701. }
  3702. }
  3703. },
  3704. /**
  3705. * 判断节点的标签上是否不存在任何属性
  3706. * @method hasNoAttributes
  3707. * @private
  3708. * @param { Node } node 需要检测的节点对象
  3709. * @return { Boolean } 节点是否不包含任何属性
  3710. * @example
  3711. * ```html
  3712. * <div id="test"><span>xxxx</span></div>
  3713. *
  3714. * <script>
  3715. *
  3716. * //output: false
  3717. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3718. *
  3719. * //output: true
  3720. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3721. *
  3722. * </script>
  3723. * ```
  3724. */
  3725. hasNoAttributes:function (node) {
  3726. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3727. },
  3728. /**
  3729. * 检测节点是否是UEditor所使用的辅助节点
  3730. * @method isCustomeNode
  3731. * @private
  3732. * @param { Node } node 需要检测的节点
  3733. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3734. * @return { Boolean } 给定的节点是否是一个辅助节点
  3735. */
  3736. isCustomeNode:function (node) {
  3737. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3738. },
  3739. /**
  3740. * 检测节点的标签是否是给定的标签
  3741. * @method isTagNode
  3742. * @param { Node } node 需要检测的节点对象
  3743. * @param { String } tagName 标签
  3744. * @return { Boolean } 节点的标签是否是给定的标签
  3745. * @example
  3746. * ```html
  3747. * <div id="test"></div>
  3748. *
  3749. * <script>
  3750. *
  3751. * //output: true
  3752. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3753. *
  3754. * </script>
  3755. * ```
  3756. */
  3757. isTagNode:function (node, tagNames) {
  3758. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3759. },
  3760. /**
  3761. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3762. * @method filterNodeList
  3763. * @param { Array } nodeList 需要过滤的节点数组
  3764. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3765. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3766. * @example
  3767. * ```javascript
  3768. * var divNodes = document.getElementsByTagName("div");
  3769. * divNodes = [].slice.call( divNodes, 0 );
  3770. *
  3771. * //output: null
  3772. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3773. * return node.tagName.toLowerCase() !== 'div';
  3774. * } ) );
  3775. * ```
  3776. */
  3777. /**
  3778. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3779. * @method filterNodeList
  3780. * @param { Array } nodeList 需要过滤的节点数组
  3781. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3782. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3783. * @example
  3784. * ```javascript
  3785. * var divNodes = document.getElementsByTagName("div");
  3786. * divNodes = [].slice.call( divNodes, 0 );
  3787. *
  3788. * //output: null
  3789. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3790. * ```
  3791. */
  3792. /**
  3793. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3794. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3795. * @method filterNodeList
  3796. * @param { Array } nodeList 需要过滤的节点数组
  3797. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3798. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3799. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3800. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3801. * @example
  3802. * ```javascript
  3803. * var divNodes = document.getElementsByTagName("div");
  3804. * divNodes = [].slice.call( divNodes, 0 );
  3805. *
  3806. * //output: 3(假定有3个div)
  3807. * console.log( divNodes.length );
  3808. *
  3809. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3810. * return node.tagName.toLowerCase() === 'div';
  3811. * }, true );
  3812. *
  3813. * //output: 3
  3814. * console.log( nodes.length );
  3815. *
  3816. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3817. * return node.tagName.toLowerCase() === 'div';
  3818. * }, false );
  3819. *
  3820. * //output: div
  3821. * console.log( node.nodeName );
  3822. * ```
  3823. */
  3824. filterNodeList : function(nodelist,filter,forAll){
  3825. var results = [];
  3826. if(!utils .isFunction(filter)){
  3827. var str = filter;
  3828. filter = function(n){
  3829. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  3830. };
  3831. }
  3832. utils.each(nodelist,function(n){
  3833. filter(n) && results.push(n)
  3834. });
  3835. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  3836. },
  3837. /**
  3838. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  3839. * @method isInNodeEndBoundary
  3840. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  3841. * @param node 需要检测的节点对象
  3842. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  3843. */
  3844. isInNodeEndBoundary : function (rng,node){
  3845. var start = rng.startContainer;
  3846. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  3847. return 0;
  3848. }
  3849. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  3850. return 0;
  3851. }
  3852. while(start !== node){
  3853. if(start.nextSibling){
  3854. return 0
  3855. };
  3856. start = start.parentNode;
  3857. }
  3858. return 1;
  3859. },
  3860. isBoundaryNode : function (node,dir){
  3861. var tmp;
  3862. while(!domUtils.isBody(node)){
  3863. tmp = node;
  3864. node = node.parentNode;
  3865. if(tmp !== node[dir]){
  3866. return false;
  3867. }
  3868. }
  3869. return true;
  3870. }
  3871. };
  3872. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  3873. /**
  3874. * Range封装
  3875. * @file
  3876. * @module UE.dom
  3877. * @class Range
  3878. * @since 1.2.6.1
  3879. */
  3880. /**
  3881. * dom操作封装
  3882. * @unfile
  3883. * @module UE.dom
  3884. */
  3885. /**
  3886. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  3887. * @unfile
  3888. * @module UE.dom
  3889. * @class Range
  3890. */
  3891. (function () {
  3892. var guid = 0,
  3893. fillChar = domUtils.fillChar,
  3894. fillData;
  3895. /*
  3896. * 更新range的collapse状态
  3897. * @param {Range} range range对象
  3898. */
  3899. function updateCollapse(range) {
  3900. range.collapsed =
  3901. range.startContainer && range.endContainer &&
  3902. range.startContainer === range.endContainer &&
  3903. range.startOffset == range.endOffset;
  3904. }
  3905. function selectOneNode(rng){
  3906. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  3907. }
  3908. function setEndPoint(toStart, node, offset, range) {
  3909. //如果node是自闭合标签要处理
  3910. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  3911. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  3912. node = node.parentNode;
  3913. }
  3914. if (toStart) {
  3915. range.startContainer = node;
  3916. range.startOffset = offset;
  3917. if (!range.endContainer) {
  3918. range.collapse(true);
  3919. }
  3920. } else {
  3921. range.endContainer = node;
  3922. range.endOffset = offset;
  3923. if (!range.startContainer) {
  3924. range.collapse(false);
  3925. }
  3926. }
  3927. updateCollapse(range);
  3928. return range;
  3929. }
  3930. function execContentsAction(range, action) {
  3931. //调整边界
  3932. //range.includeBookmark();
  3933. var start = range.startContainer,
  3934. end = range.endContainer,
  3935. startOffset = range.startOffset,
  3936. endOffset = range.endOffset,
  3937. doc = range.document,
  3938. frag = doc.createDocumentFragment(),
  3939. tmpStart, tmpEnd;
  3940. if (start.nodeType == 1) {
  3941. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  3942. }
  3943. if (end.nodeType == 1) {
  3944. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  3945. }
  3946. if (start === end && start.nodeType == 3) {
  3947. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  3948. //is not clone
  3949. if (action) {
  3950. start.deleteData(startOffset, endOffset - startOffset);
  3951. range.collapse(true);
  3952. }
  3953. return frag;
  3954. }
  3955. var current, currentLevel, clone = frag,
  3956. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  3957. for (var i = 0; startParents[i] == endParents[i];) {
  3958. i++;
  3959. }
  3960. for (var j = i, si; si = startParents[j]; j++) {
  3961. current = si.nextSibling;
  3962. if (si == start) {
  3963. if (!tmpStart) {
  3964. if (range.startContainer.nodeType == 3) {
  3965. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  3966. //is not clone
  3967. if (action) {
  3968. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  3969. }
  3970. } else {
  3971. clone.appendChild(!action ? start.cloneNode(true) : start);
  3972. }
  3973. }
  3974. } else {
  3975. currentLevel = si.cloneNode(false);
  3976. clone.appendChild(currentLevel);
  3977. }
  3978. while (current) {
  3979. if (current === end || current === endParents[j]) {
  3980. break;
  3981. }
  3982. si = current.nextSibling;
  3983. clone.appendChild(!action ? current.cloneNode(true) : current);
  3984. current = si;
  3985. }
  3986. clone = currentLevel;
  3987. }
  3988. clone = frag;
  3989. if (!startParents[i]) {
  3990. clone.appendChild(startParents[i - 1].cloneNode(false));
  3991. clone = clone.firstChild;
  3992. }
  3993. for (var j = i, ei; ei = endParents[j]; j++) {
  3994. current = ei.previousSibling;
  3995. if (ei == end) {
  3996. if (!tmpEnd && range.endContainer.nodeType == 3) {
  3997. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  3998. //is not clone
  3999. if (action) {
  4000. end.deleteData(0, endOffset);
  4001. }
  4002. }
  4003. } else {
  4004. currentLevel = ei.cloneNode(false);
  4005. clone.appendChild(currentLevel);
  4006. }
  4007. //如果两端同级,右边第一次已经被开始做了
  4008. if (j != i || !startParents[i]) {
  4009. while (current) {
  4010. if (current === start) {
  4011. break;
  4012. }
  4013. ei = current.previousSibling;
  4014. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4015. current = ei;
  4016. }
  4017. }
  4018. clone = currentLevel;
  4019. }
  4020. if (action) {
  4021. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4022. }
  4023. tmpStart && domUtils.remove(tmpStart);
  4024. tmpEnd && domUtils.remove(tmpEnd);
  4025. return frag;
  4026. }
  4027. /**
  4028. * 创建一个跟document绑定的空的Range实例
  4029. * @constructor
  4030. * @param { Document } document 新建的选区所属的文档对象
  4031. */
  4032. /**
  4033. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4034. */
  4035. /**
  4036. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4037. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4038. */
  4039. /**
  4040. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4041. */
  4042. /**
  4043. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4044. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4045. */
  4046. /**
  4047. * @property { Boolean } collapsed 当前Range是否闭合
  4048. * @default true
  4049. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4050. */
  4051. /**
  4052. * @property { Document } document 当前Range所属的Document对象
  4053. * @remind 不同range的的document属性可以是不同的
  4054. */
  4055. var Range = dom.Range = function (document) {
  4056. var me = this;
  4057. me.startContainer =
  4058. me.startOffset =
  4059. me.endContainer =
  4060. me.endOffset = null;
  4061. me.document = document;
  4062. me.collapsed = true;
  4063. };
  4064. /*
  4065. * 删除fillData
  4066. * @param doc
  4067. * @param excludeNode
  4068. */
  4069. function removeFillData(doc, excludeNode) {
  4070. try {
  4071. if (fillData && domUtils.inDoc(fillData, doc)) {
  4072. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4073. var tmpNode = fillData.parentNode;
  4074. domUtils.remove(fillData);
  4075. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4076. //safari的contains有bug
  4077. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4078. ) {
  4079. fillData = tmpNode.parentNode;
  4080. domUtils.remove(tmpNode);
  4081. tmpNode = fillData;
  4082. }
  4083. } else {
  4084. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4085. }
  4086. }
  4087. } catch (e) {
  4088. }
  4089. }
  4090. /*
  4091. * @param node
  4092. * @param dir
  4093. */
  4094. function mergeSibling(node, dir) {
  4095. var tmpNode;
  4096. node = node[dir];
  4097. while (node && domUtils.isFillChar(node)) {
  4098. tmpNode = node[dir];
  4099. domUtils.remove(node);
  4100. node = tmpNode;
  4101. }
  4102. }
  4103. Range.prototype = {
  4104. /**
  4105. * 克隆选区的内容到一个DocumentFragment里
  4106. * @method cloneContents
  4107. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4108. * @example
  4109. * ```html
  4110. * <body>
  4111. * <!-- 中括号表示选区 -->
  4112. * <b>x<i>x[x</i>xx]x</b>
  4113. *
  4114. * <script>
  4115. * //range是已选中的选区
  4116. * var fragment = range.cloneContents(),
  4117. * node = document.createElement("div");
  4118. *
  4119. * node.appendChild( fragment );
  4120. *
  4121. * //output: <i>x</i>xx
  4122. * console.log( node.innerHTML );
  4123. *
  4124. * </script>
  4125. * </body>
  4126. * ```
  4127. */
  4128. cloneContents:function () {
  4129. return this.collapsed ? null : execContentsAction(this, 0);
  4130. },
  4131. /**
  4132. * 删除当前选区范围中的所有内容
  4133. * @method deleteContents
  4134. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4135. * @return { UE.dom.Range } 当前操作的Range对象
  4136. * @example
  4137. * ```html
  4138. * <body>
  4139. * <!-- 中括号表示选区 -->
  4140. * <b>x<i>x[x</i>xx]x</b>
  4141. *
  4142. * <script>
  4143. * //range是已选中的选区
  4144. * range.deleteContents();
  4145. *
  4146. * //竖线表示闭合后的选区位置
  4147. * //output: <b>x<i>x</i>|x</b>
  4148. * console.log( document.body.innerHTML );
  4149. *
  4150. * //此时, range的各项属性为
  4151. * //output: B
  4152. * console.log( range.startContainer.tagName );
  4153. * //output: 2
  4154. * console.log( range.startOffset );
  4155. * //output: B
  4156. * console.log( range.endContainer.tagName );
  4157. * //output: 2
  4158. * console.log( range.endOffset );
  4159. * //output: true
  4160. * console.log( range.collapsed );
  4161. *
  4162. * </script>
  4163. * </body>
  4164. * ```
  4165. */
  4166. deleteContents:function () {
  4167. var txt;
  4168. if (!this.collapsed) {
  4169. execContentsAction(this, 1);
  4170. }
  4171. if (browser.webkit) {
  4172. txt = this.startContainer;
  4173. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4174. this.setStartBefore(txt).collapse(true);
  4175. domUtils.remove(txt);
  4176. }
  4177. }
  4178. return this;
  4179. },
  4180. /**
  4181. * 将当前选区的内容提取到一个DocumentFragment里
  4182. * @method extractContents
  4183. * @remind 执行该操作后, 选区将变成闭合状态
  4184. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4185. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4186. * @example
  4187. * ```html
  4188. * <body>
  4189. * <!-- 中括号表示选区 -->
  4190. * <b>x<i>x[x</i>xx]x</b>
  4191. *
  4192. * <script>
  4193. * //range是已选中的选区
  4194. * var fragment = range.extractContents(),
  4195. * node = document.createElement( "div" );
  4196. *
  4197. * node.appendChild( fragment );
  4198. *
  4199. * //竖线表示闭合后的选区位置
  4200. *
  4201. * //output: <b>x<i>x</i>|x</b>
  4202. * console.log( document.body.innerHTML );
  4203. * //output: <i>x</i>xx
  4204. * console.log( node.innerHTML );
  4205. *
  4206. * //此时, range的各项属性为
  4207. * //output: B
  4208. * console.log( range.startContainer.tagName );
  4209. * //output: 2
  4210. * console.log( range.startOffset );
  4211. * //output: B
  4212. * console.log( range.endContainer.tagName );
  4213. * //output: 2
  4214. * console.log( range.endOffset );
  4215. * //output: true
  4216. * console.log( range.collapsed );
  4217. *
  4218. * </script>
  4219. * </body>
  4220. */
  4221. extractContents:function () {
  4222. return this.collapsed ? null : execContentsAction(this, 2);
  4223. },
  4224. /**
  4225. * 设置Range的开始容器节点和偏移量
  4226. * @method setStart
  4227. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4228. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4229. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4230. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4231. * 中的索引
  4232. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4233. * @param { int } offset 选区的开始位置偏移量
  4234. * @return { UE.dom.Range } 当前range对象
  4235. * @example
  4236. * ```html
  4237. * <!-- 选区 -->
  4238. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4239. *
  4240. * <script>
  4241. *
  4242. * //执行操作
  4243. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4244. *
  4245. * //此时, 选区变成了
  4246. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4247. *
  4248. * </script>
  4249. * ```
  4250. * @example
  4251. * ```html
  4252. * <!-- 选区 -->
  4253. * <b>xxx<img>[xx]x</b>
  4254. *
  4255. * <script>
  4256. *
  4257. * //执行操作
  4258. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4259. *
  4260. * //此时, 选区变成了
  4261. * //<b>xxx[<img>xx]x</b>
  4262. *
  4263. * </script>
  4264. * ```
  4265. */
  4266. setStart:function (node, offset) {
  4267. return setEndPoint(true, node, offset, this);
  4268. },
  4269. /**
  4270. * 设置Range的结束容器和偏移量
  4271. * @method setEnd
  4272. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4273. * @param { int } offset 结束边界的偏移量
  4274. * @see UE.dom.Range:setStart(Node,int)
  4275. * @return { UE.dom.Range } 当前range对象
  4276. */
  4277. setEnd:function (node, offset) {
  4278. return setEndPoint(false, node, offset, this);
  4279. },
  4280. /**
  4281. * 将Range开始位置设置到node节点之后
  4282. * @method setStartAfter
  4283. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4284. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4285. * @return { UE.dom.Range } 当前range对象
  4286. * @example
  4287. * ```html
  4288. * <!-- 选区示例 -->
  4289. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4290. *
  4291. * <script>
  4292. *
  4293. * //执行操作
  4294. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4295. *
  4296. * //结果选区
  4297. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4298. *
  4299. * </script>
  4300. * ```
  4301. */
  4302. setStartAfter:function (node) {
  4303. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4304. },
  4305. /**
  4306. * 将Range开始位置设置到node节点之前
  4307. * @method setStartBefore
  4308. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4309. * @param { Node } node 新的选区开始位置在该节点之前
  4310. * @see UE.dom.Range:setStartAfter(Node)
  4311. * @return { UE.dom.Range } 当前range对象
  4312. */
  4313. setStartBefore:function (node) {
  4314. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4315. },
  4316. /**
  4317. * 将Range结束位置设置到node节点之后
  4318. * @method setEndAfter
  4319. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4320. * @param { Node } node 目标节点
  4321. * @see UE.dom.Range:setStartAfter(Node)
  4322. * @return { UE.dom.Range } 当前range对象
  4323. * @example
  4324. * ```html
  4325. * <!-- 选区示例 -->
  4326. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4327. *
  4328. * <script>
  4329. *
  4330. * //执行操作
  4331. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4332. *
  4333. * //结果选区
  4334. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4335. *
  4336. * </script>
  4337. * ```
  4338. */
  4339. setEndAfter:function (node) {
  4340. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4341. },
  4342. /**
  4343. * 将Range结束位置设置到node节点之前
  4344. * @method setEndBefore
  4345. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4346. * @param { Node } node 目标节点
  4347. * @see UE.dom.Range:setEndAfter(Node)
  4348. * @return { UE.dom.Range } 当前range对象
  4349. */
  4350. setEndBefore:function (node) {
  4351. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4352. },
  4353. /**
  4354. * 设置Range的开始位置到node节点内的第一个子节点之前
  4355. * @method setStartAtFirst
  4356. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4357. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4358. * @param { Node } node 目标节点
  4359. * @see UE.dom.Range:setStartBefore(Node)
  4360. * @return { UE.dom.Range } 当前range对象
  4361. * @example
  4362. * ```html
  4363. * <!-- 选区示例 -->
  4364. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4365. *
  4366. * <script>
  4367. *
  4368. * //执行操作
  4369. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4370. *
  4371. * //结果选区
  4372. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4373. *
  4374. * </script>
  4375. * ```
  4376. */
  4377. setStartAtFirst:function (node) {
  4378. return this.setStart(node, 0);
  4379. },
  4380. /**
  4381. * 设置Range的开始位置到node节点内的最后一个节点之后
  4382. * @method setStartAtLast
  4383. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4384. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4385. * @param { Node } node 目标节点
  4386. * @see UE.dom.Range:setStartAtFirst(Node)
  4387. * @return { UE.dom.Range } 当前range对象
  4388. */
  4389. setStartAtLast:function (node) {
  4390. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4391. },
  4392. /**
  4393. * 设置Range的结束位置到node节点内的第一个节点之前
  4394. * @method setEndAtFirst
  4395. * @param { Node } node 目标节点
  4396. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4397. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4398. * @see UE.dom.Range:setStartAtFirst(Node)
  4399. * @return { UE.dom.Range } 当前range对象
  4400. */
  4401. setEndAtFirst:function (node) {
  4402. return this.setEnd(node, 0);
  4403. },
  4404. /**
  4405. * 设置Range的结束位置到node节点内的最后一个节点之后
  4406. * @method setEndAtLast
  4407. * @param { Node } node 目标节点
  4408. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4409. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4410. * @see UE.dom.Range:setStartAtFirst(Node)
  4411. * @return { UE.dom.Range } 当前range对象
  4412. */
  4413. setEndAtLast:function (node) {
  4414. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4415. },
  4416. /**
  4417. * 选中给定节点
  4418. * @method selectNode
  4419. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4420. * 而endOffset为startOffset+1
  4421. * @param { Node } node 需要选中的节点
  4422. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4423. * @example
  4424. * ```html
  4425. * <!-- 选区示例 -->
  4426. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4427. *
  4428. * <script>
  4429. *
  4430. * //执行操作
  4431. * range.selectNode( document.getElementsByTagName("i")[0] );
  4432. *
  4433. * //结果选区
  4434. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4435. *
  4436. * </script>
  4437. * ```
  4438. */
  4439. selectNode:function (node) {
  4440. return this.setStartBefore(node).setEndAfter(node);
  4441. },
  4442. /**
  4443. * 选中给定节点内部的所有节点
  4444. * @method selectNodeContents
  4445. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4446. * 而endOffset是该节点的子节点数。
  4447. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4448. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4449. * @example
  4450. * ```html
  4451. * <!-- 选区示例 -->
  4452. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4453. *
  4454. * <script>
  4455. *
  4456. * //执行操作
  4457. * range.selectNode( document.getElementsByTagName("b")[0] );
  4458. *
  4459. * //结果选区
  4460. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4461. *
  4462. * </script>
  4463. * ```
  4464. */
  4465. selectNodeContents:function (node) {
  4466. return this.setStart(node, 0).setEndAtLast(node);
  4467. },
  4468. /**
  4469. * clone当前Range对象
  4470. * @method cloneRange
  4471. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4472. * @return { UE.dom.Range } 当前range对象的一个副本
  4473. */
  4474. cloneRange:function () {
  4475. var me = this;
  4476. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4477. },
  4478. /**
  4479. * 向当前选区的结束处闭合选区
  4480. * @method collapse
  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.collapse();
  4491. *
  4492. * //结果选区
  4493. * //“|”表示选区已闭合
  4494. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4495. *
  4496. * </script>
  4497. * ```
  4498. */
  4499. /**
  4500. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4501. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4502. * @method collapse
  4503. * @param { Boolean } toStart 是否向选区开始处闭合
  4504. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4505. * @see UE.dom.Range:collapse()
  4506. * @example
  4507. * ```html
  4508. * <!-- 选区示例 -->
  4509. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4510. *
  4511. * <script>
  4512. *
  4513. * //执行操作
  4514. * range.collapse( true );
  4515. *
  4516. * //结果选区
  4517. * //“|”表示选区已闭合
  4518. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4519. *
  4520. * </script>
  4521. * ```
  4522. */
  4523. collapse:function (toStart) {
  4524. var me = this;
  4525. if (toStart) {
  4526. me.endContainer = me.startContainer;
  4527. me.endOffset = me.startOffset;
  4528. } else {
  4529. me.startContainer = me.endContainer;
  4530. me.startOffset = me.endOffset;
  4531. }
  4532. me.collapsed = true;
  4533. return me;
  4534. },
  4535. /**
  4536. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4537. * @method shrinkBoundary
  4538. * @return { UE.dom.Range } 当前range对象
  4539. * @example
  4540. * ```html
  4541. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4542. * ```
  4543. *
  4544. * @example
  4545. * ```html
  4546. * <!-- 选区示例 -->
  4547. * <b>x[xx</b><i>]xxx</i>
  4548. *
  4549. * <script>
  4550. *
  4551. * //执行收缩
  4552. * range.shrinkBoundary();
  4553. *
  4554. * //结果选区
  4555. * //<b>x[xx]</b><i>xxx</i>
  4556. * </script>
  4557. * ```
  4558. *
  4559. * @example
  4560. * ```html
  4561. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4562. * ```
  4563. */
  4564. /**
  4565. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4566. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4567. * @method shrinkBoundary
  4568. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4569. * @return { UE.dom.Range } 当前range对象
  4570. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4571. */
  4572. shrinkBoundary:function (ignoreEnd) {
  4573. var me = this, child,
  4574. collapsed = me.collapsed;
  4575. function check(node){
  4576. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4577. }
  4578. while (me.startContainer.nodeType == 1 //是element
  4579. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4580. && check(child)) {
  4581. me.setStart(child, 0);
  4582. }
  4583. if (collapsed) {
  4584. return me.collapse(true);
  4585. }
  4586. if (!ignoreEnd) {
  4587. while (me.endContainer.nodeType == 1//是element
  4588. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4589. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4590. && check(child)) {
  4591. me.setEnd(child, child.childNodes.length);
  4592. }
  4593. }
  4594. return me;
  4595. },
  4596. /**
  4597. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4598. * @method getCommonAncestor
  4599. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4600. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4601. * @example
  4602. * ```html
  4603. * //选区示例
  4604. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4605. * <script>
  4606. *
  4607. * var node = range.getCommonAncestor();
  4608. *
  4609. * //公共祖先节点是: b节点
  4610. * //输出: B
  4611. * console.log(node.tagName);
  4612. *
  4613. * </script>
  4614. * ```
  4615. */
  4616. /**
  4617. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4618. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4619. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4620. * @method getCommonAncestor
  4621. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4622. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4623. * @see UE.dom.Range:getCommonAncestor()
  4624. * @example
  4625. * ```html
  4626. * <body>
  4627. *
  4628. * <!-- 选区示例 -->
  4629. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4630. *
  4631. * <script>
  4632. *
  4633. * var node = range.getCommonAncestor( false );
  4634. *
  4635. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4636. * //output: B
  4637. * console.log( node.tagName );
  4638. *
  4639. * </script>
  4640. *
  4641. * </body>
  4642. * ```
  4643. */
  4644. /**
  4645. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4646. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4647. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4648. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4649. * @method getCommonAncestor
  4650. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4651. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4652. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4653. * @see UE.dom.Range:getCommonAncestor()
  4654. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4655. * @example
  4656. * ```html
  4657. * <body>
  4658. *
  4659. * <!-- 选区示例 -->
  4660. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4661. *
  4662. * <script>
  4663. *
  4664. * var node = range.getCommonAncestor( true, false );
  4665. *
  4666. * //output: SPAN
  4667. * console.log( node.tagName );
  4668. *
  4669. * </script>
  4670. *
  4671. * </body>
  4672. * ```
  4673. */
  4674. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4675. var me = this,
  4676. start = me.startContainer,
  4677. end = me.endContainer;
  4678. if (start === end) {
  4679. if (includeSelf && selectOneNode(this)) {
  4680. start = start.childNodes[me.startOffset];
  4681. if(start.nodeType == 1)
  4682. return start;
  4683. }
  4684. //只有在上来就相等的情况下才会出现是文本的情况
  4685. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4686. }
  4687. return domUtils.getCommonAncestor(start, end);
  4688. },
  4689. /**
  4690. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4691. * @method trimBoundary
  4692. * @remind 该操作有可能会引起文本节点被切开
  4693. * @return { UE.dom.Range } 当前range对象
  4694. * @example
  4695. * ```html
  4696. *
  4697. * //选区示例
  4698. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4699. *
  4700. * <script>
  4701. * //未调整前, 选区的开始容器和结束都是文本节点
  4702. * //执行调整
  4703. * range.trimBoundary();
  4704. *
  4705. * //调整之后, 容器节点变成了i节点
  4706. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4707. * </script>
  4708. * ```
  4709. */
  4710. /**
  4711. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4712. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4713. * @method trimBoundary
  4714. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4715. * @return { UE.dom.Range } 当前range对象
  4716. * @example
  4717. * ```html
  4718. *
  4719. * //选区示例
  4720. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4721. *
  4722. * <script>
  4723. * //未调整前, 选区的开始容器和结束都是文本节点
  4724. * //执行调整
  4725. * range.trimBoundary( true );
  4726. *
  4727. * //调整之后, 开始容器节点变成了i节点
  4728. * //但是, 结束容器没有发生变化
  4729. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4730. * </script>
  4731. * ```
  4732. */
  4733. trimBoundary:function (ignoreEnd) {
  4734. this.txtToElmBoundary();
  4735. var start = this.startContainer,
  4736. offset = this.startOffset,
  4737. collapsed = this.collapsed,
  4738. end = this.endContainer;
  4739. if (start.nodeType == 3) {
  4740. if (offset == 0) {
  4741. this.setStartBefore(start);
  4742. } else {
  4743. if (offset >= start.nodeValue.length) {
  4744. this.setStartAfter(start);
  4745. } else {
  4746. var textNode = domUtils.split(start, offset);
  4747. //跟新结束边界
  4748. if (start === end) {
  4749. this.setEnd(textNode, this.endOffset - offset);
  4750. } else if (start.parentNode === end) {
  4751. this.endOffset += 1;
  4752. }
  4753. this.setStartBefore(textNode);
  4754. }
  4755. }
  4756. if (collapsed) {
  4757. return this.collapse(true);
  4758. }
  4759. }
  4760. if (!ignoreEnd) {
  4761. offset = this.endOffset;
  4762. end = this.endContainer;
  4763. if (end.nodeType == 3) {
  4764. if (offset == 0) {
  4765. this.setEndBefore(end);
  4766. } else {
  4767. offset < end.nodeValue.length && domUtils.split(end, offset);
  4768. this.setEndAfter(end);
  4769. }
  4770. }
  4771. }
  4772. return this;
  4773. },
  4774. /**
  4775. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4776. * @method txtToElmBoundary
  4777. * @remind 该操作不会修改dom节点
  4778. * @return { UE.dom.Range } 当前range对象
  4779. */
  4780. /**
  4781. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4782. * ignoreCollapsed 的值决定是否执行该调整
  4783. * @method txtToElmBoundary
  4784. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4785. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4786. * @return { UE.dom.Range } 当前range对象
  4787. */
  4788. txtToElmBoundary:function (ignoreCollapsed) {
  4789. function adjust(r, c) {
  4790. var container = r[c + 'Container'],
  4791. offset = r[c + 'Offset'];
  4792. if (container.nodeType == 3) {
  4793. if (!offset) {
  4794. r['set' + c.replace(/(\w)/, function (a) {
  4795. return a.toUpperCase();
  4796. }) + 'Before'](container);
  4797. } else if (offset >= container.nodeValue.length) {
  4798. r['set' + c.replace(/(\w)/, function (a) {
  4799. return a.toUpperCase();
  4800. }) + 'After' ](container);
  4801. }
  4802. }
  4803. }
  4804. if (ignoreCollapsed || !this.collapsed) {
  4805. adjust(this, 'start');
  4806. adjust(this, 'end');
  4807. }
  4808. return this;
  4809. },
  4810. /**
  4811. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  4812. * @method insertNode
  4813. * @param { Node } node 需要插入的节点
  4814. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  4815. * @return { UE.dom.Range } 当前range对象
  4816. */
  4817. insertNode:function (node) {
  4818. var first = node, length = 1;
  4819. if (node.nodeType == 11) {
  4820. first = node.firstChild;
  4821. length = node.childNodes.length;
  4822. }
  4823. this.trimBoundary(true);
  4824. var start = this.startContainer,
  4825. offset = this.startOffset;
  4826. var nextNode = start.childNodes[ offset ];
  4827. if (nextNode) {
  4828. start.insertBefore(node, nextNode);
  4829. } else {
  4830. start.appendChild(node);
  4831. }
  4832. if (first.parentNode === this.endContainer) {
  4833. this.endOffset = this.endOffset + length;
  4834. }
  4835. return this.setStartBefore(first);
  4836. },
  4837. /**
  4838. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  4839. * @method setCursor
  4840. * @return { UE.dom.Range } 当前range对象
  4841. * @see UE.dom.Range:collapse()
  4842. */
  4843. /**
  4844. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  4845. * @method setCursor
  4846. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  4847. * 反之,则向开始容器方向闭合
  4848. * @return { UE.dom.Range } 当前range对象
  4849. * @see UE.dom.Range:collapse(Boolean)
  4850. */
  4851. setCursor:function (toEnd, noFillData) {
  4852. return this.collapse(!toEnd).select(noFillData);
  4853. },
  4854. /**
  4855. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  4856. * @method createBookmark
  4857. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  4858. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  4859. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  4860. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  4861. * 返回的记录的类型为ID, 反之则为引用
  4862. */
  4863. createBookmark:function (serialize, same) {
  4864. var endNode,
  4865. startNode = this.document.createElement('span');
  4866. startNode.style.cssText = 'display:none;line-height:0px;';
  4867. startNode.appendChild(this.document.createTextNode('\u200D'));
  4868. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  4869. if (!this.collapsed) {
  4870. endNode = startNode.cloneNode(true);
  4871. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  4872. }
  4873. this.insertNode(startNode);
  4874. if (endNode) {
  4875. this.collapse().insertNode(endNode).setEndBefore(endNode);
  4876. }
  4877. this.setStartAfter(startNode);
  4878. return {
  4879. start:serialize ? startNode.id : startNode,
  4880. end:endNode ? serialize ? endNode.id : endNode : null,
  4881. id:serialize
  4882. }
  4883. },
  4884. /**
  4885. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  4886. * @method moveToBookmark
  4887. * @param { BookMark } bookmark createBookmark所创建的标签对象
  4888. * @return { UE.dom.Range } 当前range对象
  4889. * @see UE.dom.Range:createBookmark(Boolean)
  4890. */
  4891. moveToBookmark:function (bookmark) {
  4892. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  4893. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  4894. this.setStartBefore(start);
  4895. domUtils.remove(start);
  4896. if (end) {
  4897. this.setEndBefore(end);
  4898. domUtils.remove(end);
  4899. } else {
  4900. this.collapse(true);
  4901. }
  4902. return this;
  4903. },
  4904. /**
  4905. * 调整range的边界,使其"放大"到最近的父节点
  4906. * @method enlarge
  4907. * @remind 会引起选区的变化
  4908. * @return { UE.dom.Range } 当前range对象
  4909. */
  4910. /**
  4911. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  4912. * 要求扩大之后的父节点是block节点
  4913. * @method enlarge
  4914. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  4915. * @return { UE.dom.Range } 当前range对象
  4916. */
  4917. enlarge:function (toBlock, stopFn) {
  4918. var isBody = domUtils.isBody,
  4919. pre, node, tmp = this.document.createTextNode('');
  4920. if (toBlock) {
  4921. node = this.startContainer;
  4922. if (node.nodeType == 1) {
  4923. if (node.childNodes[this.startOffset]) {
  4924. pre = node = node.childNodes[this.startOffset]
  4925. } else {
  4926. node.appendChild(tmp);
  4927. pre = node = tmp;
  4928. }
  4929. } else {
  4930. pre = node;
  4931. }
  4932. while (1) {
  4933. if (domUtils.isBlockElm(node)) {
  4934. node = pre;
  4935. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  4936. node = pre;
  4937. }
  4938. this.setStartBefore(node);
  4939. break;
  4940. }
  4941. pre = node;
  4942. node = node.parentNode;
  4943. }
  4944. node = this.endContainer;
  4945. if (node.nodeType == 1) {
  4946. if (pre = node.childNodes[this.endOffset]) {
  4947. node.insertBefore(tmp, pre);
  4948. } else {
  4949. node.appendChild(tmp);
  4950. }
  4951. pre = node = tmp;
  4952. } else {
  4953. pre = node;
  4954. }
  4955. while (1) {
  4956. if (domUtils.isBlockElm(node)) {
  4957. node = pre;
  4958. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  4959. node = pre;
  4960. }
  4961. this.setEndAfter(node);
  4962. break;
  4963. }
  4964. pre = node;
  4965. node = node.parentNode;
  4966. }
  4967. if (tmp.parentNode === this.endContainer) {
  4968. this.endOffset--;
  4969. }
  4970. domUtils.remove(tmp);
  4971. }
  4972. // 扩展边界到最大
  4973. if (!this.collapsed) {
  4974. while (this.startOffset == 0) {
  4975. if (stopFn && stopFn(this.startContainer)) {
  4976. break;
  4977. }
  4978. if (isBody(this.startContainer)) {
  4979. break;
  4980. }
  4981. this.setStartBefore(this.startContainer);
  4982. }
  4983. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  4984. if (stopFn && stopFn(this.endContainer)) {
  4985. break;
  4986. }
  4987. if (isBody(this.endContainer)) {
  4988. break;
  4989. }
  4990. this.setEndAfter(this.endContainer);
  4991. }
  4992. }
  4993. return this;
  4994. },
  4995. enlargeToBlockElm:function(ignoreEnd){
  4996. while(!domUtils.isBlockElm(this.startContainer)){
  4997. this.setStartBefore(this.startContainer);
  4998. }
  4999. if(!ignoreEnd){
  5000. while(!domUtils.isBlockElm(this.endContainer)){
  5001. this.setEndAfter(this.endContainer);
  5002. }
  5003. }
  5004. return this;
  5005. },
  5006. /**
  5007. * 调整Range的边界,使其"缩小"到最合适的位置
  5008. * @method adjustmentBoundary
  5009. * @return { UE.dom.Range } 当前range对象
  5010. * @see UE.dom.Range:shrinkBoundary()
  5011. */
  5012. adjustmentBoundary:function () {
  5013. if (!this.collapsed) {
  5014. while (!domUtils.isBody(this.startContainer) &&
  5015. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5016. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5017. ) {
  5018. this.setStartAfter(this.startContainer);
  5019. }
  5020. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5021. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5022. ) {
  5023. this.setEndBefore(this.endContainer);
  5024. }
  5025. }
  5026. return this;
  5027. },
  5028. /**
  5029. * 给range选区中的内容添加给定的inline标签
  5030. * @method applyInlineStyle
  5031. * @param { String } tagName 需要添加的标签名
  5032. * @example
  5033. * ```html
  5034. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5035. * ```
  5036. */
  5037. /**
  5038. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5039. * @method applyInlineStyle
  5040. * @param { String } tagName 需要添加的标签名
  5041. * @param { Object } attrs 跟随新添加的标签的属性
  5042. * @return { UE.dom.Range } 当前选区
  5043. * @example
  5044. * ```html
  5045. * <p>xxxx[xxxx]x</p>
  5046. *
  5047. * ==>
  5048. *
  5049. * <!-- 执行操作 -->
  5050. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5051. *
  5052. * ==>
  5053. *
  5054. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5055. * ```
  5056. */
  5057. applyInlineStyle:function (tagName, attrs, list) {
  5058. if (this.collapsed)return this;
  5059. this.trimBoundary().enlarge(false,
  5060. function (node) {
  5061. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5062. }).adjustmentBoundary();
  5063. var bookmark = this.createBookmark(),
  5064. end = bookmark.end,
  5065. filterFn = function (node) {
  5066. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5067. },
  5068. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5069. node,
  5070. pre,
  5071. range = this.cloneRange();
  5072. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5073. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5074. range.setStartBefore(current);
  5075. node = current;
  5076. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5077. pre = node;
  5078. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5079. return dtd[tagName][parent.tagName];
  5080. });
  5081. }
  5082. var frag = range.setEndAfter(pre).extractContents(), elm;
  5083. if (list && list.length > 0) {
  5084. var level, top;
  5085. top = level = list[0].cloneNode(false);
  5086. for (var i = 1, ci; ci = list[i++];) {
  5087. level.appendChild(ci.cloneNode(false));
  5088. level = level.firstChild;
  5089. }
  5090. elm = level;
  5091. } else {
  5092. elm = range.document.createElement(tagName);
  5093. }
  5094. if (attrs) {
  5095. domUtils.setAttributes(elm, attrs);
  5096. }
  5097. elm.appendChild(frag);
  5098. range.insertNode(list ? top : elm);
  5099. //处理下滑线在a上的情况
  5100. var aNode;
  5101. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5102. domUtils.setAttributes(aNode, attrs);
  5103. domUtils.remove(elm, true);
  5104. elm = aNode;
  5105. } else {
  5106. domUtils.mergeSibling(elm);
  5107. domUtils.clearEmptySibling(elm);
  5108. }
  5109. //去除子节点相同的
  5110. domUtils.mergeChild(elm, attrs);
  5111. current = domUtils.getNextDomNode(elm, false, filterFn);
  5112. domUtils.mergeToParent(elm);
  5113. if (node === end) {
  5114. break;
  5115. }
  5116. } else {
  5117. current = domUtils.getNextDomNode(current, true, filterFn);
  5118. }
  5119. }
  5120. return this.moveToBookmark(bookmark);
  5121. },
  5122. /**
  5123. * 移除当前选区内指定的inline标签,但保留其中的内容
  5124. * @method removeInlineStyle
  5125. * @param { String } tagName 需要移除的标签名
  5126. * @return { UE.dom.Range } 当前的range对象
  5127. * @example
  5128. * ```html
  5129. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5130. * ```
  5131. */
  5132. /**
  5133. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5134. * @method removeInlineStyle
  5135. * @param { Array } tagNameArr 需要移除的标签名的数组
  5136. * @return { UE.dom.Range } 当前的range对象
  5137. * @see UE.dom.Range:removeInlineStyle(String)
  5138. */
  5139. removeInlineStyle:function (tagNames) {
  5140. if (this.collapsed)return this;
  5141. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5142. this.shrinkBoundary().adjustmentBoundary();
  5143. var start = this.startContainer, end = this.endContainer;
  5144. while (1) {
  5145. if (start.nodeType == 1) {
  5146. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5147. break;
  5148. }
  5149. if (start.tagName.toLowerCase() == 'body') {
  5150. start = null;
  5151. break;
  5152. }
  5153. }
  5154. start = start.parentNode;
  5155. }
  5156. while (1) {
  5157. if (end.nodeType == 1) {
  5158. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5159. break;
  5160. }
  5161. if (end.tagName.toLowerCase() == 'body') {
  5162. end = null;
  5163. break;
  5164. }
  5165. }
  5166. end = end.parentNode;
  5167. }
  5168. var bookmark = this.createBookmark(),
  5169. frag,
  5170. tmpRange;
  5171. if (start) {
  5172. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5173. frag = tmpRange.extractContents();
  5174. tmpRange.insertNode(frag);
  5175. domUtils.clearEmptySibling(start, true);
  5176. start.parentNode.insertBefore(bookmark.start, start);
  5177. }
  5178. if (end) {
  5179. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5180. frag = tmpRange.extractContents();
  5181. tmpRange.insertNode(frag);
  5182. domUtils.clearEmptySibling(end, false, true);
  5183. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5184. }
  5185. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5186. return node.nodeType == 1;
  5187. }), next;
  5188. while (current && current !== bookmark.end) {
  5189. next = domUtils.getNextDomNode(current, true, function (node) {
  5190. return node.nodeType == 1;
  5191. });
  5192. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5193. domUtils.remove(current, true);
  5194. }
  5195. current = next;
  5196. }
  5197. return this.moveToBookmark(bookmark);
  5198. },
  5199. /**
  5200. * 获取当前选中的自闭合的节点
  5201. * @method getClosedNode
  5202. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5203. */
  5204. getClosedNode:function () {
  5205. var node;
  5206. if (!this.collapsed) {
  5207. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5208. if (selectOneNode(range)) {
  5209. var child = range.startContainer.childNodes[range.startOffset];
  5210. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5211. node = child;
  5212. }
  5213. }
  5214. }
  5215. return node;
  5216. },
  5217. /**
  5218. * 在页面上高亮range所表示的选区
  5219. * @method select
  5220. * @return { UE.dom.Range } 返回当前Range对象
  5221. */
  5222. //这里不区分ie9以上,trace:3824
  5223. select:browser.ie ? function (noFillData, textRange) {
  5224. var nativeRange;
  5225. if (!this.collapsed)
  5226. this.shrinkBoundary();
  5227. var node = this.getClosedNode();
  5228. if (node && !textRange) {
  5229. try {
  5230. nativeRange = this.document.body.createControlRange();
  5231. nativeRange.addElement(node);
  5232. nativeRange.select();
  5233. } catch (e) {}
  5234. return this;
  5235. }
  5236. var bookmark = this.createBookmark(),
  5237. start = bookmark.start,
  5238. end;
  5239. nativeRange = this.document.body.createTextRange();
  5240. nativeRange.moveToElementText(start);
  5241. nativeRange.moveStart('character', 1);
  5242. if (!this.collapsed) {
  5243. var nativeRangeEnd = this.document.body.createTextRange();
  5244. end = bookmark.end;
  5245. nativeRangeEnd.moveToElementText(end);
  5246. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5247. } else {
  5248. if (!noFillData && this.startContainer.nodeType != 3) {
  5249. //使用<span>|x<span>固定住光标
  5250. var tmpText = this.document.createTextNode(fillChar),
  5251. tmp = this.document.createElement('span');
  5252. tmp.appendChild(this.document.createTextNode(fillChar));
  5253. start.parentNode.insertBefore(tmp, start);
  5254. start.parentNode.insertBefore(tmpText, start);
  5255. //当点b,i,u时,不能清除i上边的b
  5256. removeFillData(this.document, tmpText);
  5257. fillData = tmpText;
  5258. mergeSibling(tmp, 'previousSibling');
  5259. mergeSibling(start, 'nextSibling');
  5260. nativeRange.moveStart('character', -1);
  5261. nativeRange.collapse(true);
  5262. }
  5263. }
  5264. this.moveToBookmark(bookmark);
  5265. tmp && domUtils.remove(tmp);
  5266. //IE在隐藏状态下不支持range操作,catch一下
  5267. try {
  5268. nativeRange.select();
  5269. } catch (e) {
  5270. }
  5271. return this;
  5272. } : function (notInsertFillData) {
  5273. function checkOffset(rng){
  5274. function check(node,offset,dir){
  5275. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5276. rng[dir + 'Offset'] = node.nodeValue.length
  5277. }
  5278. }
  5279. check(rng.startContainer,rng.startOffset,'start');
  5280. check(rng.endContainer,rng.endOffset,'end');
  5281. }
  5282. var win = domUtils.getWindow(this.document),
  5283. sel = win.getSelection(),
  5284. txtNode;
  5285. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5286. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5287. browser.gecko ? this.document.body.focus() : win.focus();
  5288. if (sel) {
  5289. sel.removeAllRanges();
  5290. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5291. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5292. if (this.collapsed && !notInsertFillData) {
  5293. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5294. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5295. // var tmp = this.document.createTextNode('');
  5296. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5297. // }
  5298. //
  5299. //处理光标落在文本节点的情况
  5300. //处理以下的情况
  5301. //<b>|xxxx</b>
  5302. //<b>xxxx</b>|xxxx
  5303. //xxxx<b>|</b>
  5304. var start = this.startContainer,child = start;
  5305. if(start.nodeType == 1){
  5306. child = start.childNodes[this.startOffset];
  5307. }
  5308. if( !(start.nodeType == 3 && this.startOffset) &&
  5309. (child ?
  5310. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5311. :
  5312. (!start.lastChild || start.lastChild.nodeType != 3)
  5313. )
  5314. ){
  5315. txtNode = this.document.createTextNode(fillChar);
  5316. //跟着前边走
  5317. this.insertNode(txtNode);
  5318. removeFillData(this.document, txtNode);
  5319. mergeSibling(txtNode, 'previousSibling');
  5320. mergeSibling(txtNode, 'nextSibling');
  5321. fillData = txtNode;
  5322. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5323. }
  5324. }
  5325. var nativeRange = this.document.createRange();
  5326. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5327. var child = this.startContainer.childNodes[this.startOffset];
  5328. if(!child){
  5329. //往前靠拢
  5330. child = this.startContainer.lastChild;
  5331. if( child && domUtils.isBr(child)){
  5332. this.setStartBefore(child).collapse(true);
  5333. }
  5334. }else{
  5335. //向后靠拢
  5336. while(child && domUtils.isBlockElm(child)){
  5337. if(child.nodeType == 1 && child.childNodes[0]){
  5338. child = child.childNodes[0]
  5339. }else{
  5340. break;
  5341. }
  5342. }
  5343. child && this.setStartBefore(child).collapse(true)
  5344. }
  5345. }
  5346. //是createAddress最后一位算的不准,现在这里进行微调
  5347. checkOffset(this);
  5348. nativeRange.setStart(this.startContainer, this.startOffset);
  5349. nativeRange.setEnd(this.endContainer, this.endOffset);
  5350. sel.addRange(nativeRange);
  5351. }
  5352. return this;
  5353. },
  5354. /**
  5355. * 滚动到当前range开始的位置
  5356. * @method scrollToView
  5357. * @param { Window } win 当前range对象所属的window对象
  5358. * @return { UE.dom.Range } 当前Range对象
  5359. */
  5360. /**
  5361. * 滚动到距离当前range开始位置 offset 的位置处
  5362. * @method scrollToView
  5363. * @param { Window } win 当前range对象所属的window对象
  5364. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5365. * @return { UE.dom.Range } 当前Range对象
  5366. */
  5367. scrollToView:function (win, offset) {
  5368. win = win ? window : domUtils.getWindow(this.document);
  5369. var me = this,
  5370. span = me.document.createElement('span');
  5371. //trace:717
  5372. span.innerHTML = '&nbsp;';
  5373. me.cloneRange().insertNode(span);
  5374. domUtils.scrollToView(span, win, offset);
  5375. domUtils.remove(span);
  5376. return me;
  5377. },
  5378. /**
  5379. * 判断当前选区内容是否占位符
  5380. * @private
  5381. * @method inFillChar
  5382. * @return { Boolean } 如果是占位符返回true,否则返回false
  5383. */
  5384. inFillChar : function(){
  5385. var start = this.startContainer;
  5386. if(this.collapsed && start.nodeType == 3
  5387. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5388. ){
  5389. return true;
  5390. }
  5391. return false;
  5392. },
  5393. /**
  5394. * 保存
  5395. * @method createAddress
  5396. * @private
  5397. * @return { Boolean } 返回开始和结束的位置
  5398. * @example
  5399. * ```html
  5400. * <body>
  5401. * <p>
  5402. * aaaa
  5403. * <em>
  5404. * <!-- 选区开始 -->
  5405. * bbbb
  5406. * <!-- 选区结束 -->
  5407. * </em>
  5408. * </p>
  5409. *
  5410. * <script>
  5411. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5412. * console.log( range.createAddress() );
  5413. * </script>
  5414. * </body>
  5415. * ```
  5416. */
  5417. createAddress : function(ignoreEnd,ignoreTxt){
  5418. var addr = {},me = this;
  5419. function getAddress(isStart){
  5420. var node = isStart ? me.startContainer : me.endContainer;
  5421. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5422. addrs = [];
  5423. for(var i = 0,ci;ci = parents[i++];){
  5424. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5425. }
  5426. var firstIndex = 0;
  5427. if(ignoreTxt){
  5428. if(node.nodeType == 3){
  5429. var tmpNode = node.previousSibling;
  5430. while(tmpNode && tmpNode.nodeType == 3){
  5431. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5432. tmpNode = tmpNode.previousSibling;
  5433. }
  5434. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5435. }else{
  5436. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5437. if(node){
  5438. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5439. }else{
  5440. node = isStart ? me.startContainer : me.endContainer;
  5441. var first = node.firstChild;
  5442. while(first){
  5443. if(domUtils.isFillChar(first)){
  5444. first = first.nextSibling;
  5445. continue;
  5446. }
  5447. firstIndex++;
  5448. if(first.nodeType == 3){
  5449. while( first && first.nodeType == 3){
  5450. first = first.nextSibling;
  5451. }
  5452. }else{
  5453. first = first.nextSibling;
  5454. }
  5455. }
  5456. }
  5457. }
  5458. }else{
  5459. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5460. }
  5461. if(firstIndex < 0){
  5462. firstIndex = 0;
  5463. }
  5464. addrs.push(firstIndex);
  5465. return addrs;
  5466. }
  5467. addr.startAddress = getAddress(true);
  5468. if(!ignoreEnd){
  5469. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5470. }
  5471. return addr;
  5472. },
  5473. /**
  5474. * 保存
  5475. * @method createAddress
  5476. * @private
  5477. * @return { Boolean } 返回开始和结束的位置
  5478. * @example
  5479. * ```html
  5480. * <body>
  5481. * <p>
  5482. * aaaa
  5483. * <em>
  5484. * <!-- 选区开始 -->
  5485. * bbbb
  5486. * <!-- 选区结束 -->
  5487. * </em>
  5488. * </p>
  5489. *
  5490. * <script>
  5491. * var range = editor.selection.getRange();
  5492. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5493. * range.select();
  5494. * //output: 'bbbb'
  5495. * console.log(editor.selection.getText());
  5496. * </script>
  5497. * </body>
  5498. * ```
  5499. */
  5500. moveToAddress : function(addr,ignoreEnd){
  5501. var me = this;
  5502. function getNode(address,isStart){
  5503. var tmpNode = me.document.body,
  5504. parentNode,offset;
  5505. for(var i= 0,ci,l=address.length;i<l;i++){
  5506. ci = address[i];
  5507. parentNode = tmpNode;
  5508. tmpNode = tmpNode.childNodes[ci];
  5509. if(!tmpNode){
  5510. offset = ci;
  5511. break;
  5512. }
  5513. }
  5514. if(isStart){
  5515. if(tmpNode){
  5516. me.setStartBefore(tmpNode)
  5517. }else{
  5518. me.setStart(parentNode,offset)
  5519. }
  5520. }else{
  5521. if(tmpNode){
  5522. me.setEndBefore(tmpNode)
  5523. }else{
  5524. me.setEnd(parentNode,offset)
  5525. }
  5526. }
  5527. }
  5528. getNode(addr.startAddress,true);
  5529. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5530. return me;
  5531. },
  5532. /**
  5533. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5534. * @method equals
  5535. * @param { UE.dom.Range } 需要判断的Range对象
  5536. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5537. */
  5538. equals : function(rng){
  5539. for(var p in this){
  5540. if(this.hasOwnProperty(p)){
  5541. if(this[p] !== rng[p])
  5542. return false
  5543. }
  5544. }
  5545. return true;
  5546. },
  5547. /**
  5548. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5549. * 作为其参数。
  5550. * @method traversal
  5551. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5552. * @return { UE.dom.Range } 当前range对象
  5553. * @example
  5554. * ```html
  5555. *
  5556. * <body>
  5557. *
  5558. * <!-- 选区开始 -->
  5559. * <span></span>
  5560. * <a></a>
  5561. * <!-- 选区结束 -->
  5562. * </body>
  5563. *
  5564. * <script>
  5565. *
  5566. * //output: <span></span><a></a>
  5567. * console.log( range.cloneContents() );
  5568. *
  5569. * range.traversal( function ( node ) {
  5570. *
  5571. * if ( node.nodeType === 1 ) {
  5572. * node.className = "test";
  5573. * }
  5574. *
  5575. * } );
  5576. *
  5577. * //output: <span class="test"></span><a class="test"></a>
  5578. * console.log( range.cloneContents() );
  5579. *
  5580. * </script>
  5581. * ```
  5582. */
  5583. /**
  5584. * 遍历range内的节点。
  5585. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5586. * 作为其参数。
  5587. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5588. * 发doFn函数的执行
  5589. * @method traversal
  5590. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5591. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5592. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5593. * 会触发doFn。
  5594. * @return { UE.dom.Range } 当前range对象
  5595. * @see UE.dom.Range:traversal(Function)
  5596. * @example
  5597. * ```html
  5598. *
  5599. * <body>
  5600. *
  5601. * <!-- 选区开始 -->
  5602. * <span></span>
  5603. * <a></a>
  5604. * <!-- 选区结束 -->
  5605. * </body>
  5606. *
  5607. * <script>
  5608. *
  5609. * //output: <span></span><a></a>
  5610. * console.log( range.cloneContents() );
  5611. *
  5612. * range.traversal( function ( node ) {
  5613. *
  5614. * node.className = "test";
  5615. *
  5616. * }, function ( node ) {
  5617. * return node.nodeType === 1;
  5618. * } );
  5619. *
  5620. * //output: <span class="test"></span><a class="test"></a>
  5621. * console.log( range.cloneContents() );
  5622. *
  5623. * </script>
  5624. * ```
  5625. */
  5626. traversal:function(doFn,filterFn){
  5627. if (this.collapsed)
  5628. return this;
  5629. var bookmark = this.createBookmark(),
  5630. end = bookmark.end,
  5631. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5632. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5633. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5634. doFn(current);
  5635. current = tmpNode;
  5636. }
  5637. return this.moveToBookmark(bookmark);
  5638. }
  5639. };
  5640. })();
  5641. /**
  5642. * 选集
  5643. * @file
  5644. * @module UE.dom
  5645. * @class Selection
  5646. * @since 1.2.6.1
  5647. */
  5648. /**
  5649. * 选区集合
  5650. * @unfile
  5651. * @module UE.dom
  5652. * @class Selection
  5653. */
  5654. (function () {
  5655. function getBoundaryInformation( range, start ) {
  5656. var getIndex = domUtils.getNodeIndex;
  5657. range = range.duplicate();
  5658. range.collapse( start );
  5659. var parent = range.parentElement();
  5660. //如果节点里没有子节点,直接退出
  5661. if ( !parent.hasChildNodes() ) {
  5662. return {container:parent, offset:0};
  5663. }
  5664. var siblings = parent.children,
  5665. child,
  5666. testRange = range.duplicate(),
  5667. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5668. distance;
  5669. while ( startIndex <= endIndex ) {
  5670. index = Math.floor( (startIndex + endIndex) / 2 );
  5671. child = siblings[index];
  5672. testRange.moveToElementText( child );
  5673. var position = testRange.compareEndPoints( 'StartToStart', range );
  5674. if ( position > 0 ) {
  5675. endIndex = index - 1;
  5676. } else if ( position < 0 ) {
  5677. startIndex = index + 1;
  5678. } else {
  5679. //trace:1043
  5680. return {container:parent, offset:getIndex( child )};
  5681. }
  5682. }
  5683. if ( index == -1 ) {
  5684. testRange.moveToElementText( parent );
  5685. testRange.setEndPoint( 'StartToStart', range );
  5686. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5687. siblings = parent.childNodes;
  5688. if ( !distance ) {
  5689. child = siblings[siblings.length - 1];
  5690. return {container:child, offset:child.nodeValue.length};
  5691. }
  5692. var i = siblings.length;
  5693. while ( distance > 0 ){
  5694. distance -= siblings[ --i ].nodeValue.length;
  5695. }
  5696. return {container:siblings[i], offset:-distance};
  5697. }
  5698. testRange.collapse( position > 0 );
  5699. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5700. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5701. if ( !distance ) {
  5702. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5703. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5704. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5705. }
  5706. while ( distance > 0 ) {
  5707. try {
  5708. var pre = child;
  5709. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5710. distance -= child.nodeValue.length;
  5711. } catch ( e ) {
  5712. return {container:parent, offset:getIndex( pre )};
  5713. }
  5714. }
  5715. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5716. }
  5717. /*
  5718. * 将ieRange转换为Range对象
  5719. * @param {Range} ieRange ieRange对象
  5720. * @param {Range} range Range对象
  5721. * @return {Range} range 返回转换后的Range对象
  5722. */
  5723. function transformIERangeToRange( ieRange, range ) {
  5724. if ( ieRange.item ) {
  5725. range.selectNode( ieRange.item( 0 ) );
  5726. } else {
  5727. var bi = getBoundaryInformation( ieRange, true );
  5728. range.setStart( bi.container, bi.offset );
  5729. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5730. bi = getBoundaryInformation( ieRange, false );
  5731. range.setEnd( bi.container, bi.offset );
  5732. }
  5733. }
  5734. return range;
  5735. }
  5736. /*
  5737. * 获得ieRange
  5738. * @param {Selection} sel Selection对象
  5739. * @return {ieRange} 得到ieRange
  5740. */
  5741. function _getIERange( sel ) {
  5742. var ieRange;
  5743. //ie下有可能报错
  5744. try {
  5745. ieRange = sel.getNative().createRange();
  5746. } catch ( e ) {
  5747. return null;
  5748. }
  5749. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5750. if ( ( el.ownerDocument || el ) === sel.document ) {
  5751. return ieRange;
  5752. }
  5753. return null;
  5754. }
  5755. var Selection = dom.Selection = function ( doc ) {
  5756. var me = this, iframe;
  5757. me.document = doc;
  5758. if ( browser.ie9below ) {
  5759. iframe = domUtils.getWindow( doc ).frameElement;
  5760. domUtils.on( iframe, 'beforedeactivate', function () {
  5761. me._bakIERange = me.getIERange();
  5762. } );
  5763. domUtils.on( iframe, 'activate', function () {
  5764. try {
  5765. if ( !_getIERange( me ) && me._bakIERange ) {
  5766. me._bakIERange.select();
  5767. }
  5768. } catch ( ex ) {
  5769. }
  5770. me._bakIERange = null;
  5771. } );
  5772. }
  5773. iframe = doc = null;
  5774. };
  5775. Selection.prototype = {
  5776. rangeInBody : function(rng,txtRange){
  5777. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5778. return node === this.document.body || domUtils.inDoc(node,this.document);
  5779. },
  5780. /**
  5781. * 获取原生seleciton对象
  5782. * @method getNative
  5783. * @return { Object } 获得selection对象
  5784. * @example
  5785. * ```javascript
  5786. * editor.selection.getNative();
  5787. * ```
  5788. */
  5789. getNative:function () {
  5790. var doc = this.document;
  5791. try {
  5792. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5793. } catch ( e ) {
  5794. return null;
  5795. }
  5796. },
  5797. /**
  5798. * 获得ieRange
  5799. * @method getIERange
  5800. * @return { Object } 返回ie原生的Range
  5801. * @example
  5802. * ```javascript
  5803. * editor.selection.getIERange();
  5804. * ```
  5805. */
  5806. getIERange:function () {
  5807. var ieRange = _getIERange( this );
  5808. if ( !ieRange ) {
  5809. if ( this._bakIERange ) {
  5810. return this._bakIERange;
  5811. }
  5812. }
  5813. return ieRange;
  5814. },
  5815. /**
  5816. * 缓存当前选区的range和选区的开始节点
  5817. * @method cache
  5818. */
  5819. cache:function () {
  5820. this.clear();
  5821. this._cachedRange = this.getRange();
  5822. this._cachedStartElement = this.getStart();
  5823. this._cachedStartElementPath = this.getStartElementPath();
  5824. },
  5825. /**
  5826. * 获取选区开始位置的父节点到body
  5827. * @method getStartElementPath
  5828. * @return { Array } 返回父节点集合
  5829. * @example
  5830. * ```javascript
  5831. * editor.selection.getStartElementPath();
  5832. * ```
  5833. */
  5834. getStartElementPath:function () {
  5835. if ( this._cachedStartElementPath ) {
  5836. return this._cachedStartElementPath;
  5837. }
  5838. var start = this.getStart();
  5839. if ( start ) {
  5840. return domUtils.findParents( start, true, null, true )
  5841. }
  5842. return [];
  5843. },
  5844. /**
  5845. * 清空缓存
  5846. * @method clear
  5847. */
  5848. clear:function () {
  5849. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  5850. },
  5851. /**
  5852. * 编辑器是否得到了选区
  5853. * @method isFocus
  5854. */
  5855. isFocus:function () {
  5856. try {
  5857. if(browser.ie9below){
  5858. var nativeRange = _getIERange(this);
  5859. return !!(nativeRange && this.rangeInBody(nativeRange));
  5860. }else{
  5861. return !!this.getNative().rangeCount;
  5862. }
  5863. } catch ( e ) {
  5864. return false;
  5865. }
  5866. },
  5867. /**
  5868. * 获取选区对应的Range
  5869. * @method getRange
  5870. * @return { Object } 得到Range对象
  5871. * @example
  5872. * ```javascript
  5873. * editor.selection.getRange();
  5874. * ```
  5875. */
  5876. getRange:function () {
  5877. var me = this;
  5878. function optimze( range ) {
  5879. var child = me.document.body.firstChild,
  5880. collapsed = range.collapsed;
  5881. while ( child && child.firstChild ) {
  5882. range.setStart( child, 0 );
  5883. child = child.firstChild;
  5884. }
  5885. if ( !range.startContainer ) {
  5886. range.setStart( me.document.body, 0 )
  5887. }
  5888. if ( collapsed ) {
  5889. range.collapse( true );
  5890. }
  5891. }
  5892. if ( me._cachedRange != null ) {
  5893. return this._cachedRange;
  5894. }
  5895. var range = new baidu.editor.dom.Range( me.document );
  5896. if ( browser.ie9below ) {
  5897. var nativeRange = me.getIERange();
  5898. if ( nativeRange ) {
  5899. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  5900. try{
  5901. transformIERangeToRange( nativeRange, range );
  5902. }catch(e){
  5903. optimze( range );
  5904. }
  5905. } else {
  5906. optimze( range );
  5907. }
  5908. } else {
  5909. var sel = me.getNative();
  5910. if ( sel && sel.rangeCount ) {
  5911. var firstRange = sel.getRangeAt( 0 );
  5912. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  5913. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  5914. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  5915. optimze( range );
  5916. }
  5917. } else {
  5918. //trace:1734 有可能已经不在dom树上了,标识的节点
  5919. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  5920. return this._bakRange;
  5921. }
  5922. optimze( range );
  5923. }
  5924. }
  5925. return this._bakRange = range;
  5926. },
  5927. /**
  5928. * 获取开始元素,用于状态反射
  5929. * @method getStart
  5930. * @return { Element } 获得开始元素
  5931. * @example
  5932. * ```javascript
  5933. * editor.selection.getStart();
  5934. * ```
  5935. */
  5936. getStart:function () {
  5937. if ( this._cachedStartElement ) {
  5938. return this._cachedStartElement;
  5939. }
  5940. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  5941. tmpRange,
  5942. start, tmp, parent;
  5943. if ( browser.ie9below ) {
  5944. if ( !range ) {
  5945. //todo 给第一个值可能会有问题
  5946. return this.document.body.firstChild;
  5947. }
  5948. //control元素
  5949. if ( range.item ){
  5950. return range.item( 0 );
  5951. }
  5952. tmpRange = range.duplicate();
  5953. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  5954. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  5955. tmpRange.collapse( 1 );
  5956. start = tmpRange.parentElement();
  5957. parent = tmp = range.parentElement();
  5958. while ( tmp = tmp.parentNode ) {
  5959. if ( tmp == start ) {
  5960. start = parent;
  5961. break;
  5962. }
  5963. }
  5964. } else {
  5965. range.shrinkBoundary();
  5966. start = range.startContainer;
  5967. if ( start.nodeType == 1 && start.hasChildNodes() ){
  5968. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  5969. }
  5970. if ( start.nodeType == 3 ){
  5971. return start.parentNode;
  5972. }
  5973. }
  5974. return start;
  5975. },
  5976. /**
  5977. * 得到选区中的文本
  5978. * @method getText
  5979. * @return { String } 选区中包含的文本
  5980. * @example
  5981. * ```javascript
  5982. * editor.selection.getText();
  5983. * ```
  5984. */
  5985. getText:function () {
  5986. var nativeSel, nativeRange;
  5987. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  5988. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  5989. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  5990. }
  5991. return '';
  5992. },
  5993. /**
  5994. * 清除选区
  5995. * @method clearRange
  5996. * @example
  5997. * ```javascript
  5998. * editor.selection.clearRange();
  5999. * ```
  6000. */
  6001. clearRange : function(){
  6002. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6003. }
  6004. };
  6005. })();
  6006. /**
  6007. * 编辑器主类,包含编辑器提供的大部分公用接口
  6008. * @file
  6009. * @module UE
  6010. * @class Editor
  6011. * @since 1.2.6.1
  6012. */
  6013. /**
  6014. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6015. * @unfile
  6016. * @module UE
  6017. */
  6018. /**
  6019. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6020. * @unfile
  6021. * @module UE
  6022. * @class Editor
  6023. */
  6024. (function () {
  6025. var uid = 0, _selectionChangeTimer;
  6026. /**
  6027. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6028. * @private
  6029. * @method setValue
  6030. * @param { UE.Editor } editor 编辑器事例
  6031. */
  6032. function setValue(form, editor) {
  6033. var textarea;
  6034. if (editor.textarea) {
  6035. if (utils.isString(editor.textarea)) {
  6036. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6037. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6038. textarea = ti;
  6039. break;
  6040. }
  6041. }
  6042. } else {
  6043. textarea = editor.textarea;
  6044. }
  6045. }
  6046. if (!textarea) {
  6047. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6048. 'name': editor.options.textarea,
  6049. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6050. 'style': "display:none"
  6051. }));
  6052. //不要产生多个textarea
  6053. editor.textarea = textarea;
  6054. }
  6055. textarea.value = editor.hasContents() ?
  6056. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6057. ''
  6058. }
  6059. function loadPlugins(me){
  6060. //初始化插件
  6061. for (var pi in UE.plugins) {
  6062. UE.plugins[pi].call(me);
  6063. }
  6064. }
  6065. function checkCurLang(I18N){
  6066. for(var lang in I18N){
  6067. return lang
  6068. }
  6069. }
  6070. function langReadied(me){
  6071. me.langIsReady = true;
  6072. me.fireEvent("langReady");
  6073. }
  6074. /**
  6075. * 编辑器准备就绪后会触发该事件
  6076. * @module UE
  6077. * @class Editor
  6078. * @event ready
  6079. * @remind render方法执行完成之后,会触发该事件
  6080. * @remind
  6081. * @example
  6082. * ```javascript
  6083. * editor.addListener( 'ready', function( editor ) {
  6084. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6085. * } );
  6086. * ```
  6087. */
  6088. /**
  6089. * 执行destroy方法,会触发该事件
  6090. * @module UE
  6091. * @class Editor
  6092. * @event destroy
  6093. * @see UE.Editor:destroy()
  6094. */
  6095. /**
  6096. * 执行reset方法,会触发该事件
  6097. * @module UE
  6098. * @class Editor
  6099. * @event reset
  6100. * @see UE.Editor:reset()
  6101. */
  6102. /**
  6103. * 执行focus方法,会触发该事件
  6104. * @module UE
  6105. * @class Editor
  6106. * @event focus
  6107. * @see UE.Editor:focus(Boolean)
  6108. */
  6109. /**
  6110. * 语言加载完成会触发该事件
  6111. * @module UE
  6112. * @class Editor
  6113. * @event langReady
  6114. */
  6115. /**
  6116. * 运行命令之后会触发该命令
  6117. * @module UE
  6118. * @class Editor
  6119. * @event beforeExecCommand
  6120. */
  6121. /**
  6122. * 运行命令之后会触发该命令
  6123. * @module UE
  6124. * @class Editor
  6125. * @event afterExecCommand
  6126. */
  6127. /**
  6128. * 运行命令之前会触发该命令
  6129. * @module UE
  6130. * @class Editor
  6131. * @event firstBeforeExecCommand
  6132. */
  6133. /**
  6134. * 在getContent方法执行之前会触发该事件
  6135. * @module UE
  6136. * @class Editor
  6137. * @event beforeGetContent
  6138. * @see UE.Editor:getContent()
  6139. */
  6140. /**
  6141. * 在getContent方法执行之后会触发该事件
  6142. * @module UE
  6143. * @class Editor
  6144. * @event afterGetContent
  6145. * @see UE.Editor:getContent()
  6146. */
  6147. /**
  6148. * 在getAllHtml方法执行时会触发该事件
  6149. * @module UE
  6150. * @class Editor
  6151. * @event getAllHtml
  6152. * @see UE.Editor:getAllHtml()
  6153. */
  6154. /**
  6155. * 在setContent方法执行之前会触发该事件
  6156. * @module UE
  6157. * @class Editor
  6158. * @event beforeSetContent
  6159. * @see UE.Editor:setContent(String)
  6160. */
  6161. /**
  6162. * 在setContent方法执行之后会触发该事件
  6163. * @module UE
  6164. * @class Editor
  6165. * @event afterSetContent
  6166. * @see UE.Editor:setContent(String)
  6167. */
  6168. /**
  6169. * 每当编辑器内部选区发生改变时,将触发该事件
  6170. * @event selectionchange
  6171. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6172. * @example
  6173. * ```javascript
  6174. * editor.addListener( 'selectionchange', function( editor ) {
  6175. * console.log('选区发生改变');
  6176. * }
  6177. */
  6178. /**
  6179. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6180. * @module UE
  6181. * @class Editor
  6182. * @event beforeSelectionChange
  6183. * @see UE.Editor:selectionchange
  6184. */
  6185. /**
  6186. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6187. * @module UE
  6188. * @class Editor
  6189. * @event afterSelectionChange
  6190. * @see UE.Editor:selectionchange
  6191. */
  6192. /**
  6193. * 编辑器内容发生改变时会触发该事件
  6194. * @module UE
  6195. * @class Editor
  6196. * @event contentChange
  6197. */
  6198. /**
  6199. * 以默认参数构建一个编辑器实例
  6200. * @constructor
  6201. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6202. * @example
  6203. * ```javascript
  6204. * var editor = new UE.Editor();
  6205. * editor.execCommand('blod');
  6206. * ```
  6207. * @see UE.Config
  6208. */
  6209. /**
  6210. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6211. * @constructor
  6212. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6213. * @param { Object } setting 创建编辑器的参数
  6214. * @example
  6215. * ```javascript
  6216. * var editor = new UE.Editor();
  6217. * editor.execCommand('blod');
  6218. * ```
  6219. * @see UE.Config
  6220. */
  6221. var Editor = UE.Editor = function (options) {
  6222. var me = this;
  6223. me.uid = uid++;
  6224. EventBase.call(me);
  6225. me.commands = {};
  6226. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6227. me.shortcutkeys = {};
  6228. me.inputRules = [];
  6229. me.outputRules = [];
  6230. //设置默认的常用属性
  6231. me.setOpt({
  6232. isShow: true,
  6233. initialContent: '',
  6234. initialStyle:'',
  6235. autoClearinitialContent: false,
  6236. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  6237. textarea: 'editorValue',
  6238. focus: false,
  6239. focusInEnd: true,
  6240. autoClearEmptyNode: true,
  6241. fullscreen: false,
  6242. readonly: false,
  6243. zIndex: 999,
  6244. imagePopup: true,
  6245. enterTag: 'p',
  6246. customDomain: false,
  6247. lang: 'zh-cn',
  6248. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  6249. theme: 'default',
  6250. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  6251. allHtmlEnabled: false,
  6252. scaleEnabled: false,
  6253. tableNativeEditInFF: false,
  6254. autoSyncData : true,
  6255. fileNameFormat: '{time}{rand:6}'
  6256. });
  6257. if(!utils.isEmptyObject(UE.I18N)){
  6258. //修改默认的语言类型
  6259. me.options.lang = checkCurLang(UE.I18N);
  6260. UE.plugin.load(me);
  6261. langReadied(me);
  6262. }else{
  6263. utils.loadFile(document, {
  6264. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6265. tag: "script",
  6266. type: "text/javascript",
  6267. defer: "defer"
  6268. }, function () {
  6269. UE.plugin.load(me);
  6270. langReadied(me);
  6271. });
  6272. }
  6273. UE.instants['ueditorInstant' + me.uid] = me;
  6274. };
  6275. Editor.prototype = {
  6276. /**
  6277. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6278. * @method ready
  6279. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6280. * 立即触发该回调。
  6281. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6282. * @example
  6283. * ```javascript
  6284. * editor.ready( function( editor ) {
  6285. * editor.setContent('初始化完毕');
  6286. * } );
  6287. * ```
  6288. * @see UE.Editor.event:ready
  6289. */
  6290. ready: function (fn) {
  6291. var me = this;
  6292. if (fn) {
  6293. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6294. }
  6295. },
  6296. /**
  6297. * 该方法是提供给插件里面使用,设置配置项默认值
  6298. * @method setOpt
  6299. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6300. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6301. * @param { String } key 编辑器的可接受的选项名称
  6302. * @param { * } val 该选项可接受的值
  6303. * @example
  6304. * ```javascript
  6305. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6306. * ```
  6307. */
  6308. /**
  6309. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6310. * @method setOpt
  6311. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6312. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6313. * @param { Object } options 将要设置的选项的键值对对象
  6314. * @example
  6315. * ```javascript
  6316. * editor.setOpt( {
  6317. * 'initContent': '欢迎使用编辑器'
  6318. * } );
  6319. * ```
  6320. */
  6321. setOpt: function (key, val) {
  6322. var obj = {};
  6323. if (utils.isString(key)) {
  6324. obj[key] = val
  6325. } else {
  6326. obj = key;
  6327. }
  6328. utils.extend(this.options, obj, true);
  6329. },
  6330. /**
  6331. * 销毁编辑器实例,使用textarea代替
  6332. * @method destroy
  6333. * @example
  6334. * ```javascript
  6335. * editor.destroy();
  6336. * ```
  6337. */
  6338. destroy: function () {
  6339. var me = this;
  6340. me.fireEvent('destroy');
  6341. var container = me.container.parentNode;
  6342. var textarea = me.textarea;
  6343. if (!textarea) {
  6344. textarea = document.createElement('textarea');
  6345. container.parentNode.insertBefore(textarea, container);
  6346. } else {
  6347. textarea.style.display = ''
  6348. }
  6349. textarea.style.width = me.iframe.offsetWidth + 'px';
  6350. textarea.style.height = me.iframe.offsetHeight + 'px';
  6351. textarea.value = me.getContent();
  6352. textarea.id = me.key;
  6353. container.innerHTML = '';
  6354. domUtils.remove(container);
  6355. var key = me.key;
  6356. //trace:2004
  6357. for (var p in me) {
  6358. if (me.hasOwnProperty(p)) {
  6359. delete this[p];
  6360. }
  6361. }
  6362. UE.delEditor(key);
  6363. },
  6364. /**
  6365. * 渲染编辑器的DOM到指定容器
  6366. * @method render
  6367. * @param { String } containerId 指定一个容器ID
  6368. * @remind 执行该方法,会触发ready事件
  6369. * @warning 必须且只能调用一次
  6370. */
  6371. /**
  6372. * 渲染编辑器的DOM到指定容器
  6373. * @method render
  6374. * @param { Element } containerDom 直接指定容器对象
  6375. * @remind 执行该方法,会触发ready事件
  6376. * @warning 必须且只能调用一次
  6377. */
  6378. render: function (container) {
  6379. var me = this,
  6380. options = me.options,
  6381. getStyleValue=function(attr){
  6382. return parseInt(domUtils.getComputedStyle(container,attr));
  6383. };
  6384. if (utils.isString(container)) {
  6385. container = document.getElementById(container);
  6386. }
  6387. if (container) {
  6388. if(options.initialFrameWidth){
  6389. options.minFrameWidth = options.initialFrameWidth
  6390. }else{
  6391. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6392. }
  6393. if(options.initialFrameHeight){
  6394. options.minFrameHeight = options.initialFrameHeight
  6395. }else{
  6396. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6397. }
  6398. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6399. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6400. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6401. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6402. container.style.zIndex = options.zIndex;
  6403. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6404. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6405. '<style type=\'text/css\'>' +
  6406. //设置四周的留边
  6407. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6408. //设置默认字体和字号
  6409. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6410. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6411. //设置段落间距
  6412. 'p{margin:5px 0;}</style>' +
  6413. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6414. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6415. '</head><body class=\'view\' ></body>' +
  6416. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6417. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6418. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6419. container.appendChild(domUtils.createElement(document, 'iframe', {
  6420. id: 'ueditor_' + me.uid,
  6421. width: "100%",
  6422. height: "100%",
  6423. frameborder: "0",
  6424. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6425. // scrolling :'no',
  6426. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6427. 'document.write("' + html + '");document.close();}())'
  6428. }));
  6429. container.style.overflow = 'hidden';
  6430. //解决如果是给定的百分比,会导致高度算不对的问题
  6431. setTimeout(function(){
  6432. if( /%$/.test(options.initialFrameWidth)){
  6433. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6434. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6435. // container.style.width = options.initialFrameWidth + 'px';
  6436. }
  6437. if(/%$/.test(options.initialFrameHeight)){
  6438. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6439. container.style.height = options.initialFrameHeight + 'px';
  6440. }
  6441. })
  6442. }
  6443. },
  6444. /**
  6445. * 编辑器初始化
  6446. * @method _setup
  6447. * @private
  6448. * @param { Element } doc 编辑器Iframe中的文档对象
  6449. */
  6450. _setup: function (doc) {
  6451. var me = this,
  6452. options = me.options;
  6453. if (ie) {
  6454. doc.body.disabled = true;
  6455. doc.body.contentEditable = true;
  6456. doc.body.disabled = false;
  6457. } else {
  6458. doc.body.contentEditable = true;
  6459. }
  6460. doc.body.spellcheck = false;
  6461. me.document = doc;
  6462. me.window = doc.defaultView || doc.parentWindow;
  6463. me.iframe = me.window.frameElement;
  6464. me.body = doc.body;
  6465. me.selection = new dom.Selection(doc);
  6466. //gecko初始化就能得到range,无法判断isFocus了
  6467. var geckoSel;
  6468. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6469. geckoSel.removeAllRanges();
  6470. }
  6471. this._initEvents();
  6472. //为form提交提供一个隐藏的textarea
  6473. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6474. if (form.tagName == 'FORM') {
  6475. me.form = form;
  6476. if(me.options.autoSyncData){
  6477. domUtils.on(me.window,'blur',function(){
  6478. setValue(form,me);
  6479. });
  6480. }else{
  6481. domUtils.on(form, 'submit', function () {
  6482. setValue(this, me);
  6483. });
  6484. }
  6485. break;
  6486. }
  6487. }
  6488. if (options.initialContent) {
  6489. if (options.autoClearinitialContent) {
  6490. var oldExecCommand = me.execCommand;
  6491. me.execCommand = function () {
  6492. me.fireEvent('firstBeforeExecCommand');
  6493. return oldExecCommand.apply(me, arguments);
  6494. };
  6495. this._setDefaultContent(options.initialContent);
  6496. } else
  6497. this.setContent(options.initialContent, false, true);
  6498. }
  6499. //编辑器不能为空内容
  6500. if (domUtils.isEmptyNode(me.body)) {
  6501. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6502. }
  6503. //如果要求focus, 就把光标定位到内容开始
  6504. if (options.focus) {
  6505. setTimeout(function () {
  6506. me.focus(me.options.focusInEnd);
  6507. //如果自动清除开着,就不需要做selectionchange;
  6508. !me.options.autoClearinitialContent && me._selectionChange();
  6509. }, 0);
  6510. }
  6511. if (!me.container) {
  6512. me.container = this.iframe.parentNode;
  6513. }
  6514. if (options.fullscreen && me.ui) {
  6515. me.ui.setFullScreen(true);
  6516. }
  6517. try {
  6518. me.document.execCommand('2D-position', false, false);
  6519. } catch (e) {
  6520. }
  6521. try {
  6522. me.document.execCommand('enableInlineTableEditing', false, false);
  6523. } catch (e) {
  6524. }
  6525. try {
  6526. me.document.execCommand('enableObjectResizing', false, false);
  6527. } catch (e) {
  6528. }
  6529. //挂接快捷键
  6530. me._bindshortcutKeys();
  6531. me.isReady = 1;
  6532. me.fireEvent('ready');
  6533. options.onready && options.onready.call(me);
  6534. if (!browser.ie9below) {
  6535. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6536. //chrome下会出现alt+tab切换时,导致选区位置不对
  6537. if (e.type == 'blur') {
  6538. me._bakRange = me.selection.getRange();
  6539. try {
  6540. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6541. me.selection.getNative().removeAllRanges();
  6542. } catch (e) {
  6543. me._bakNativeRange = null;
  6544. }
  6545. } else {
  6546. try {
  6547. me._bakRange && me._bakRange.select();
  6548. } catch (e) {
  6549. }
  6550. }
  6551. });
  6552. }
  6553. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6554. if (browser.gecko && browser.version <= 10902) {
  6555. //修复ff3.6初始化进来,不能点击获得焦点
  6556. me.body.contentEditable = false;
  6557. setTimeout(function () {
  6558. me.body.contentEditable = true;
  6559. }, 100);
  6560. setInterval(function () {
  6561. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6562. }, 100)
  6563. }
  6564. !options.isShow && me.setHide();
  6565. options.readonly && me.setDisabled();
  6566. },
  6567. /**
  6568. * 同步数据到编辑器所在的form
  6569. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6570. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6571. * @method sync
  6572. * @example
  6573. * ```javascript
  6574. * editor.sync();
  6575. * form.sumbit(); //form变量已经指向了form元素
  6576. * ```
  6577. */
  6578. /**
  6579. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6580. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6581. * @method sync
  6582. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6583. */
  6584. sync: function (formId) {
  6585. var me = this,
  6586. form = formId ? document.getElementById(formId) :
  6587. domUtils.findParent(me.iframe.parentNode, function (node) {
  6588. return node.tagName == 'FORM'
  6589. }, true);
  6590. form && setValue(form, me);
  6591. },
  6592. /**
  6593. * 设置编辑器高度
  6594. * @method setHeight
  6595. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6596. * @param { Number } number 设置的高度值,纯数值,不带单位
  6597. * @example
  6598. * ```javascript
  6599. * editor.setHeight(number);
  6600. * ```
  6601. */
  6602. setHeight: function (height,notSetHeight) {
  6603. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6604. this.iframe.parentNode.style.height = height + 'px';
  6605. }
  6606. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6607. this.body.style.height = height + 'px';
  6608. },
  6609. /**
  6610. * 为编辑器的编辑命令提供快捷键
  6611. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6612. * @method addshortcutkey
  6613. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6614. * @example
  6615. * ```javascript
  6616. * editor.addshortcutkey({
  6617. * "Bold" : "ctrl+66",//^B
  6618. * "Italic" : "ctrl+73", //^I
  6619. * });
  6620. * ```
  6621. */
  6622. /**
  6623. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6624. * @method addshortcutkey
  6625. * @param { String } cmd 触发快捷键时,响应的命令
  6626. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6627. * @example
  6628. * ```javascript
  6629. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6630. * ```
  6631. */
  6632. addshortcutkey: function (cmd, keys) {
  6633. var obj = {};
  6634. if (keys) {
  6635. obj[cmd] = keys
  6636. } else {
  6637. obj = cmd;
  6638. }
  6639. utils.extend(this.shortcutkeys, obj)
  6640. },
  6641. /**
  6642. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6643. * @method _bindshortcutKeys
  6644. * @private
  6645. */
  6646. _bindshortcutKeys: function () {
  6647. var me = this, shortcutkeys = this.shortcutkeys;
  6648. me.addListener('keydown', function (type, e) {
  6649. var keyCode = e.keyCode || e.which;
  6650. for (var i in shortcutkeys) {
  6651. var tmp = shortcutkeys[i].split(',');
  6652. for (var t = 0, ti; ti = tmp[t++];) {
  6653. ti = ti.split(':');
  6654. var key = ti[0], param = ti[1];
  6655. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6656. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6657. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6658. && keyCode == RegExp.$3
  6659. ) ||
  6660. keyCode == RegExp.$1
  6661. ) {
  6662. if (me.queryCommandState(i,param) != -1)
  6663. me.execCommand(i, param);
  6664. domUtils.preventDefault(e);
  6665. }
  6666. }
  6667. }
  6668. }
  6669. });
  6670. },
  6671. /**
  6672. * 获取编辑器的内容
  6673. * @method getContent
  6674. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6675. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6676. * @example
  6677. * ```javascript
  6678. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6679. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6680. * ```
  6681. */
  6682. /**
  6683. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6684. * @method getContent
  6685. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6686. * 代表当前编辑器的内容是否空,
  6687. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6688. * 经过内置过滤规则处理后的内容。
  6689. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6690. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6691. * @return { String } 编辑器的内容字符串
  6692. * @example
  6693. * ```javascript
  6694. * // editor 是一个编辑器的实例
  6695. * var content = editor.getContent( function ( editor ) {
  6696. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6697. * } );
  6698. * ```
  6699. */
  6700. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6701. var me = this;
  6702. if (cmd && utils.isFunction(cmd)) {
  6703. fn = cmd;
  6704. cmd = '';
  6705. }
  6706. if (fn ? !fn() : !this.hasContents()) {
  6707. return '';
  6708. }
  6709. me.fireEvent('beforegetcontent');
  6710. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6711. me.filterOutputRule(root);
  6712. me.fireEvent('aftergetcontent', cmd,root);
  6713. return root.toHtml(formatter);
  6714. },
  6715. /**
  6716. * 取得完整的html代码,可以直接显示成完整的html文档
  6717. * @method getAllHtml
  6718. * @return { String } 编辑器的内容html文档字符串
  6719. * @eaxmple
  6720. * ```javascript
  6721. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6722. * ```
  6723. */
  6724. getAllHtml: function () {
  6725. var me = this,
  6726. headHtml = [],
  6727. html = '';
  6728. me.fireEvent('getAllHtml', headHtml);
  6729. if (browser.ie && browser.version > 8) {
  6730. var headHtmlForIE9 = '';
  6731. utils.each(me.document.styleSheets, function (si) {
  6732. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6733. });
  6734. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6735. headHtmlForIE9 += si.outerHTML;
  6736. });
  6737. }
  6738. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6739. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6740. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6741. },
  6742. /**
  6743. * 得到编辑器的纯文本内容,但会保留段落格式
  6744. * @method getPlainTxt
  6745. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6746. * @example
  6747. * ```javascript
  6748. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6749. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6750. * ```
  6751. */
  6752. getPlainTxt: function () {
  6753. var reg = new RegExp(domUtils.fillChar, 'g'),
  6754. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6755. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6756. .replace(/<br\/?>/gi, '\n')
  6757. .replace(/<[^>/]+>/g, '')
  6758. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6759. return dtd.$block[c] ? '\n' : b ? b : '';
  6760. });
  6761. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6762. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6763. },
  6764. /**
  6765. * 获取编辑器中的纯文本内容,没有段落格式
  6766. * @method getContentTxt
  6767. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6768. * @example
  6769. * ```javascript
  6770. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6771. * console.log(editor.getPlainTxt()); //输出:"12
  6772. * ```
  6773. */
  6774. getContentTxt: function () {
  6775. var reg = new RegExp(domUtils.fillChar, 'g');
  6776. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6777. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6778. },
  6779. /**
  6780. * 设置编辑器的内容,可修改编辑器当前的html内容
  6781. * @method setContent
  6782. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6783. * @warning 该方法会触发selectionchange事件
  6784. * @param { String } html 要插入的html内容
  6785. * @example
  6786. * ```javascript
  6787. * editor.getContent('<p>test</p>');
  6788. * ```
  6789. */
  6790. /**
  6791. * 设置编辑器的内容,可修改编辑器当前的html内容
  6792. * @method setContent
  6793. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6794. * @warning 该方法会触发selectionchange事件
  6795. * @param { String } html 要插入的html内容
  6796. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6797. * @example
  6798. * ```javascript
  6799. * //假设设置前的编辑器内容是 <p>old text</p>
  6800. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6801. * ```
  6802. */
  6803. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6804. var me = this;
  6805. me.fireEvent('beforesetcontent', html);
  6806. var root = UE.htmlparser(html);
  6807. me.filterInputRule(root);
  6808. html = root.toHtml();
  6809. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6810. function isCdataDiv(node){
  6811. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6812. }
  6813. //给文本或者inline节点套p标签
  6814. if (me.options.enterTag == 'p') {
  6815. var child = this.body.firstChild, tmpNode;
  6816. if (!child || child.nodeType == 1 &&
  6817. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  6818. domUtils.isCustomeNode(child)
  6819. )
  6820. && child === this.body.lastChild) {
  6821. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  6822. } else {
  6823. var p = me.document.createElement('p');
  6824. while (child) {
  6825. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  6826. tmpNode = child.nextSibling;
  6827. p.appendChild(child);
  6828. child = tmpNode;
  6829. }
  6830. if (p.firstChild) {
  6831. if (!child) {
  6832. me.body.appendChild(p);
  6833. break;
  6834. } else {
  6835. child.parentNode.insertBefore(p, child);
  6836. p = me.document.createElement('p');
  6837. }
  6838. }
  6839. child = child.nextSibling;
  6840. }
  6841. }
  6842. }
  6843. me.fireEvent('aftersetcontent');
  6844. me.fireEvent('contentchange');
  6845. !notFireSelectionchange && me._selectionChange();
  6846. //清除保存的选区
  6847. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  6848. //trace:1742 setContent后gecko能得到焦点问题
  6849. var geckoSel;
  6850. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6851. geckoSel.removeAllRanges();
  6852. }
  6853. if(me.options.autoSyncData){
  6854. me.form && setValue(me.form,me);
  6855. }
  6856. },
  6857. /**
  6858. * 让编辑器获得焦点,默认focus到编辑器头部
  6859. * @method focus
  6860. * @example
  6861. * ```javascript
  6862. * editor.focus()
  6863. * ```
  6864. */
  6865. /**
  6866. * 让编辑器获得焦点,toEnd确定focus位置
  6867. * @method focus
  6868. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  6869. * @example
  6870. * ```javascript
  6871. * editor.focus(true)
  6872. * ```
  6873. */
  6874. focus: function (toEnd) {
  6875. try {
  6876. var me = this,
  6877. rng = me.selection.getRange();
  6878. if (toEnd) {
  6879. var node = me.body.lastChild;
  6880. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6881. if(domUtils.isEmptyBlock(node)){
  6882. rng.setStartAtFirst(node)
  6883. }else{
  6884. rng.setStartAtLast(node)
  6885. }
  6886. rng.collapse(true);
  6887. }
  6888. rng.setCursor(true);
  6889. } else {
  6890. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  6891. var node = me.body.firstChild;
  6892. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6893. rng.setStartAtFirst(node).collapse(true);
  6894. }
  6895. }
  6896. rng.select(true);
  6897. }
  6898. this.fireEvent('focus selectionchange');
  6899. } catch (e) {
  6900. }
  6901. },
  6902. isFocus:function(){
  6903. return this.selection.isFocus();
  6904. },
  6905. blur:function(){
  6906. var sel = this.selection.getNative();
  6907. if(sel.empty && browser.ie){
  6908. var nativeRng = document.body.createTextRange();
  6909. nativeRng.moveToElementText(document.body);
  6910. nativeRng.collapse(true);
  6911. nativeRng.select();
  6912. sel.empty()
  6913. }else{
  6914. sel.removeAllRanges()
  6915. }
  6916. //this.fireEvent('blur selectionchange');
  6917. },
  6918. /**
  6919. * 初始化UE事件及部分事件代理
  6920. * @method _initEvents
  6921. * @private
  6922. */
  6923. _initEvents: function () {
  6924. var me = this,
  6925. doc = me.document,
  6926. win = me.window;
  6927. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  6928. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  6929. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  6930. domUtils.on(me.body,'drop',function(e){
  6931. //阻止ff下默认的弹出新页面打开图片
  6932. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  6933. me.fireEvent('contentchange')
  6934. });
  6935. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  6936. //特殊键不触发selectionchange
  6937. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  6938. return;
  6939. }
  6940. if (evt.button == 2)return;
  6941. me._selectionChange(250, evt);
  6942. });
  6943. },
  6944. /**
  6945. * 触发事件代理
  6946. * @method _proxyDomEvent
  6947. * @private
  6948. * @return { * } fireEvent的返回值
  6949. * @see UE.EventBase:fireEvent(String)
  6950. */
  6951. _proxyDomEvent: function (evt) {
  6952. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  6953. return false;
  6954. }
  6955. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  6956. return false;
  6957. }
  6958. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  6959. },
  6960. /**
  6961. * 变化选区
  6962. * @method _selectionChange
  6963. * @private
  6964. */
  6965. _selectionChange: function (delay, evt) {
  6966. var me = this;
  6967. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  6968. // if ( !me.selection.isFocus() ){
  6969. // return;
  6970. // }
  6971. var hackForMouseUp = false;
  6972. var mouseX, mouseY;
  6973. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  6974. var range = this.selection.getRange();
  6975. if (!range.collapsed) {
  6976. hackForMouseUp = true;
  6977. mouseX = evt.clientX;
  6978. mouseY = evt.clientY;
  6979. }
  6980. }
  6981. clearTimeout(_selectionChangeTimer);
  6982. _selectionChangeTimer = setTimeout(function () {
  6983. if (!me.selection || !me.selection.getNative()) {
  6984. return;
  6985. }
  6986. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  6987. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  6988. var ieRange;
  6989. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  6990. ieRange = me.document.body.createTextRange();
  6991. try {
  6992. ieRange.moveToPoint(mouseX, mouseY);
  6993. } catch (ex) {
  6994. ieRange = null;
  6995. }
  6996. }
  6997. var bakGetIERange;
  6998. if (ieRange) {
  6999. bakGetIERange = me.selection.getIERange;
  7000. me.selection.getIERange = function () {
  7001. return ieRange;
  7002. };
  7003. }
  7004. me.selection.cache();
  7005. if (bakGetIERange) {
  7006. me.selection.getIERange = bakGetIERange;
  7007. }
  7008. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7009. me.fireEvent('beforeselectionchange');
  7010. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7011. me.fireEvent('selectionchange', !!evt);
  7012. me.fireEvent('afterselectionchange');
  7013. me.selection.clear();
  7014. }
  7015. }, delay || 50);
  7016. },
  7017. /**
  7018. * 执行编辑命令
  7019. * @method _callCmdFn
  7020. * @private
  7021. * @param { String } fnName 函数名称
  7022. * @param { * } args 传给命令函数的参数
  7023. * @return { * } 返回命令函数运行的返回值
  7024. */
  7025. _callCmdFn: function (fnName, args) {
  7026. var cmdName = args[0].toLowerCase(),
  7027. cmd, cmdFn;
  7028. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7029. cmdFn = cmd && cmd[fnName];
  7030. //没有querycommandstate或者没有command的都默认返回0
  7031. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7032. return 0;
  7033. } else if (cmdFn) {
  7034. return cmdFn.apply(this, args);
  7035. }
  7036. },
  7037. /**
  7038. * 执行编辑命令cmdName,完成富文本编辑效果
  7039. * @method execCommand
  7040. * @param { String } cmdName 需要执行的命令
  7041. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7042. * @return { * } 返回命令函数运行的返回值
  7043. * @example
  7044. * ```javascript
  7045. * editor.execCommand(cmdName);
  7046. * ```
  7047. */
  7048. execCommand: function (cmdName) {
  7049. cmdName = cmdName.toLowerCase();
  7050. var me = this,
  7051. result,
  7052. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7053. if (!cmd || !cmd.execCommand) {
  7054. return null;
  7055. }
  7056. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7057. me.__hasEnterExecCommand = true;
  7058. if (me.queryCommandState.apply(me,arguments) != -1) {
  7059. me.fireEvent('saveScene');
  7060. me.fireEvent('beforeexeccommand', cmdName);
  7061. result = this._callCmdFn('execCommand', arguments);
  7062. (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7063. me.fireEvent('afterexeccommand', cmdName);
  7064. me.fireEvent('saveScene');
  7065. }
  7066. me.__hasEnterExecCommand = false;
  7067. } else {
  7068. result = this._callCmdFn('execCommand', arguments);
  7069. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7070. }
  7071. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7072. return result;
  7073. },
  7074. /**
  7075. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7076. * @method queryCommandState
  7077. * @param { String } cmdName 需要查询的命令名称
  7078. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7079. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7080. * @example
  7081. * ```javascript
  7082. * editor.queryCommandState(cmdName) => (-1|0|1)
  7083. * ```
  7084. * @see COMMAND.LIST
  7085. */
  7086. queryCommandState: function (cmdName) {
  7087. return this._callCmdFn('queryCommandState', arguments);
  7088. },
  7089. /**
  7090. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7091. * @method queryCommandValue
  7092. * @param { String } cmdName 需要查询的命令名称
  7093. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7094. * @remind 只有部分插件有此方法
  7095. * @return { * } 返回每个命令特定的当前状态值
  7096. * @grammar editor.queryCommandValue(cmdName) => {*}
  7097. * @see COMMAND.LIST
  7098. */
  7099. queryCommandValue: function (cmdName) {
  7100. return this._callCmdFn('queryCommandValue', arguments);
  7101. },
  7102. /**
  7103. * 检查编辑区域中是否有内容
  7104. * @method hasContents
  7105. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7106. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7107. * @return { Boolean } 检查有内容返回true,否则返回false
  7108. * @example
  7109. * ```javascript
  7110. * editor.hasContents()
  7111. * ```
  7112. */
  7113. /**
  7114. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7115. * @method hasContents
  7116. * @param { Array } tags 传入数组判断时用到的节点类型
  7117. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7118. * @example
  7119. * ```javascript
  7120. * editor.hasContents(['span']);
  7121. * ```
  7122. */
  7123. hasContents: function (tags) {
  7124. if (tags) {
  7125. for (var i = 0, ci; ci = tags[i++];) {
  7126. if (this.document.getElementsByTagName(ci).length > 0) {
  7127. return true;
  7128. }
  7129. }
  7130. }
  7131. if (!domUtils.isEmptyBlock(this.body)) {
  7132. return true
  7133. }
  7134. //随时添加,定义的特殊标签如果存在,不能认为是空
  7135. tags = ['div'];
  7136. for (i = 0; ci = tags[i++];) {
  7137. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7138. for (var n = 0, cn; cn = nodes[n++];) {
  7139. if (domUtils.isCustomeNode(cn)) {
  7140. return true;
  7141. }
  7142. }
  7143. }
  7144. return false;
  7145. },
  7146. /**
  7147. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7148. * @method reset
  7149. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7150. * @example
  7151. * ```javascript
  7152. * editor.reset()
  7153. * ```
  7154. */
  7155. reset: function () {
  7156. this.fireEvent('reset');
  7157. },
  7158. /**
  7159. * 设置当前编辑区域可以编辑
  7160. * @method setEnabled
  7161. * @example
  7162. * ```javascript
  7163. * editor.setEnabled()
  7164. * ```
  7165. */
  7166. setEnabled: function () {
  7167. var me = this, range;
  7168. if (me.body.contentEditable == 'false') {
  7169. me.body.contentEditable = true;
  7170. range = me.selection.getRange();
  7171. //有可能内容丢失了
  7172. try {
  7173. range.moveToBookmark(me.lastBk);
  7174. delete me.lastBk
  7175. } catch (e) {
  7176. range.setStartAtFirst(me.body).collapse(true)
  7177. }
  7178. range.select(true);
  7179. if (me.bkqueryCommandState) {
  7180. me.queryCommandState = me.bkqueryCommandState;
  7181. delete me.bkqueryCommandState;
  7182. }
  7183. me.fireEvent('selectionchange');
  7184. }
  7185. },
  7186. enable: function () {
  7187. return this.setEnabled();
  7188. },
  7189. /** 设置当前编辑区域不可编辑
  7190. * @method setDisabled
  7191. */
  7192. /** 设置当前编辑区域不可编辑,except中的命令除外
  7193. * @method setDisabled
  7194. * @param { String } except 例外命令的字符串
  7195. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7196. * @example
  7197. * ```javascript
  7198. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7199. * ```
  7200. */
  7201. /** 设置当前编辑区域不可编辑,except中的命令除外
  7202. * @method setDisabled
  7203. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7204. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7205. * @example
  7206. * ```javascript
  7207. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7208. * ```
  7209. */
  7210. setDisabled: function (except) {
  7211. var me = this;
  7212. except = except ? utils.isArray(except) ? except : [except] : [];
  7213. if (me.body.contentEditable == 'true') {
  7214. if (!me.lastBk) {
  7215. me.lastBk = me.selection.getRange().createBookmark(true);
  7216. }
  7217. me.body.contentEditable = false;
  7218. me.bkqueryCommandState = me.queryCommandState;
  7219. me.queryCommandState = function (type) {
  7220. if (utils.indexOf(except, type) != -1) {
  7221. return me.bkqueryCommandState.apply(me, arguments);
  7222. }
  7223. return -1;
  7224. };
  7225. me.fireEvent('selectionchange');
  7226. }
  7227. },
  7228. disable: function (except) {
  7229. return this.setDisabled(except);
  7230. },
  7231. /**
  7232. * 设置默认内容
  7233. * @method _setDefaultContent
  7234. * @private
  7235. * @param { String } cont 要存入的内容
  7236. */
  7237. _setDefaultContent: function () {
  7238. function clear() {
  7239. var me = this;
  7240. if (me.document.getElementById('initContent')) {
  7241. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7242. me.removeListener('firstBeforeExecCommand focus', clear);
  7243. setTimeout(function () {
  7244. me.focus();
  7245. me._selectionChange();
  7246. }, 0)
  7247. }
  7248. }
  7249. return function (cont) {
  7250. var me = this;
  7251. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7252. me.addListener('firstBeforeExecCommand focus', clear);
  7253. }
  7254. }(),
  7255. /**
  7256. * 显示编辑器
  7257. * @method setShow
  7258. * @example
  7259. * ```javascript
  7260. * editor.setShow()
  7261. * ```
  7262. */
  7263. setShow: function () {
  7264. var me = this, range = me.selection.getRange();
  7265. if (me.container.style.display == 'none') {
  7266. //有可能内容丢失了
  7267. try {
  7268. range.moveToBookmark(me.lastBk);
  7269. delete me.lastBk
  7270. } catch (e) {
  7271. range.setStartAtFirst(me.body).collapse(true)
  7272. }
  7273. //ie下focus实效,所以做了个延迟
  7274. setTimeout(function () {
  7275. range.select(true);
  7276. }, 100);
  7277. me.container.style.display = '';
  7278. }
  7279. },
  7280. show: function () {
  7281. return this.setShow();
  7282. },
  7283. /**
  7284. * 隐藏编辑器
  7285. * @method setHide
  7286. * @example
  7287. * ```javascript
  7288. * editor.setHide()
  7289. * ```
  7290. */
  7291. setHide: function () {
  7292. var me = this;
  7293. if (!me.lastBk) {
  7294. me.lastBk = me.selection.getRange().createBookmark(true);
  7295. }
  7296. me.container.style.display = 'none'
  7297. },
  7298. hide: function () {
  7299. return this.setHide();
  7300. },
  7301. /**
  7302. * 根据指定的路径,获取对应的语言资源
  7303. * @method getLang
  7304. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7305. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7306. * @example
  7307. * ```javascript
  7308. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7309. * ```
  7310. */
  7311. getLang: function (path) {
  7312. var lang = UE.I18N[this.options.lang];
  7313. if (!lang) {
  7314. throw Error("not import language file");
  7315. }
  7316. path = (path || "").split(".");
  7317. for (var i = 0, ci; ci = path[i++];) {
  7318. lang = lang[ci];
  7319. if (!lang)break;
  7320. }
  7321. return lang;
  7322. },
  7323. /**
  7324. * 计算编辑器html内容字符串的长度
  7325. * @method getContentLength
  7326. * @return { Number } 返回计算的长度
  7327. * @example
  7328. * ```javascript
  7329. * //编辑器html内容<p><strong>132</strong></p>
  7330. * editor.getContentLength() //返回27
  7331. * ```
  7332. */
  7333. /**
  7334. * 计算编辑器当前纯文本内容的长度
  7335. * @method getContentLength
  7336. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7337. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7338. * @example
  7339. * ```javascript
  7340. * //编辑器html内容<p><strong>132</strong></p>
  7341. * editor.getContentLength() //返回3
  7342. * ```
  7343. */
  7344. getContentLength: function (ingoneHtml, tagNames) {
  7345. var count = this.getContent(false,false,true).length;
  7346. if (ingoneHtml) {
  7347. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7348. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7349. for (var i = 0, ci; ci = tagNames[i++];) {
  7350. count += this.document.getElementsByTagName(ci).length;
  7351. }
  7352. }
  7353. return count;
  7354. },
  7355. /**
  7356. * 注册输入过滤规则
  7357. * @method addInputRule
  7358. * @param { Function } rule 要添加的过滤规则
  7359. * @example
  7360. * ```javascript
  7361. * editor.addInputRule(function(root){
  7362. * $.each(root.getNodesByTagName('div'),function(i,node){
  7363. * node.tagName="p";
  7364. * });
  7365. * });
  7366. * ```
  7367. */
  7368. addInputRule: function (rule) {
  7369. this.inputRules.push(rule);
  7370. },
  7371. /**
  7372. * 执行注册的过滤规则
  7373. * @method filterInputRule
  7374. * @param { UE.uNode } root 要过滤的uNode节点
  7375. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7376. * @example
  7377. * ```javascript
  7378. * editor.filterInputRule(editor.body);
  7379. * ```
  7380. * @see UE.Editor:addInputRule
  7381. */
  7382. filterInputRule: function (root) {
  7383. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7384. ci.call(this, root)
  7385. }
  7386. },
  7387. /**
  7388. * 注册输出过滤规则
  7389. * @method addOutputRule
  7390. * @param { Function } rule 要添加的过滤规则
  7391. * @example
  7392. * ```javascript
  7393. * editor.addOutputRule(function(root){
  7394. * $.each(root.getNodesByTagName('p'),function(i,node){
  7395. * node.tagName="div";
  7396. * });
  7397. * });
  7398. * ```
  7399. */
  7400. addOutputRule: function (rule) {
  7401. this.outputRules.push(rule)
  7402. },
  7403. /**
  7404. * 根据输出过滤规则,过滤编辑器内容
  7405. * @method filterOutputRule
  7406. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7407. * @param { UE.uNode } root 要过滤的uNode节点
  7408. * @example
  7409. * ```javascript
  7410. * editor.filterOutputRule(editor.body);
  7411. * ```
  7412. * @see UE.Editor:addOutputRule
  7413. */
  7414. filterOutputRule: function (root) {
  7415. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7416. ci.call(this, root)
  7417. }
  7418. }
  7419. };
  7420. utils.inherits(Editor, EventBase);
  7421. })();
  7422. /**
  7423. * @file
  7424. * @module UE.ajax
  7425. * @since 1.2.6.1
  7426. */
  7427. /**
  7428. * 提供对ajax请求的支持
  7429. * @module UE.ajax
  7430. */
  7431. UE.ajax = function() {
  7432. //创建一个ajaxRequest对象
  7433. var fnStr = 'XMLHttpRequest()';
  7434. try {
  7435. new ActiveXObject("Msxml2.XMLHTTP");
  7436. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7437. } catch (e) {
  7438. try {
  7439. new ActiveXObject("Microsoft.XMLHTTP");
  7440. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7441. } catch (e) {
  7442. }
  7443. }
  7444. var creatAjaxRequest = new Function('return new ' + fnStr);
  7445. /*
  7446. * 将json参数转化成适合ajax提交的参数列表
  7447. * @param json
  7448. */
  7449. function json2str(json) {
  7450. var strArr = [];
  7451. for (var i in json) {
  7452. //忽略默认的几个参数
  7453. if(i=="method" || i=="timeout" || i=="async") continue;
  7454. //传递过来的对象和函数不在提交之列
  7455. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7456. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7457. }
  7458. }
  7459. return strArr.join("&");
  7460. }
  7461. return {
  7462. /**
  7463. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7464. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7465. * @method request
  7466. * @param { URLString } url ajax请求的url地址
  7467. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7468. * @example
  7469. * ```javascript
  7470. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7471. * UE.ajax.requeset( 'sayhello.php', {
  7472. *
  7473. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7474. * method: 'GET',
  7475. *
  7476. * //超时时间。 默认为5000, 单位是ms
  7477. * timeout: 10000,
  7478. *
  7479. * //是否是异步请求。 true为异步请求, false为同步请求
  7480. * async: true,
  7481. *
  7482. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7483. * data: {
  7484. * name: 'ueditor'
  7485. * },
  7486. *
  7487. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7488. * onsuccess: function ( xhr ) {
  7489. * console.log( xhr.responseText );
  7490. * },
  7491. *
  7492. * //请求失败或者超时后的回调。
  7493. * onerror: function ( xhr ) {
  7494. * alert( 'Ajax请求失败' );
  7495. * }
  7496. *
  7497. * } );
  7498. * ```
  7499. */
  7500. /**
  7501. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7502. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7503. * @method request
  7504. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7505. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7506. * @example
  7507. * ```javascript
  7508. *
  7509. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7510. * UE.ajax.requeset( 'sayhello.php', {
  7511. *
  7512. * //请求的地址, 该项是必须的。
  7513. * url: 'sayhello.php'
  7514. *
  7515. * } );
  7516. * ```
  7517. */
  7518. request:function(url, ajaxOptions) {
  7519. var ajaxRequest = creatAjaxRequest(),
  7520. //是否超时
  7521. timeIsOut = false,
  7522. //默认参数
  7523. defaultAjaxOptions = {
  7524. method:"POST",
  7525. timeout:5000,
  7526. async:true,
  7527. data:{},//需要传递对象的话只能覆盖
  7528. onsuccess:function() {
  7529. },
  7530. onerror:function() {
  7531. }
  7532. };
  7533. if (typeof url === "object") {
  7534. ajaxOptions = url;
  7535. url = ajaxOptions.url;
  7536. }
  7537. if (!ajaxRequest || !url) return;
  7538. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7539. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7540. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7541. if (!utils.isEmptyObject(ajaxOpts.data)){
  7542. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7543. }
  7544. //超时检测
  7545. var timerID = setTimeout(function() {
  7546. if (ajaxRequest.readyState != 4) {
  7547. timeIsOut = true;
  7548. ajaxRequest.abort();
  7549. clearTimeout(timerID);
  7550. }
  7551. }, ajaxOpts.timeout);
  7552. var method = ajaxOpts.method.toUpperCase();
  7553. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7554. ajaxRequest.open(method, str, ajaxOpts.async);
  7555. ajaxRequest.onreadystatechange = function() {
  7556. if (ajaxRequest.readyState == 4) {
  7557. if (!timeIsOut && ajaxRequest.status == 200) {
  7558. ajaxOpts.onsuccess(ajaxRequest);
  7559. } else {
  7560. ajaxOpts.onerror(ajaxRequest);
  7561. }
  7562. }
  7563. };
  7564. if (method == "POST") {
  7565. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7566. ajaxRequest.send(submitStr);
  7567. } else {
  7568. ajaxRequest.send(null);
  7569. }
  7570. }
  7571. };
  7572. }();
  7573. /**
  7574. * UE过滤word的静态方法
  7575. * @file
  7576. */
  7577. /**
  7578. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7579. * @module UE
  7580. */
  7581. /**
  7582. * 根据传入html字符串过滤word
  7583. * @module UE
  7584. * @since 1.2.6.1
  7585. * @method filterWord
  7586. * @param { String } html html字符串
  7587. * @return { String } 已过滤后的结果字符串
  7588. * @example
  7589. * ```javascript
  7590. * UE.filterWord(html);
  7591. * ```
  7592. */
  7593. var filterWord = UE.filterWord = function () {
  7594. //是否是word过来的内容
  7595. function isWordDocument( str ) {
  7596. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  7597. }
  7598. //去掉小数
  7599. function transUnit( v ) {
  7600. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  7601. return utils.transUnitToPx(m);
  7602. } );
  7603. return v;
  7604. }
  7605. function filterPasteWord( str ) {
  7606. return str.replace(/[\t\r\n]+/g,' ')
  7607. .replace( /<!--[\s\S]*?-->/ig, "" )
  7608. //转换图片
  7609. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  7610. //opera能自己解析出image所这里直接返回空
  7611. if(browser.opera){
  7612. return '';
  7613. }
  7614. try{
  7615. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  7616. if(/Bitmap/i.test(str)){
  7617. return '';
  7618. }
  7619. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  7620. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  7621. src = str.match(/src=\s*"([^"]*)"/i)[1];
  7622. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  7623. } catch(e){
  7624. return '';
  7625. }
  7626. })
  7627. //针对wps添加的多余标签处理
  7628. .replace(/<\/?div[^>]*>/g,'')
  7629. //去掉多余的属性
  7630. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  7631. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  7632. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  7633. //去掉多余的属性
  7634. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  7635. //保留list的标示
  7636. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  7637. })
  7638. //清除多余的font/span不能匹配&nbsp;有可能是空格
  7639. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  7640. return c.replace(/[\t\r\n ]+/g,' ')
  7641. })
  7642. //处理style的问题
  7643. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  7644. var n = [],
  7645. s = style.replace( /^\s+|\s+$/, '' )
  7646. .replace(/&#39;/g,'\'')
  7647. .replace( /&quot;/gi, "'" )
  7648. .split( /;\s*/g );
  7649. for ( var i = 0,v; v = s[i];i++ ) {
  7650. var name, value,
  7651. parts = v.split( ":" );
  7652. if ( parts.length == 2 ) {
  7653. name = parts[0].toLowerCase();
  7654. value = parts[1].toLowerCase();
  7655. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  7656. ||
  7657. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  7658. ){
  7659. continue;
  7660. }
  7661. switch ( name ) {
  7662. case "mso-padding-alt":
  7663. case "mso-padding-top-alt":
  7664. case "mso-padding-right-alt":
  7665. case "mso-padding-bottom-alt":
  7666. case "mso-padding-left-alt":
  7667. case "mso-margin-alt":
  7668. case "mso-margin-top-alt":
  7669. case "mso-margin-right-alt":
  7670. case "mso-margin-bottom-alt":
  7671. case "mso-margin-left-alt":
  7672. //ie下会出现挤到一起的情况
  7673. //case "mso-table-layout-alt":
  7674. case "mso-height":
  7675. case "mso-width":
  7676. case "mso-vertical-align-alt":
  7677. //trace:1819 ff下会解析出padding在table上
  7678. if(!/<table/.test(tag))
  7679. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  7680. continue;
  7681. case "horiz-align":
  7682. n[i] = "text-align:" + value;
  7683. continue;
  7684. case "vert-align":
  7685. n[i] = "vertical-align:" + value;
  7686. continue;
  7687. case "font-color":
  7688. case "mso-foreground":
  7689. n[i] = "color:" + value;
  7690. continue;
  7691. case "mso-background":
  7692. case "mso-highlight":
  7693. n[i] = "background:" + value;
  7694. continue;
  7695. case "mso-default-height":
  7696. n[i] = "min-height:" + transUnit( value );
  7697. continue;
  7698. case "mso-default-width":
  7699. n[i] = "min-width:" + transUnit( value );
  7700. continue;
  7701. case "mso-padding-between-alt":
  7702. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  7703. continue;
  7704. case "text-line-through":
  7705. if ( (value == "single") || (value == "double") ) {
  7706. n[i] = "text-decoration:line-through";
  7707. }
  7708. continue;
  7709. case "mso-zero-height":
  7710. if ( value == "yes" ) {
  7711. n[i] = "display:none";
  7712. }
  7713. continue;
  7714. // case 'background':
  7715. // break;
  7716. case 'margin':
  7717. if ( !/[1-9]/.test( value ) ) {
  7718. continue;
  7719. }
  7720. }
  7721. 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 )
  7722. ||
  7723. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  7724. ) {
  7725. continue;
  7726. }
  7727. n[i] = name + ":" + parts[1];
  7728. }
  7729. }
  7730. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  7731. })
  7732. .replace(/[\d.]+(cm|pt)/g,function(str){
  7733. return utils.transUnitToPx(str)
  7734. })
  7735. }
  7736. return function ( html ) {
  7737. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  7738. };
  7739. }();
  7740. /**
  7741. * 编辑器模拟的节点类
  7742. * @file
  7743. * @module UE
  7744. * @class uNode
  7745. * @since 1.2.6.1
  7746. */
  7747. /**
  7748. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7749. * @unfile
  7750. * @module UE
  7751. */
  7752. (function () {
  7753. /**
  7754. * 编辑器模拟的节点类
  7755. * @unfile
  7756. * @module UE
  7757. * @class uNode
  7758. */
  7759. /**
  7760. * 通过一个键值对,创建一个uNode对象
  7761. * @constructor
  7762. * @param { Object } attr 传入要创建的uNode的初始属性
  7763. * @example
  7764. * ```javascript
  7765. * var node = new uNode({
  7766. * type:'element',
  7767. * tagName:'span',
  7768. * attrs:{style:'font-size:14px;'}
  7769. * }
  7770. * ```
  7771. */
  7772. var uNode = UE.uNode = function (obj) {
  7773. this.type = obj.type;
  7774. this.data = obj.data;
  7775. this.tagName = obj.tagName;
  7776. this.parentNode = obj.parentNode;
  7777. this.attrs = obj.attrs || {};
  7778. this.children = obj.children;
  7779. };
  7780. var notTransAttrs = {
  7781. 'href':1,
  7782. 'src':1,
  7783. '_src':1,
  7784. '_href':1,
  7785. 'cdata_data':1
  7786. };
  7787. var notTransTagName = {
  7788. style:1,
  7789. script:1
  7790. };
  7791. var indentChar = ' ',
  7792. breakChar = '\n';
  7793. function insertLine(arr, current, begin) {
  7794. arr.push(breakChar);
  7795. return current + (begin ? 1 : -1);
  7796. }
  7797. function insertIndent(arr, current) {
  7798. //插入缩进
  7799. for (var i = 0; i < current; i++) {
  7800. arr.push(indentChar);
  7801. }
  7802. }
  7803. //创建uNode的静态方法
  7804. //支持标签和html
  7805. uNode.createElement = function (html) {
  7806. if (/[<>]/.test(html)) {
  7807. return UE.htmlparser(html).children[0]
  7808. } else {
  7809. return new uNode({
  7810. type:'element',
  7811. children:[],
  7812. tagName:html
  7813. })
  7814. }
  7815. };
  7816. uNode.createText = function (data,noTrans) {
  7817. return new UE.uNode({
  7818. type:'text',
  7819. 'data':noTrans ? data : utils.unhtml(data || '')
  7820. })
  7821. };
  7822. function nodeToHtml(node, arr, formatter, current) {
  7823. switch (node.type) {
  7824. case 'root':
  7825. for (var i = 0, ci; ci = node.children[i++];) {
  7826. //插入新行
  7827. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7828. insertLine(arr, current, true);
  7829. insertIndent(arr, current)
  7830. }
  7831. nodeToHtml(ci, arr, formatter, current)
  7832. }
  7833. break;
  7834. case 'text':
  7835. isText(node, arr);
  7836. break;
  7837. case 'element':
  7838. isElement(node, arr, formatter, current);
  7839. break;
  7840. case 'comment':
  7841. isComment(node, arr, formatter);
  7842. }
  7843. return arr;
  7844. }
  7845. function isText(node, arr) {
  7846. if(node.parentNode.tagName == 'pre'){
  7847. //源码模式下输入html标签,不能做转换处理,直接输出
  7848. arr.push(node.data)
  7849. }else{
  7850. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  7851. }
  7852. }
  7853. function isElement(node, arr, formatter, current) {
  7854. var attrhtml = '';
  7855. if (node.attrs) {
  7856. attrhtml = [];
  7857. var attrs = node.attrs;
  7858. for (var a in attrs) {
  7859. //这里就针对
  7860. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  7861. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  7862. //有可能做的不够
  7863. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  7864. return '&quot;'
  7865. }) : utils.unhtml(attrs[a])) + '"' : ''))
  7866. }
  7867. attrhtml = attrhtml.join(' ');
  7868. }
  7869. arr.push('<' + node.tagName +
  7870. (attrhtml ? ' ' + attrhtml : '') +
  7871. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  7872. );
  7873. //插入新行
  7874. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7875. if(node.children && node.children.length){
  7876. current = insertLine(arr, current, true);
  7877. insertIndent(arr, current)
  7878. }
  7879. }
  7880. if (node.children && node.children.length) {
  7881. for (var i = 0, ci; ci = node.children[i++];) {
  7882. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7883. insertLine(arr, current);
  7884. insertIndent(arr, current)
  7885. }
  7886. nodeToHtml(ci, arr, formatter, current)
  7887. }
  7888. }
  7889. if (!dtd.$empty[node.tagName]) {
  7890. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7891. if(node.children && node.children.length){
  7892. current = insertLine(arr, current);
  7893. insertIndent(arr, current)
  7894. }
  7895. }
  7896. arr.push('<\/' + node.tagName + '>');
  7897. }
  7898. }
  7899. function isComment(node, arr) {
  7900. arr.push('<!--' + node.data + '-->');
  7901. }
  7902. function getNodeById(root, id) {
  7903. var node;
  7904. if (root.type == 'element' && root.getAttr('id') == id) {
  7905. return root;
  7906. }
  7907. if (root.children && root.children.length) {
  7908. for (var i = 0, ci; ci = root.children[i++];) {
  7909. if (node = getNodeById(ci, id)) {
  7910. return node;
  7911. }
  7912. }
  7913. }
  7914. }
  7915. function getNodesByTagName(node, tagName, arr) {
  7916. if (node.type == 'element' && node.tagName == tagName) {
  7917. arr.push(node);
  7918. }
  7919. if (node.children && node.children.length) {
  7920. for (var i = 0, ci; ci = node.children[i++];) {
  7921. getNodesByTagName(ci, tagName, arr)
  7922. }
  7923. }
  7924. }
  7925. function nodeTraversal(root,fn){
  7926. if(root.children && root.children.length){
  7927. for(var i= 0,ci;ci=root.children[i];){
  7928. nodeTraversal(ci,fn);
  7929. //ci被替换的情况,这里就不再走 fn了
  7930. if(ci.parentNode ){
  7931. if(ci.children && ci.children.length){
  7932. fn(ci)
  7933. }
  7934. if(ci.parentNode) i++
  7935. }
  7936. }
  7937. }else{
  7938. fn(root)
  7939. }
  7940. }
  7941. uNode.prototype = {
  7942. /**
  7943. * 当前节点对象,转换成html文本
  7944. * @method toHtml
  7945. * @return { String } 返回转换后的html字符串
  7946. * @example
  7947. * ```javascript
  7948. * node.toHtml();
  7949. * ```
  7950. */
  7951. /**
  7952. * 当前节点对象,转换成html文本
  7953. * @method toHtml
  7954. * @param { Boolean } formatter 是否格式化返回值
  7955. * @return { String } 返回转换后的html字符串
  7956. * @example
  7957. * ```javascript
  7958. * node.toHtml( true );
  7959. * ```
  7960. */
  7961. toHtml:function (formatter) {
  7962. var arr = [];
  7963. nodeToHtml(this, arr, formatter, 0);
  7964. return arr.join('')
  7965. },
  7966. /**
  7967. * 获取节点的html内容
  7968. * @method innerHTML
  7969. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7970. * @return { String } 返回节点的html内容
  7971. * @example
  7972. * ```javascript
  7973. * var htmlstr = node.innerHTML();
  7974. * ```
  7975. */
  7976. /**
  7977. * 设置节点的html内容
  7978. * @method innerHTML
  7979. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7980. * @param { String } htmlstr 传入要设置的html内容
  7981. * @return { UE.uNode } 返回节点本身
  7982. * @example
  7983. * ```javascript
  7984. * node.innerHTML('<span>text</span>');
  7985. * ```
  7986. */
  7987. innerHTML:function (htmlstr) {
  7988. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  7989. return this;
  7990. }
  7991. if (utils.isString(htmlstr)) {
  7992. if(this.children){
  7993. for (var i = 0, ci; ci = this.children[i++];) {
  7994. ci.parentNode = null;
  7995. }
  7996. }
  7997. this.children = [];
  7998. var tmpRoot = UE.htmlparser(htmlstr);
  7999. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8000. this.children.push(ci);
  8001. ci.parentNode = this;
  8002. }
  8003. return this;
  8004. } else {
  8005. var tmpRoot = new UE.uNode({
  8006. type:'root',
  8007. children:this.children
  8008. });
  8009. return tmpRoot.toHtml();
  8010. }
  8011. },
  8012. /**
  8013. * 获取节点的纯文本内容
  8014. * @method innerText
  8015. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8016. * @return { String } 返回节点的存文本内容
  8017. * @example
  8018. * ```javascript
  8019. * var textStr = node.innerText();
  8020. * ```
  8021. */
  8022. /**
  8023. * 设置节点的纯文本内容
  8024. * @method innerText
  8025. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8026. * @param { String } textStr 传入要设置的文本内容
  8027. * @return { UE.uNode } 返回节点本身
  8028. * @example
  8029. * ```javascript
  8030. * node.innerText('<span>text</span>');
  8031. * ```
  8032. */
  8033. innerText:function (textStr,noTrans) {
  8034. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8035. return this;
  8036. }
  8037. if (textStr) {
  8038. if(this.children){
  8039. for (var i = 0, ci; ci = this.children[i++];) {
  8040. ci.parentNode = null;
  8041. }
  8042. }
  8043. this.children = [];
  8044. this.appendChild(uNode.createText(textStr,noTrans));
  8045. return this;
  8046. } else {
  8047. return this.toHtml().replace(/<[^>]+>/g, '');
  8048. }
  8049. },
  8050. /**
  8051. * 获取当前对象的data属性
  8052. * @method getData
  8053. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8054. * @example
  8055. * ```javascript
  8056. * node.getData();
  8057. * ```
  8058. */
  8059. getData:function () {
  8060. if (this.type == 'element')
  8061. return '';
  8062. return this.data
  8063. },
  8064. /**
  8065. * 获取当前节点下的第一个子节点
  8066. * @method firstChild
  8067. * @return { UE.uNode } 返回第一个子节点
  8068. * @example
  8069. * ```javascript
  8070. * node.firstChild(); //返回第一个子节点
  8071. * ```
  8072. */
  8073. firstChild:function () {
  8074. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8075. // return this;
  8076. // }
  8077. return this.children ? this.children[0] : null;
  8078. },
  8079. /**
  8080. * 获取当前节点下的最后一个子节点
  8081. * @method lastChild
  8082. * @return { UE.uNode } 返回最后一个子节点
  8083. * @example
  8084. * ```javascript
  8085. * node.lastChild(); //返回最后一个子节点
  8086. * ```
  8087. */
  8088. lastChild:function () {
  8089. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8090. // return this;
  8091. // }
  8092. return this.children ? this.children[this.children.length - 1] : null;
  8093. },
  8094. /**
  8095. * 获取和当前节点有相同父亲节点的前一个节点
  8096. * @method previousSibling
  8097. * @return { UE.uNode } 返回前一个节点
  8098. * @example
  8099. * ```javascript
  8100. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8101. * ```
  8102. */
  8103. previousSibling : function(){
  8104. var parent = this.parentNode;
  8105. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8106. if (ci === this) {
  8107. return i == 0 ? null : parent.children[i-1];
  8108. }
  8109. }
  8110. },
  8111. /**
  8112. * 获取和当前节点有相同父亲节点的后一个节点
  8113. * @method nextSibling
  8114. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8115. * @example
  8116. * ```javascript
  8117. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8118. * ```
  8119. */
  8120. nextSibling : function(){
  8121. var parent = this.parentNode;
  8122. for (var i = 0, ci; ci = parent.children[i++];) {
  8123. if (ci === this) {
  8124. return parent.children[i];
  8125. }
  8126. }
  8127. },
  8128. /**
  8129. * 用新的节点替换当前节点
  8130. * @method replaceChild
  8131. * @param { UE.uNode } target 要替换成该节点参数
  8132. * @param { UE.uNode } source 要被替换掉的节点
  8133. * @return { UE.uNode } 返回替换之后的节点对象
  8134. * @example
  8135. * ```javascript
  8136. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8137. * ```
  8138. */
  8139. replaceChild:function (target, source) {
  8140. if (this.children) {
  8141. if(target.parentNode){
  8142. target.parentNode.removeChild(target);
  8143. }
  8144. for (var i = 0, ci; ci = this.children[i]; i++) {
  8145. if (ci === source) {
  8146. this.children.splice(i, 1, target);
  8147. source.parentNode = null;
  8148. target.parentNode = this;
  8149. return target;
  8150. }
  8151. }
  8152. }
  8153. },
  8154. /**
  8155. * 在节点的子节点列表最后位置插入一个节点
  8156. * @method appendChild
  8157. * @param { UE.uNode } node 要插入的节点
  8158. * @return { UE.uNode } 返回刚插入的子节点
  8159. * @example
  8160. * ```javascript
  8161. * node.appendChild( newNode ); //在node内插入子节点newNode
  8162. * ```
  8163. */
  8164. appendChild:function (node) {
  8165. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8166. if (!this.children) {
  8167. this.children = []
  8168. }
  8169. if(node.parentNode){
  8170. node.parentNode.removeChild(node);
  8171. }
  8172. for (var i = 0, ci; ci = this.children[i]; i++) {
  8173. if (ci === node) {
  8174. this.children.splice(i, 1);
  8175. break;
  8176. }
  8177. }
  8178. this.children.push(node);
  8179. node.parentNode = this;
  8180. return node;
  8181. }
  8182. },
  8183. /**
  8184. * 在传入节点的前面插入一个节点
  8185. * @method insertBefore
  8186. * @param { UE.uNode } target 要插入的节点
  8187. * @param { UE.uNode } source 在该参数节点前面插入
  8188. * @return { UE.uNode } 返回刚插入的子节点
  8189. * @example
  8190. * ```javascript
  8191. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8192. * ```
  8193. */
  8194. insertBefore:function (target, source) {
  8195. if (this.children) {
  8196. if(target.parentNode){
  8197. target.parentNode.removeChild(target);
  8198. }
  8199. for (var i = 0, ci; ci = this.children[i]; i++) {
  8200. if (ci === source) {
  8201. this.children.splice(i, 0, target);
  8202. target.parentNode = this;
  8203. return target;
  8204. }
  8205. }
  8206. }
  8207. },
  8208. /**
  8209. * 在传入节点的后面插入一个节点
  8210. * @method insertAfter
  8211. * @param { UE.uNode } target 要插入的节点
  8212. * @param { UE.uNode } source 在该参数节点后面插入
  8213. * @return { UE.uNode } 返回刚插入的子节点
  8214. * @example
  8215. * ```javascript
  8216. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8217. * ```
  8218. */
  8219. insertAfter:function (target, source) {
  8220. if (this.children) {
  8221. if(target.parentNode){
  8222. target.parentNode.removeChild(target);
  8223. }
  8224. for (var i = 0, ci; ci = this.children[i]; i++) {
  8225. if (ci === source) {
  8226. this.children.splice(i + 1, 0, target);
  8227. target.parentNode = this;
  8228. return target;
  8229. }
  8230. }
  8231. }
  8232. },
  8233. /**
  8234. * 从当前节点的子节点列表中,移除节点
  8235. * @method removeChild
  8236. * @param { UE.uNode } node 要移除的节点引用
  8237. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8238. * @return { * } 返回刚移除的子节点
  8239. * @example
  8240. * ```javascript
  8241. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8242. * ```
  8243. */
  8244. removeChild:function (node,keepChildren) {
  8245. if (this.children) {
  8246. for (var i = 0, ci; ci = this.children[i]; i++) {
  8247. if (ci === node) {
  8248. this.children.splice(i, 1);
  8249. ci.parentNode = null;
  8250. if(keepChildren && ci.children && ci.children.length){
  8251. for(var j= 0,cj;cj=ci.children[j];j++){
  8252. this.children.splice(i+j,0,cj);
  8253. cj.parentNode = this;
  8254. }
  8255. }
  8256. return ci;
  8257. }
  8258. }
  8259. }
  8260. },
  8261. /**
  8262. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8263. * @method getAttr
  8264. * @param { String } attrName 要获取的属性名称
  8265. * @return { * } 返回attrs对象下的属性值
  8266. * @example
  8267. * ```javascript
  8268. * node.getAttr('title');
  8269. * ```
  8270. */
  8271. getAttr:function (attrName) {
  8272. return this.attrs && this.attrs[attrName.toLowerCase()]
  8273. },
  8274. /**
  8275. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8276. * @method setAttr
  8277. * @param { String } attrName 要设置的属性名称
  8278. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8279. * @return { * } 返回attrs对象下的属性值
  8280. * @example
  8281. * ```javascript
  8282. * node.setAttr('title','标题');
  8283. * ```
  8284. */
  8285. setAttr:function (attrName, attrVal) {
  8286. if (!attrName) {
  8287. delete this.attrs;
  8288. return;
  8289. }
  8290. if(!this.attrs){
  8291. this.attrs = {};
  8292. }
  8293. if (utils.isObject(attrName)) {
  8294. for (var a in attrName) {
  8295. if (!attrName[a]) {
  8296. delete this.attrs[a]
  8297. } else {
  8298. this.attrs[a.toLowerCase()] = attrName[a];
  8299. }
  8300. }
  8301. } else {
  8302. if (!attrVal) {
  8303. delete this.attrs[attrName]
  8304. } else {
  8305. this.attrs[attrName.toLowerCase()] = attrVal;
  8306. }
  8307. }
  8308. },
  8309. /**
  8310. * 获取当前节点在父节点下的位置索引
  8311. * @method getIndex
  8312. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8313. * @example
  8314. * ```javascript
  8315. * node.getIndex();
  8316. * ```
  8317. */
  8318. getIndex:function(){
  8319. var parent = this.parentNode;
  8320. for(var i= 0,ci;ci=parent.children[i];i++){
  8321. if(ci === this){
  8322. return i;
  8323. }
  8324. }
  8325. return -1;
  8326. },
  8327. /**
  8328. * 在当前节点下,根据id查找节点
  8329. * @method getNodeById
  8330. * @param { String } id 要查找的id
  8331. * @return { UE.uNode } 返回找到的节点
  8332. * @example
  8333. * ```javascript
  8334. * node.getNodeById('textId');
  8335. * ```
  8336. */
  8337. getNodeById:function (id) {
  8338. var node;
  8339. if (this.children && this.children.length) {
  8340. for (var i = 0, ci; ci = this.children[i++];) {
  8341. if (node = getNodeById(ci, id)) {
  8342. return node;
  8343. }
  8344. }
  8345. }
  8346. },
  8347. /**
  8348. * 在当前节点下,根据元素名称查找节点列表
  8349. * @method getNodesByTagName
  8350. * @param { String } tagNames 要查找的元素名称
  8351. * @return { Array } 返回找到的节点列表
  8352. * @example
  8353. * ```javascript
  8354. * node.getNodesByTagName('span');
  8355. * ```
  8356. */
  8357. getNodesByTagName:function (tagNames) {
  8358. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8359. var arr = [], me = this;
  8360. utils.each(tagNames, function (tagName) {
  8361. if (me.children && me.children.length) {
  8362. for (var i = 0, ci; ci = me.children[i++];) {
  8363. getNodesByTagName(ci, tagName, arr)
  8364. }
  8365. }
  8366. });
  8367. return arr;
  8368. },
  8369. /**
  8370. * 根据样式名称,获取节点的样式值
  8371. * @method getStyle
  8372. * @param { String } name 要获取的样式名称
  8373. * @return { String } 返回样式值
  8374. * @example
  8375. * ```javascript
  8376. * node.getStyle('font-size');
  8377. * ```
  8378. */
  8379. getStyle:function (name) {
  8380. var cssStyle = this.getAttr('style');
  8381. if (!cssStyle) {
  8382. return ''
  8383. }
  8384. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8385. var match = cssStyle.match(reg);
  8386. if (match && match[0]) {
  8387. return match[2]
  8388. }
  8389. return '';
  8390. },
  8391. /**
  8392. * 给节点设置样式
  8393. * @method setStyle
  8394. * @param { String } name 要设置的的样式名称
  8395. * @param { String } val 要设置的的样值
  8396. * @example
  8397. * ```javascript
  8398. * node.setStyle('font-size', '12px');
  8399. * ```
  8400. */
  8401. setStyle:function (name, val) {
  8402. function exec(name, val) {
  8403. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8404. cssStyle = cssStyle.replace(reg, '$1');
  8405. if (val) {
  8406. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8407. }
  8408. }
  8409. var cssStyle = this.getAttr('style');
  8410. if (!cssStyle) {
  8411. cssStyle = '';
  8412. }
  8413. if (utils.isObject(name)) {
  8414. for (var a in name) {
  8415. exec(a, name[a])
  8416. }
  8417. } else {
  8418. exec(name, val)
  8419. }
  8420. this.setAttr('style', utils.trim(cssStyle))
  8421. },
  8422. /**
  8423. * 传入一个函数,递归遍历当前节点下的所有节点
  8424. * @method traversal
  8425. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8426. * @example
  8427. * ```javascript
  8428. * traversal(node, function(){
  8429. * console.log(node.type);
  8430. * });
  8431. * ```
  8432. */
  8433. traversal:function(fn){
  8434. if(this.children && this.children.length){
  8435. nodeTraversal(this,fn);
  8436. }
  8437. return this;
  8438. }
  8439. }
  8440. })();
  8441. /**
  8442. * html字符串转换成uNode节点
  8443. * @file
  8444. * @module UE
  8445. * @since 1.2.6.1
  8446. */
  8447. /**
  8448. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8449. * @unfile
  8450. * @module UE
  8451. */
  8452. /**
  8453. * html字符串转换成uNode节点的静态方法
  8454. * @method htmlparser
  8455. * @param { String } htmlstr 要转换的html代码
  8456. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8457. * @return { uNode } 给定的html片段转换形成的uNode对象
  8458. * @example
  8459. * ```javascript
  8460. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8461. * ```
  8462. */
  8463. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8464. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8465. //先去掉了,加上的原因忘了,这里先记录
  8466. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8467. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8468. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8469. var allowEmptyTags = {
  8470. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8471. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8472. };
  8473. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8474. if(!ignoreBlank){
  8475. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8476. //br暂时单独处理
  8477. if(b && allowEmptyTags[b.toLowerCase()]){
  8478. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8479. }
  8480. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8481. });
  8482. }
  8483. var notTransAttrs = {
  8484. 'href':1,
  8485. 'src':1
  8486. };
  8487. var uNode = UE.uNode,
  8488. needParentNode = {
  8489. 'td':'tr',
  8490. 'tr':['tbody','thead','tfoot'],
  8491. 'tbody':'table',
  8492. 'th':'tr',
  8493. 'thead':'table',
  8494. 'tfoot':'table',
  8495. 'caption':'table',
  8496. 'li':['ul', 'ol'],
  8497. 'dt':'dl',
  8498. 'dd':'dl',
  8499. 'option':'select'
  8500. },
  8501. needChild = {
  8502. 'ol':'li',
  8503. 'ul':'li'
  8504. };
  8505. function text(parent, data) {
  8506. if(needChild[parent.tagName]){
  8507. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8508. parent.appendChild(tmpNode);
  8509. tmpNode.appendChild(uNode.createText(data));
  8510. parent = tmpNode;
  8511. }else{
  8512. parent.appendChild(uNode.createText(data));
  8513. }
  8514. }
  8515. function element(parent, tagName, htmlattr) {
  8516. var needParentTag;
  8517. if (needParentTag = needParentNode[tagName]) {
  8518. var tmpParent = parent,hasParent;
  8519. while(tmpParent.type != 'root'){
  8520. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8521. parent = tmpParent;
  8522. hasParent = true;
  8523. break;
  8524. }
  8525. tmpParent = tmpParent.parentNode;
  8526. }
  8527. if(!hasParent){
  8528. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8529. }
  8530. }
  8531. //按dtd处理嵌套
  8532. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8533. // parent = parent.parentNode;
  8534. var elm = new uNode({
  8535. parentNode:parent,
  8536. type:'element',
  8537. tagName:tagName.toLowerCase(),
  8538. //是自闭合的处理一下
  8539. children:dtd.$empty[tagName] ? null : []
  8540. });
  8541. //如果属性存在,处理属性
  8542. if (htmlattr) {
  8543. var attrs = {}, match;
  8544. while (match = re_attr.exec(htmlattr)) {
  8545. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8546. }
  8547. elm.attrs = attrs;
  8548. }
  8549. parent.children.push(elm);
  8550. //如果是自闭合节点返回父亲节点
  8551. return dtd.$empty[tagName] ? parent : elm
  8552. }
  8553. function comment(parent, data) {
  8554. parent.children.push(new uNode({
  8555. type:'comment',
  8556. data:data,
  8557. parentNode:parent
  8558. }));
  8559. }
  8560. var match, currentIndex = 0, nextIndex = 0;
  8561. //设置根节点
  8562. var root = new uNode({
  8563. type:'root',
  8564. children:[]
  8565. });
  8566. var currentParent = root;
  8567. while (match = re_tag.exec(htmlstr)) {
  8568. currentIndex = match.index;
  8569. try{
  8570. if (currentIndex > nextIndex) {
  8571. //text node
  8572. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8573. }
  8574. if (match[3]) {
  8575. if(dtd.$cdata[currentParent.tagName]){
  8576. text(currentParent, match[0]);
  8577. }else{
  8578. //start tag
  8579. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8580. }
  8581. } else if (match[1]) {
  8582. if(currentParent.type != 'root'){
  8583. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8584. text(currentParent, match[0]);
  8585. }else{
  8586. var tmpParent = currentParent;
  8587. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8588. currentParent = currentParent.parentNode;
  8589. if(currentParent.type == 'root'){
  8590. currentParent = tmpParent;
  8591. throw 'break'
  8592. }
  8593. }
  8594. //end tag
  8595. currentParent = currentParent.parentNode;
  8596. }
  8597. }
  8598. } else if (match[2]) {
  8599. //comment
  8600. comment(currentParent, match[2])
  8601. }
  8602. }catch(e){}
  8603. nextIndex = re_tag.lastIndex;
  8604. }
  8605. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  8606. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  8607. if (nextIndex < htmlstr.length) {
  8608. text(currentParent, htmlstr.slice(nextIndex));
  8609. }
  8610. return root;
  8611. };
  8612. /**
  8613. * UE过滤节点的静态方法
  8614. * @file
  8615. */
  8616. /**
  8617. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8618. * @module UE
  8619. */
  8620. /**
  8621. * 根据传入节点和过滤规则过滤相应节点
  8622. * @module UE
  8623. * @since 1.2.6.1
  8624. * @method filterNode
  8625. * @param { Object } root 指定root节点
  8626. * @param { Object } rules 过滤规则json对象
  8627. * @example
  8628. * ```javascript
  8629. * UE.filterNode(root,editor.options.filterRules);
  8630. * ```
  8631. */
  8632. var filterNode = UE.filterNode = function () {
  8633. function filterNode(node,rules){
  8634. switch (node.type) {
  8635. case 'text':
  8636. break;
  8637. case 'element':
  8638. var val;
  8639. if(val = rules[node.tagName]){
  8640. if(val === '-'){
  8641. node.parentNode.removeChild(node)
  8642. }else if(utils.isFunction(val)){
  8643. var parentNode = node.parentNode,
  8644. index = node.getIndex();
  8645. val(node);
  8646. if(node.parentNode){
  8647. if(node.children){
  8648. for(var i = 0,ci;ci=node.children[i];){
  8649. filterNode(ci,rules);
  8650. if(ci.parentNode){
  8651. i++;
  8652. }
  8653. }
  8654. }
  8655. }else{
  8656. for(var i = index,ci;ci=parentNode.children[i];){
  8657. filterNode(ci,rules);
  8658. if(ci.parentNode){
  8659. i++;
  8660. }
  8661. }
  8662. }
  8663. }else{
  8664. var attrs = val['$'];
  8665. if(attrs && node.attrs){
  8666. var tmpAttrs = {},tmpVal;
  8667. for(var a in attrs){
  8668. tmpVal = node.getAttr(a);
  8669. //todo 只先对style单独处理
  8670. if(a == 'style' && utils.isArray(attrs[a])){
  8671. var tmpCssStyle = [];
  8672. utils.each(attrs[a],function(v){
  8673. var tmp;
  8674. if(tmp = node.getStyle(v)){
  8675. tmpCssStyle.push(v + ':' + tmp);
  8676. }
  8677. });
  8678. tmpVal = tmpCssStyle.join(';')
  8679. }
  8680. if(tmpVal){
  8681. tmpAttrs[a] = tmpVal;
  8682. }
  8683. }
  8684. node.attrs = tmpAttrs;
  8685. }
  8686. if(node.children){
  8687. for(var i = 0,ci;ci=node.children[i];){
  8688. filterNode(ci,rules);
  8689. if(ci.parentNode){
  8690. i++;
  8691. }
  8692. }
  8693. }
  8694. }
  8695. }else{
  8696. //如果不在名单里扣出子节点并删除该节点,cdata除外
  8697. if(dtd.$cdata[node.tagName]){
  8698. node.parentNode.removeChild(node)
  8699. }else{
  8700. var parentNode = node.parentNode,
  8701. index = node.getIndex();
  8702. node.parentNode.removeChild(node,true);
  8703. for(var i = index,ci;ci=parentNode.children[i];){
  8704. filterNode(ci,rules);
  8705. if(ci.parentNode){
  8706. i++;
  8707. }
  8708. }
  8709. }
  8710. }
  8711. break;
  8712. case 'comment':
  8713. node.parentNode.removeChild(node)
  8714. }
  8715. }
  8716. return function(root,rules){
  8717. if(utils.isEmptyObject(rules)){
  8718. return root;
  8719. }
  8720. var val;
  8721. if(val = rules['-']){
  8722. utils.each(val.split(' '),function(k){
  8723. rules[k] = '-'
  8724. })
  8725. }
  8726. for(var i= 0,ci;ci=root.children[i];){
  8727. filterNode(ci,rules);
  8728. if(ci.parentNode){
  8729. i++;
  8730. }
  8731. }
  8732. return root;
  8733. }
  8734. }();
  8735. /*
  8736. * Created with JetBrains PhpStorm.
  8737. * User: campaign
  8738. * Date: 10/8/13
  8739. * Time: 6:15 PM
  8740. * To change this template use File | Settings | File Templates.
  8741. */
  8742. UE.plugin = function(){
  8743. var _plugins = {};
  8744. return {
  8745. register : function(pluginName,fn,oldOptionName,afterDisabled){
  8746. if(oldOptionName && utils.isFunction(oldOptionName)){
  8747. afterDisabled = oldOptionName;
  8748. oldOptionName = null
  8749. }
  8750. _plugins[pluginName] = {
  8751. optionName : oldOptionName || pluginName,
  8752. execFn : fn,
  8753. //当插件被禁用时执行
  8754. afterDisabled : afterDisabled
  8755. }
  8756. },
  8757. load : function(editor){
  8758. utils.each(_plugins,function(plugin){
  8759. var _export = plugin.execFn.call(editor);
  8760. if(editor.options[plugin.optionName] !== false){
  8761. if(_export){
  8762. //后边需要再做扩展
  8763. utils.each(_export,function(v,k){
  8764. switch(k.toLowerCase()){
  8765. case 'shortcutkey':
  8766. editor.addshortcutkey(v);
  8767. break;
  8768. case 'bindevents':
  8769. utils.each(v,function(fn,eventName){
  8770. editor.addListener(eventName,fn);
  8771. });
  8772. break;
  8773. case 'bindmultievents':
  8774. utils.each(utils.isArray(v) ? v:[v],function(event){
  8775. var types = utils.trim(event.type).split(/\s+/);
  8776. utils.each(types,function(eventName){
  8777. editor.addListener(eventName, event.handler);
  8778. });
  8779. });
  8780. break;
  8781. case 'commands':
  8782. utils.each(v,function(execFn,execName){
  8783. editor.commands[execName] = execFn
  8784. });
  8785. break;
  8786. case 'outputrule':
  8787. editor.addOutputRule(v);
  8788. break;
  8789. case 'inputrule':
  8790. editor.addInputRule(v);
  8791. break;
  8792. case 'defaultoptions':
  8793. editor.setOpt(v)
  8794. }
  8795. })
  8796. }
  8797. }else if(plugin.afterDisabled){
  8798. plugin.afterDisabled.call(editor)
  8799. }
  8800. });
  8801. //向下兼容
  8802. utils.each(UE.plugins,function(plugin){
  8803. plugin.call(editor);
  8804. });
  8805. },
  8806. run : function(plugnName,editor){
  8807. var plugin = _plugins[pluginName];
  8808. if(plugin){
  8809. plugin.exeFn.call(editor)
  8810. }
  8811. }
  8812. }
  8813. }();
  8814. ///import core
  8815. ///plugin 编辑器默认的过滤转换机制
  8816. UE.plugins['defaultfilter'] = function () {
  8817. var me = this;
  8818. me.setOpt({
  8819. 'allowDivTransToP':true,
  8820. 'disabledTableInTable':true
  8821. });
  8822. //默认的过滤处理
  8823. //进入编辑器的内容处理
  8824. me.addInputRule(function (root) {
  8825. var allowDivTransToP = this.options.allowDivTransToP;
  8826. var val;
  8827. function tdParent(node){
  8828. while(node && node.type == 'element'){
  8829. if(node.tagName == 'td'){
  8830. return true;
  8831. }
  8832. node = node.parentNode;
  8833. }
  8834. return false;
  8835. }
  8836. //进行默认的处理
  8837. root.traversal(function (node) {
  8838. if (node.type == 'element') {
  8839. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8840. if (!node.firstChild()) node.parentNode.removeChild(node);
  8841. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8842. node.parentNode.removeChild(node, true)
  8843. }
  8844. return;
  8845. }
  8846. switch (node.tagName) {
  8847. case 'style':
  8848. case 'script':
  8849. node.setAttr({
  8850. cdata_tag: node.tagName,
  8851. cdata_data: (node.innerHTML() || ''),
  8852. '_ue_custom_node_':'true'
  8853. });
  8854. node.tagName = 'div';
  8855. node.innerHTML('');
  8856. break;
  8857. case 'a':
  8858. if (val = node.getAttr('href')) {
  8859. node.setAttr('_href', val)
  8860. }
  8861. break;
  8862. case 'img':
  8863. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  8864. if (val = node.getAttr('src')) {
  8865. if (/^data:/.test(val)) {
  8866. node.parentNode.removeChild(node);
  8867. break;
  8868. }
  8869. }
  8870. node.setAttr('_src', node.getAttr('src'));
  8871. break;
  8872. case 'span':
  8873. if (browser.webkit && (val = node.getStyle('white-space'))) {
  8874. if (/nowrap|normal/.test(val)) {
  8875. node.setStyle('white-space', '');
  8876. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  8877. node.parentNode.removeChild(node, true)
  8878. }
  8879. }
  8880. }
  8881. break;
  8882. case 'p':
  8883. if (val = node.getAttr('align')) {
  8884. node.setAttr('align');
  8885. node.setStyle('text-align', val)
  8886. }
  8887. //trace:3431
  8888. // var cssStyle = node.getAttr('style');
  8889. // if (cssStyle) {
  8890. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  8891. // node.setAttr('style', cssStyle)
  8892. //
  8893. // }
  8894. //p标签不允许嵌套
  8895. utils.each(node.children,function(n){
  8896. if(n.type == 'element' && n.tagName == 'p'){
  8897. var next = n.nextSibling();
  8898. node.parentNode.insertAfter(n,node);
  8899. var last = n;
  8900. while(next){
  8901. var tmp = next.nextSibling();
  8902. node.parentNode.insertAfter(next,last);
  8903. last = next;
  8904. next = tmp;
  8905. }
  8906. return false;
  8907. }
  8908. });
  8909. if (!node.firstChild()) {
  8910. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  8911. }
  8912. break;
  8913. case 'div':
  8914. if(node.getAttr('cdata_tag')){
  8915. break;
  8916. }
  8917. //针对代码这里不处理插入代码的div
  8918. val = node.getAttr('class');
  8919. if(val && /^line number\d+/.test(val)){
  8920. break;
  8921. }
  8922. if(!allowDivTransToP){
  8923. break;
  8924. }
  8925. var tmpNode, p = UE.uNode.createElement('p');
  8926. while (tmpNode = node.firstChild()) {
  8927. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  8928. p.appendChild(tmpNode);
  8929. } else {
  8930. if (p.firstChild()) {
  8931. node.parentNode.insertBefore(p, node);
  8932. p = UE.uNode.createElement('p');
  8933. } else {
  8934. node.parentNode.insertBefore(tmpNode, node);
  8935. }
  8936. }
  8937. }
  8938. if (p.firstChild()) {
  8939. node.parentNode.insertBefore(p, node);
  8940. }
  8941. node.parentNode.removeChild(node);
  8942. break;
  8943. case 'dl':
  8944. node.tagName = 'ul';
  8945. break;
  8946. case 'dt':
  8947. case 'dd':
  8948. node.tagName = 'li';
  8949. break;
  8950. case 'li':
  8951. var className = node.getAttr('class');
  8952. if (!className || !/list\-/.test(className)) {
  8953. node.setAttr()
  8954. }
  8955. var tmpNodes = node.getNodesByTagName('ol ul');
  8956. UE.utils.each(tmpNodes, function (n) {
  8957. node.parentNode.insertAfter(n, node);
  8958. });
  8959. break;
  8960. case 'td':
  8961. case 'th':
  8962. case 'caption':
  8963. if(!node.children || !node.children.length){
  8964. node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  8965. }
  8966. break;
  8967. case 'table':
  8968. if(me.options.disabledTableInTable && tdParent(node)){
  8969. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  8970. node.parentNode.removeChild(node)
  8971. }
  8972. }
  8973. }
  8974. // if(node.type == 'comment'){
  8975. // node.parentNode.removeChild(node);
  8976. // }
  8977. })
  8978. });
  8979. //从编辑器出去的内容处理
  8980. me.addOutputRule(function (root) {
  8981. var val;
  8982. root.traversal(function (node) {
  8983. if (node.type == 'element') {
  8984. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8985. if (!node.firstChild()) node.parentNode.removeChild(node);
  8986. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8987. node.parentNode.removeChild(node, true)
  8988. }
  8989. return;
  8990. }
  8991. switch (node.tagName) {
  8992. case 'div':
  8993. if (val = node.getAttr('cdata_tag')) {
  8994. node.tagName = val;
  8995. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  8996. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  8997. }
  8998. break;
  8999. case 'a':
  9000. if (val = node.getAttr('_href')) {
  9001. node.setAttr({
  9002. 'href': utils.html(val),
  9003. '_href': ''
  9004. })
  9005. }
  9006. break;
  9007. case 'img':
  9008. if (val = node.getAttr('_src')) {
  9009. node.setAttr({
  9010. 'src': node.getAttr('_src'),
  9011. '_src': ''
  9012. })
  9013. }
  9014. }
  9015. }
  9016. })
  9017. });
  9018. };
  9019. /**
  9020. * 插入html字符串插件
  9021. * @file
  9022. * @since 1.2.6.1
  9023. */
  9024. /**
  9025. * 插入html代码
  9026. * @command inserthtml
  9027. * @method execCommand
  9028. * @param { String } cmd 命令字符串
  9029. * @param { String } html 插入的html字符串
  9030. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9031. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9032. * @example
  9033. * ```javascript
  9034. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9035. * //执行命令,插入<b>CC</b>
  9036. * //插入后的效果 xxx<b>CC</b>xxx
  9037. * //<p>xx|xxx</p> 当前选区为闭合状态
  9038. * //插入<p>CC</p>
  9039. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9040. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9041. * //插入 xxxx
  9042. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9043. * ```
  9044. */
  9045. UE.commands['inserthtml'] = {
  9046. execCommand: function (command,html,notNeedFilter){
  9047. var me = this,
  9048. range,
  9049. div;
  9050. if(!html){
  9051. return;
  9052. }
  9053. if(me.fireEvent('beforeinserthtml',html) === true){
  9054. return;
  9055. }
  9056. range = me.selection.getRange();
  9057. div = range.document.createElement( 'div' );
  9058. div.style.display = 'inline';
  9059. if (!notNeedFilter) {
  9060. var root = UE.htmlparser(html);
  9061. //如果给了过滤规则就先进行过滤
  9062. if(me.options.filterRules){
  9063. UE.filterNode(root,me.options.filterRules);
  9064. }
  9065. //执行默认的处理
  9066. me.filterInputRule(root);
  9067. html = root.toHtml()
  9068. }
  9069. div.innerHTML = utils.trim( html );
  9070. if ( !range.collapsed ) {
  9071. var tmpNode = range.startContainer;
  9072. if(domUtils.isFillChar(tmpNode)){
  9073. range.setStartBefore(tmpNode)
  9074. }
  9075. tmpNode = range.endContainer;
  9076. if(domUtils.isFillChar(tmpNode)){
  9077. range.setEndAfter(tmpNode)
  9078. }
  9079. range.txtToElmBoundary();
  9080. //结束边界可能放到了br的前边,要把br包含进来
  9081. // x[xxx]<br/>
  9082. if(range.endContainer && range.endContainer.nodeType == 1){
  9083. tmpNode = range.endContainer.childNodes[range.endOffset];
  9084. if(tmpNode && domUtils.isBr(tmpNode)){
  9085. range.setEndAfter(tmpNode);
  9086. }
  9087. }
  9088. if(range.startOffset == 0){
  9089. tmpNode = range.startContainer;
  9090. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9091. tmpNode = range.endContainer;
  9092. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9093. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9094. range.setStart(me.body.firstChild,0).collapse(true)
  9095. }
  9096. }
  9097. }
  9098. !range.collapsed && range.deleteContents();
  9099. if(range.startContainer.nodeType == 1){
  9100. var child = range.startContainer.childNodes[range.startOffset],pre;
  9101. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9102. range.setEnd(pre,pre.childNodes.length).collapse();
  9103. while(child.firstChild){
  9104. pre.appendChild(child.firstChild);
  9105. }
  9106. domUtils.remove(child);
  9107. }
  9108. }
  9109. }
  9110. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9111. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9112. if(range.inFillChar()){
  9113. child = range.startContainer;
  9114. if(domUtils.isFillChar(child)){
  9115. range.setStartBefore(child).collapse(true);
  9116. domUtils.remove(child);
  9117. }else if(domUtils.isFillChar(child,true)){
  9118. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9119. range.startOffset--;
  9120. range.collapsed && range.collapse(true)
  9121. }
  9122. }
  9123. //列表单独处理
  9124. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9125. if(li){
  9126. var next,last;
  9127. while(child = div.firstChild){
  9128. //针对hr单独处理一下先
  9129. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9130. next = child.nextSibling;
  9131. range.insertNode( child).collapse();
  9132. last = child;
  9133. child = next;
  9134. }
  9135. if(child){
  9136. if(/^(ol|ul)$/i.test(child.tagName)){
  9137. while(child.firstChild){
  9138. last = child.firstChild;
  9139. domUtils.insertAfter(li,child.firstChild);
  9140. li = li.nextSibling;
  9141. }
  9142. domUtils.remove(child)
  9143. }else{
  9144. var tmpLi;
  9145. next = child.nextSibling;
  9146. tmpLi = me.document.createElement('li');
  9147. domUtils.insertAfter(li,tmpLi);
  9148. tmpLi.appendChild(child);
  9149. last = child;
  9150. child = next;
  9151. li = tmpLi;
  9152. }
  9153. }
  9154. }
  9155. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9156. if(domUtils.isEmptyBlock(li)){
  9157. domUtils.remove(li)
  9158. }
  9159. if(last){
  9160. range.setStartAfter(last).collapse(true).select(true)
  9161. }
  9162. }else{
  9163. while ( child = div.firstChild ) {
  9164. if(hadBreak){
  9165. var p = me.document.createElement('p');
  9166. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9167. nextNode = child.nextSibling;
  9168. p.appendChild(child);
  9169. child = nextNode;
  9170. }
  9171. if(p.firstChild){
  9172. child = p
  9173. }
  9174. }
  9175. range.insertNode( child );
  9176. nextNode = child.nextSibling;
  9177. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9178. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9179. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9180. if(!dtd[parent.tagName][child.nodeName]){
  9181. pre = parent;
  9182. }else{
  9183. tmp = child.parentNode;
  9184. while (tmp !== parent){
  9185. pre = tmp;
  9186. tmp = tmp.parentNode;
  9187. }
  9188. }
  9189. domUtils.breakParent( child, pre || tmp );
  9190. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9191. var pre = child.previousSibling;
  9192. domUtils.trimWhiteTextNode(pre);
  9193. if(!pre.childNodes.length){
  9194. domUtils.remove(pre);
  9195. }
  9196. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9197. if(!browser.ie &&
  9198. (next = child.nextSibling) &&
  9199. domUtils.isBlockElm(next) &&
  9200. next.lastChild &&
  9201. !domUtils.isBr(next.lastChild)){
  9202. next.appendChild(me.document.createElement('br'));
  9203. }
  9204. hadBreak = 1;
  9205. }
  9206. }
  9207. var next = child.nextSibling;
  9208. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9209. range.setStart(next,0).collapse(true);
  9210. break;
  9211. }
  9212. range.setEndAfter( child ).collapse();
  9213. }
  9214. child = range.startContainer;
  9215. if(nextNode && domUtils.isBr(nextNode)){
  9216. domUtils.remove(nextNode)
  9217. }
  9218. //用chrome可能有空白展位符
  9219. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9220. if(nextNode = child.nextSibling){
  9221. domUtils.remove(child);
  9222. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9223. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9224. }
  9225. }else{
  9226. try{
  9227. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9228. }catch(e){
  9229. range.setStartBefore(child);
  9230. domUtils.remove(child)
  9231. }
  9232. }
  9233. }
  9234. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9235. try{
  9236. range.select(true);
  9237. }catch(e){}
  9238. }
  9239. setTimeout(function(){
  9240. range = me.selection.getRange();
  9241. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9242. me.fireEvent('afterinserthtml');
  9243. },200);
  9244. }
  9245. };
  9246. /**
  9247. * 图片插入、排版插件
  9248. * @file
  9249. * @since 1.2.6.1
  9250. */
  9251. /**
  9252. * 图片对齐方式
  9253. * @command imagefloat
  9254. * @method execCommand
  9255. * @remind 值center为独占一行居中
  9256. * @param { String } cmd 命令字符串
  9257. * @param { String } align 对齐方式,可传left、right、none、center
  9258. * @remaind center表示图片独占一行
  9259. * @example
  9260. * ```javascript
  9261. * editor.execCommand( 'imagefloat', 'center' );
  9262. * ```
  9263. */
  9264. /**
  9265. * 如果选区所在位置是图片区域
  9266. * @command imagefloat
  9267. * @method queryCommandValue
  9268. * @param { String } cmd 命令字符串
  9269. * @return { String } 返回图片对齐方式
  9270. * @example
  9271. * ```javascript
  9272. * editor.queryCommandValue( 'imagefloat' );
  9273. * ```
  9274. */
  9275. UE.commands['imagefloat'] = {
  9276. execCommand:function (cmd, align) {
  9277. var me = this,
  9278. range = me.selection.getRange();
  9279. if (!range.collapsed) {
  9280. var img = range.getClosedNode();
  9281. if (img && img.tagName == 'IMG') {
  9282. switch (align) {
  9283. case 'left':
  9284. case 'right':
  9285. case 'none':
  9286. var pN = img.parentNode, tmpNode, pre, next;
  9287. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  9288. pN = pN.parentNode;
  9289. }
  9290. tmpNode = pN;
  9291. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  9292. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  9293. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9294. }) == 1) {
  9295. pre = tmpNode.previousSibling;
  9296. next = tmpNode.nextSibling;
  9297. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  9298. pre.appendChild(tmpNode.firstChild);
  9299. while (next.firstChild) {
  9300. pre.appendChild(next.firstChild);
  9301. }
  9302. domUtils.remove(tmpNode);
  9303. domUtils.remove(next);
  9304. } else {
  9305. domUtils.setStyle(tmpNode, 'text-align', '');
  9306. }
  9307. }
  9308. range.selectNode(img).select();
  9309. }
  9310. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  9311. if(align == 'none'){
  9312. domUtils.removeAttributes(img,'align');
  9313. }
  9314. break;
  9315. case 'center':
  9316. if (me.queryCommandValue('imagefloat') != 'center') {
  9317. pN = img.parentNode;
  9318. domUtils.setStyle(img, 'float', '');
  9319. domUtils.removeAttributes(img,'align');
  9320. tmpNode = img;
  9321. while (pN && domUtils.getChildCount(pN, function (node) {
  9322. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9323. }) == 1
  9324. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  9325. tmpNode = pN;
  9326. pN = pN.parentNode;
  9327. }
  9328. range.setStartBefore(tmpNode).setCursor(false);
  9329. pN = me.document.createElement('div');
  9330. pN.appendChild(tmpNode);
  9331. domUtils.setStyle(tmpNode, 'float', '');
  9332. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  9333. tmpNode = me.document.getElementById('_img_parent_tmp');
  9334. tmpNode.removeAttribute('id');
  9335. tmpNode = tmpNode.firstChild;
  9336. range.selectNode(tmpNode).select();
  9337. //去掉后边多余的元素
  9338. next = tmpNode.parentNode.nextSibling;
  9339. if (next && domUtils.isEmptyNode(next)) {
  9340. domUtils.remove(next);
  9341. }
  9342. }
  9343. break;
  9344. }
  9345. }
  9346. }
  9347. },
  9348. queryCommandValue:function () {
  9349. var range = this.selection.getRange(),
  9350. startNode, floatStyle;
  9351. if (range.collapsed) {
  9352. return 'none';
  9353. }
  9354. startNode = range.getClosedNode();
  9355. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9356. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  9357. if (floatStyle == 'none') {
  9358. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  9359. }
  9360. return {
  9361. left:1,
  9362. right:1,
  9363. center:1
  9364. }[floatStyle] ? floatStyle : 'none';
  9365. }
  9366. return 'none';
  9367. },
  9368. queryCommandState:function () {
  9369. var range = this.selection.getRange(),
  9370. startNode;
  9371. if (range.collapsed) return -1;
  9372. startNode = range.getClosedNode();
  9373. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9374. return 0;
  9375. }
  9376. return -1;
  9377. }
  9378. };
  9379. /**
  9380. * 插入图片
  9381. * @command insertimage
  9382. * @method execCommand
  9383. * @param { String } cmd 命令字符串
  9384. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  9385. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  9386. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  9387. * @example
  9388. * ```javascript
  9389. * editor.execCommand( 'insertimage', {
  9390. * src:'a/b/c.jpg',
  9391. * width:'100',
  9392. * height:'100'
  9393. * } );
  9394. * ```
  9395. * @example
  9396. * ```javascript
  9397. * editor.execCommand( 'insertimage', [{
  9398. * src:'a/b/c.jpg',
  9399. * width:'100',
  9400. * height:'100'
  9401. * },{
  9402. * src:'a/b/d.jpg',
  9403. * width:'100',
  9404. * height:'100'
  9405. * }] );
  9406. * ```
  9407. */
  9408. UE.commands['insertimage'] = {
  9409. execCommand:function (cmd, opt) {
  9410. opt = utils.isArray(opt) ? opt : [opt];
  9411. if (!opt.length) {
  9412. return;
  9413. }
  9414. var me = this,
  9415. range = me.selection.getRange(),
  9416. img = range.getClosedNode();
  9417. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  9418. var first = opt.shift();
  9419. var floatStyle = first['floatStyle'];
  9420. delete first['floatStyle'];
  9421. //// img.style.border = (first.border||0) +"px solid #000";
  9422. //// img.style.margin = (first.margin||0) +"px";
  9423. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  9424. domUtils.setAttributes(img, first);
  9425. me.execCommand('imagefloat', floatStyle);
  9426. if (opt.length > 0) {
  9427. range.setStartAfter(img).setCursor(false, true);
  9428. me.execCommand('insertimage', opt);
  9429. }
  9430. } else {
  9431. var html = [], str = '', ci;
  9432. ci = opt[0];
  9433. if (opt.length == 1) {
  9434. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9435. (ci.width ? 'width="' + ci.width + '" ' : '') +
  9436. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9437. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  9438. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  9439. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  9440. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  9441. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  9442. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  9443. if (ci['floatStyle'] == 'center') {
  9444. str = '<p style="text-align: center">' + str + '</p>';
  9445. }
  9446. html.push(str);
  9447. } else {
  9448. for (var i = 0; ci = opt[i++];) {
  9449. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  9450. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9451. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9452. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  9453. (ci.border || '') + '" ' +
  9454. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  9455. html.push(str);
  9456. }
  9457. }
  9458. me.execCommand('insertHtml', html.join(''));
  9459. }
  9460. }
  9461. };
  9462. /**
  9463. * 段落格式
  9464. * @file
  9465. * @since 1.2.6.1
  9466. */
  9467. /**
  9468. * 段落对齐方式
  9469. * @command justify
  9470. * @method execCommand
  9471. * @param { String } cmd 命令字符串
  9472. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  9473. * @example
  9474. * ```javascript
  9475. * editor.execCommand( 'justify', 'center' );
  9476. * ```
  9477. */
  9478. /**
  9479. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  9480. * @command justify
  9481. * @method queryCommandValue
  9482. * @param { String } cmd 命令字符串
  9483. * @return { String } 返回段落对齐方式
  9484. * @example
  9485. * ```javascript
  9486. * editor.queryCommandValue( 'justify' );
  9487. * ```
  9488. */
  9489. UE.plugins['justify']=function(){
  9490. var me=this,
  9491. block = domUtils.isBlockElm,
  9492. defaultValue = {
  9493. left:1,
  9494. right:1,
  9495. center:1,
  9496. justify:1
  9497. },
  9498. doJustify = function (range, style) {
  9499. var bookmark = range.createBookmark(),
  9500. filterFn = function (node) {
  9501. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  9502. };
  9503. range.enlarge(true);
  9504. var bookmark2 = range.createBookmark(),
  9505. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  9506. tmpRange = range.cloneRange(),
  9507. tmpNode;
  9508. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  9509. if (current.nodeType == 3 || !block(current)) {
  9510. tmpRange.setStartBefore(current);
  9511. while (current && current !== bookmark2.end && !block(current)) {
  9512. tmpNode = current;
  9513. current = domUtils.getNextDomNode(current, false, null, function (node) {
  9514. return !block(node);
  9515. });
  9516. }
  9517. tmpRange.setEndAfter(tmpNode);
  9518. var common = tmpRange.getCommonAncestor();
  9519. if (!domUtils.isBody(common) && block(common)) {
  9520. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  9521. current = common;
  9522. } else {
  9523. var p = range.document.createElement('p');
  9524. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  9525. var frag = tmpRange.extractContents();
  9526. p.appendChild(frag);
  9527. tmpRange.insertNode(p);
  9528. current = p;
  9529. }
  9530. current = domUtils.getNextDomNode(current, false, filterFn);
  9531. } else {
  9532. current = domUtils.getNextDomNode(current, true, filterFn);
  9533. }
  9534. }
  9535. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  9536. };
  9537. UE.commands['justify'] = {
  9538. execCommand:function (cmdName, align) {
  9539. var range = this.selection.getRange(),
  9540. txt;
  9541. //闭合时单独处理
  9542. if (range.collapsed) {
  9543. txt = this.document.createTextNode('p');
  9544. range.insertNode(txt);
  9545. }
  9546. doJustify(range, align);
  9547. if (txt) {
  9548. range.setStartBefore(txt).collapse(true);
  9549. domUtils.remove(txt);
  9550. }
  9551. range.select();
  9552. return true;
  9553. },
  9554. queryCommandValue:function () {
  9555. var startNode = this.selection.getStart(),
  9556. value = domUtils.getComputedStyle(startNode, 'text-align');
  9557. return defaultValue[value] ? value : 'left';
  9558. },
  9559. queryCommandState:function () {
  9560. var start = this.selection.getStart(),
  9561. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  9562. return cell? -1:0;
  9563. }
  9564. };
  9565. };
  9566. /**
  9567. * 字体颜色,背景色,字号,字体,下划线,删除线
  9568. * @file
  9569. * @since 1.2.6.1
  9570. */
  9571. /**
  9572. * 字体颜色
  9573. * @command forecolor
  9574. * @method execCommand
  9575. * @param { String } cmd 命令字符串
  9576. * @param { String } value 色值(必须十六进制)
  9577. * @example
  9578. * ```javascript
  9579. * editor.execCommand( 'forecolor', '#000' );
  9580. * ```
  9581. */
  9582. /**
  9583. * 返回选区字体颜色
  9584. * @command forecolor
  9585. * @method queryCommandValue
  9586. * @param { String } cmd 命令字符串
  9587. * @return { String } 返回字体颜色
  9588. * @example
  9589. * ```javascript
  9590. * editor.queryCommandValue( 'forecolor' );
  9591. * ```
  9592. */
  9593. /**
  9594. * 字体背景颜色
  9595. * @command backcolor
  9596. * @method execCommand
  9597. * @param { String } cmd 命令字符串
  9598. * @param { String } value 色值(必须十六进制)
  9599. * @example
  9600. * ```javascript
  9601. * editor.execCommand( 'backcolor', '#000' );
  9602. * ```
  9603. */
  9604. /**
  9605. * 返回选区字体颜色
  9606. * @command backcolor
  9607. * @method queryCommandValue
  9608. * @param { String } cmd 命令字符串
  9609. * @return { String } 返回字体背景颜色
  9610. * @example
  9611. * ```javascript
  9612. * editor.queryCommandValue( 'backcolor' );
  9613. * ```
  9614. */
  9615. /**
  9616. * 字体大小
  9617. * @command fontsize
  9618. * @method execCommand
  9619. * @param { String } cmd 命令字符串
  9620. * @param { String } value 字体大小
  9621. * @example
  9622. * ```javascript
  9623. * editor.execCommand( 'fontsize', '14px' );
  9624. * ```
  9625. */
  9626. /**
  9627. * 返回选区字体大小
  9628. * @command fontsize
  9629. * @method queryCommandValue
  9630. * @param { String } cmd 命令字符串
  9631. * @return { String } 返回字体大小
  9632. * @example
  9633. * ```javascript
  9634. * editor.queryCommandValue( 'fontsize' );
  9635. * ```
  9636. */
  9637. /**
  9638. * 字体样式
  9639. * @command fontfamily
  9640. * @method execCommand
  9641. * @param { String } cmd 命令字符串
  9642. * @param { String } value 字体样式
  9643. * @example
  9644. * ```javascript
  9645. * editor.execCommand( 'fontfamily', '微软雅黑' );
  9646. * ```
  9647. */
  9648. /**
  9649. * 返回选区字体样式
  9650. * @command fontfamily
  9651. * @method queryCommandValue
  9652. * @param { String } cmd 命令字符串
  9653. * @return { String } 返回字体样式
  9654. * @example
  9655. * ```javascript
  9656. * editor.queryCommandValue( 'fontfamily' );
  9657. * ```
  9658. */
  9659. /**
  9660. * 字体下划线,与删除线互斥
  9661. * @command underline
  9662. * @method execCommand
  9663. * @param { String } cmd 命令字符串
  9664. * @example
  9665. * ```javascript
  9666. * editor.execCommand( 'underline' );
  9667. * ```
  9668. */
  9669. /**
  9670. * 字体删除线,与下划线互斥
  9671. * @command strikethrough
  9672. * @method execCommand
  9673. * @param { String } cmd 命令字符串
  9674. * @example
  9675. * ```javascript
  9676. * editor.execCommand( 'strikethrough' );
  9677. * ```
  9678. */
  9679. /**
  9680. * 字体边框
  9681. * @command fontborder
  9682. * @method execCommand
  9683. * @param { String } cmd 命令字符串
  9684. * @example
  9685. * ```javascript
  9686. * editor.execCommand( 'fontborder' );
  9687. * ```
  9688. */
  9689. UE.plugins['font'] = function () {
  9690. var me = this,
  9691. fonts = {
  9692. 'forecolor': 'color',
  9693. 'backcolor': 'background-color',
  9694. 'fontsize': 'font-size',
  9695. 'fontfamily': 'font-family',
  9696. 'underline': 'text-decoration',
  9697. 'strikethrough': 'text-decoration',
  9698. 'fontborder': 'border'
  9699. },
  9700. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  9701. needSetChild = {
  9702. 'forecolor': 'color',
  9703. 'backcolor': 'background-color',
  9704. 'fontsize': 'font-size',
  9705. 'fontfamily': 'font-family'
  9706. };
  9707. me.setOpt({
  9708. 'fontfamily': [
  9709. { name: 'songti', val: '宋体,SimSun'},
  9710. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  9711. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  9712. { name: 'heiti', val: '黑体, SimHei'},
  9713. { name: 'lishu', val: '隶书, SimLi'},
  9714. { name: 'andaleMono', val: 'andale mono'},
  9715. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  9716. { name: 'arialBlack', val: 'arial black,avant garde'},
  9717. { name: 'comicSansMs', val: 'comic sans ms'},
  9718. { name: 'impact', val: 'impact,chicago'},
  9719. { name: 'timesNewRoman', val: 'times new roman'}
  9720. ],
  9721. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  9722. });
  9723. function mergeWithParent(node){
  9724. var parent;
  9725. while(parent = node.parentNode){
  9726. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  9727. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  9728. }) == 1) {
  9729. parent.style.cssText += node.style.cssText;
  9730. domUtils.remove(node,true);
  9731. node = parent;
  9732. }else{
  9733. break;
  9734. }
  9735. }
  9736. }
  9737. function mergeChild(rng,cmdName,value){
  9738. if(needSetChild[cmdName]){
  9739. rng.adjustmentBoundary();
  9740. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  9741. var start = rng.startContainer.childNodes[rng.startOffset];
  9742. if(start && domUtils.isTagNode(start,'span')){
  9743. var bk = rng.createBookmark();
  9744. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  9745. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  9746. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  9747. return;
  9748. }
  9749. domUtils.removeStyle(span,needSetChild[cmdName]);
  9750. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  9751. domUtils.remove(span,true)
  9752. }
  9753. });
  9754. rng.moveToBookmark(bk)
  9755. }
  9756. }
  9757. }
  9758. }
  9759. function mergesibling(rng,cmdName,value) {
  9760. var collapsed = rng.collapsed,
  9761. bk = rng.createBookmark(), common;
  9762. if (collapsed) {
  9763. common = bk.start.parentNode;
  9764. while (dtd.$inline[common.tagName]) {
  9765. common = common.parentNode;
  9766. }
  9767. } else {
  9768. common = domUtils.getCommonAncestor(bk.start, bk.end);
  9769. }
  9770. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  9771. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  9772. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  9773. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  9774. domUtils.remove(span, true);
  9775. }else{
  9776. domUtils.removeStyle(span,'border');
  9777. }
  9778. return
  9779. }
  9780. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  9781. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  9782. }
  9783. if(!(cmdName=='fontborder' && value=='none')){
  9784. var next = span.nextSibling;
  9785. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  9786. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  9787. span.appendChild(next);
  9788. next = span.nextSibling;
  9789. continue;
  9790. }
  9791. if (next.style.cssText == span.style.cssText) {
  9792. domUtils.moveChild(next, span);
  9793. domUtils.remove(next);
  9794. }
  9795. if (span.nextSibling === next)
  9796. break;
  9797. next = span.nextSibling;
  9798. }
  9799. }
  9800. mergeWithParent(span);
  9801. if(browser.ie && browser.version > 8 ){
  9802. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  9803. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  9804. if(parent && !/background-color/.test(span.style.cssText)){
  9805. span.style.backgroundColor = parent.style.backgroundColor;
  9806. }
  9807. }
  9808. });
  9809. rng.moveToBookmark(bk);
  9810. mergeChild(rng,cmdName,value)
  9811. }
  9812. me.addInputRule(function (root) {
  9813. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  9814. if (node.tagName == 'font') {
  9815. var cssStyle = [];
  9816. for (var p in node.attrs) {
  9817. switch (p) {
  9818. case 'size':
  9819. cssStyle.push('font-size:' +
  9820. ({
  9821. '1':'10',
  9822. '2':'12',
  9823. '3':'16',
  9824. '4':'18',
  9825. '5':'24',
  9826. '6':'32',
  9827. '7':'48'
  9828. }[node.attrs[p]] || node.attrs[p]) + 'px');
  9829. break;
  9830. case 'color':
  9831. cssStyle.push('color:' + node.attrs[p]);
  9832. break;
  9833. case 'face':
  9834. cssStyle.push('font-family:' + node.attrs[p]);
  9835. break;
  9836. case 'style':
  9837. cssStyle.push(node.attrs[p]);
  9838. }
  9839. }
  9840. node.attrs = {
  9841. 'style': cssStyle.join(';')
  9842. };
  9843. } else {
  9844. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  9845. node.attrs = {
  9846. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  9847. }
  9848. }
  9849. node.tagName = 'span';
  9850. });
  9851. // utils.each(root.getNodesByTagName('span'), function (node) {
  9852. // var val;
  9853. // if(val = node.getAttr('class')){
  9854. // if(/fontstrikethrough/.test(val)){
  9855. // node.setStyle('text-decoration','line-through');
  9856. // if(node.attrs['class']){
  9857. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  9858. // }else{
  9859. // node.setAttr('class')
  9860. // }
  9861. // }
  9862. // if(/fontborder/.test(val)){
  9863. // node.setStyle('border','1px solid #000');
  9864. // if(node.attrs['class']){
  9865. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  9866. // }else{
  9867. // node.setAttr('class')
  9868. // }
  9869. // }
  9870. // }
  9871. // });
  9872. });
  9873. // me.addOutputRule(function(root){
  9874. // utils.each(root.getNodesByTagName('span'), function (node) {
  9875. // var val;
  9876. // if(val = node.getStyle('text-decoration')){
  9877. // if(/line-through/.test(val)){
  9878. // if(node.attrs['class']){
  9879. // node.attrs['class'] += ' fontstrikethrough';
  9880. // }else{
  9881. // node.setAttr('class','fontstrikethrough')
  9882. // }
  9883. // }
  9884. //
  9885. // node.setStyle('text-decoration')
  9886. // }
  9887. // if(val = node.getStyle('border')){
  9888. // if(/1px/.test(val) && /solid/.test(val)){
  9889. // if(node.attrs['class']){
  9890. // node.attrs['class'] += ' fontborder';
  9891. //
  9892. // }else{
  9893. // node.setAttr('class','fontborder')
  9894. // }
  9895. // }
  9896. // node.setStyle('border')
  9897. //
  9898. // }
  9899. // });
  9900. // });
  9901. for (var p in fonts) {
  9902. (function (cmd, style) {
  9903. UE.commands[cmd] = {
  9904. execCommand: function (cmdName, value) {
  9905. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  9906. cmdName == 'fontborder' ? '1px solid #000' :
  9907. 'line-through');
  9908. var me = this,
  9909. range = this.selection.getRange(),
  9910. text;
  9911. if (value == 'default') {
  9912. if (range.collapsed) {
  9913. text = me.document.createTextNode('font');
  9914. range.insertNode(text).select();
  9915. }
  9916. me.execCommand('removeFormat', 'span,a', style);
  9917. if (text) {
  9918. range.setStartBefore(text).collapse(true);
  9919. domUtils.remove(text);
  9920. }
  9921. mergesibling(range,cmdName,value);
  9922. range.select()
  9923. } else {
  9924. if (!range.collapsed) {
  9925. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  9926. me.execCommand('removeFormat', 'span,a', style);
  9927. }
  9928. range = me.selection.getRange();
  9929. range.applyInlineStyle('span', {'style': style + ':' + value});
  9930. mergesibling(range, cmdName,value);
  9931. range.select();
  9932. } else {
  9933. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  9934. text = me.document.createTextNode('font');
  9935. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  9936. //for ie hack when enter
  9937. range.insertNode(text);
  9938. if (needCmd[cmd]) {
  9939. range.selectNode(text).select();
  9940. me.execCommand('removeFormat', 'span,a', style, null);
  9941. span = domUtils.findParentByTagName(text, 'span', true);
  9942. range.setStartBefore(text);
  9943. }
  9944. span && (span.style.cssText += ';' + style + ':' + value);
  9945. range.collapse(true).select();
  9946. } else {
  9947. range.insertNode(text);
  9948. range.selectNode(text).select();
  9949. span = range.document.createElement('span');
  9950. if (needCmd[cmd]) {
  9951. //a标签内的不处理跳过
  9952. if (domUtils.findParentByTagName(text, 'a', true)) {
  9953. range.setStartBefore(text).setCursor();
  9954. domUtils.remove(text);
  9955. return;
  9956. }
  9957. me.execCommand('removeFormat', 'span,a', style);
  9958. }
  9959. span.style.cssText = style + ':' + value;
  9960. text.parentNode.insertBefore(span, text);
  9961. //修复,span套span 但样式不继承的问题
  9962. if (!browser.ie || browser.ie && browser.version == 9) {
  9963. var spanParent = span.parentNode;
  9964. while (!domUtils.isBlockElm(spanParent)) {
  9965. if (spanParent.tagName == 'SPAN') {
  9966. //opera合并style不会加入";"
  9967. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  9968. }
  9969. spanParent = spanParent.parentNode;
  9970. }
  9971. }
  9972. if (opera) {
  9973. setTimeout(function () {
  9974. range.setStart(span, 0).collapse(true);
  9975. mergesibling(range, cmdName,value);
  9976. range.select();
  9977. });
  9978. } else {
  9979. range.setStart(span, 0).collapse(true);
  9980. mergesibling(range,cmdName,value);
  9981. range.select();
  9982. }
  9983. //trace:981
  9984. //domUtils.mergeToParent(span)
  9985. }
  9986. domUtils.remove(text);
  9987. }
  9988. }
  9989. return true;
  9990. },
  9991. queryCommandValue: function (cmdName) {
  9992. var startNode = this.selection.getStart();
  9993. //trace:946
  9994. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  9995. var tmpNode = startNode, value;
  9996. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  9997. if (tmpNode.nodeType == 1) {
  9998. value = domUtils.getComputedStyle(tmpNode, style);
  9999. if (value != 'none') {
  10000. return value;
  10001. }
  10002. }
  10003. tmpNode = tmpNode.parentNode;
  10004. }
  10005. return 'none';
  10006. }
  10007. if (cmdName == 'fontborder') {
  10008. var tmp = startNode, val;
  10009. while (tmp && dtd.$inline[tmp.tagName]) {
  10010. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  10011. if (/1px/.test(val) && /solid/.test(val)) {
  10012. return val;
  10013. }
  10014. }
  10015. tmp = tmp.parentNode;
  10016. }
  10017. return ''
  10018. }
  10019. if( cmdName == 'FontSize' ) {
  10020. var styleVal = domUtils.getComputedStyle(startNode, style),
  10021. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  10022. if( tmp ) {
  10023. return Math.floor( tmp[1] ) + tmp[2];
  10024. }
  10025. return styleVal;
  10026. }
  10027. return domUtils.getComputedStyle(startNode, style);
  10028. },
  10029. queryCommandState: function (cmdName) {
  10030. if (!needCmd[cmdName])
  10031. return 0;
  10032. var val = this.queryCommandValue(cmdName);
  10033. if (cmdName == 'fontborder') {
  10034. return /1px/.test(val) && /solid/.test(val)
  10035. } else {
  10036. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  10037. }
  10038. }
  10039. };
  10040. })(p, fonts[p]);
  10041. }
  10042. };
  10043. /**
  10044. * 超链接
  10045. * @file
  10046. * @since 1.2.6.1
  10047. */
  10048. /**
  10049. * 插入超链接
  10050. * @command link
  10051. * @method execCommand
  10052. * @param { String } cmd 命令字符串
  10053. * @param { Object } options 设置自定义属性,例如:url、title、target
  10054. * @example
  10055. * ```javascript
  10056. * editor.execCommand( 'link', '{
  10057. * url:'ueditor.baidu.com',
  10058. * title:'ueditor',
  10059. * target:'_blank'
  10060. * }' );
  10061. * ```
  10062. */
  10063. /**
  10064. * 返回当前选中的第一个超链接节点
  10065. * @command link
  10066. * @method queryCommandValue
  10067. * @param { String } cmd 命令字符串
  10068. * @return { Element } 超链接节点
  10069. * @example
  10070. * ```javascript
  10071. * editor.queryCommandValue( 'link' );
  10072. * ```
  10073. */
  10074. /**
  10075. * 取消超链接
  10076. * @command unlink
  10077. * @method execCommand
  10078. * @param { String } cmd 命令字符串
  10079. * @example
  10080. * ```javascript
  10081. * editor.execCommand( 'unlink');
  10082. * ```
  10083. */
  10084. UE.plugins['link'] = function(){
  10085. function optimize( range ) {
  10086. var start = range.startContainer,end = range.endContainer;
  10087. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  10088. range.setStartBefore( start );
  10089. }
  10090. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  10091. range.setEndAfter( end );
  10092. }
  10093. }
  10094. UE.commands['unlink'] = {
  10095. execCommand : function() {
  10096. var range = this.selection.getRange(),
  10097. bookmark;
  10098. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  10099. return;
  10100. }
  10101. bookmark = range.createBookmark();
  10102. optimize( range );
  10103. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  10104. },
  10105. queryCommandState : function(){
  10106. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  10107. }
  10108. };
  10109. function doLink(range,opt,me){
  10110. var rngClone = range.cloneRange(),
  10111. link = me.queryCommandValue('link');
  10112. optimize( range = range.adjustmentBoundary() );
  10113. var start = range.startContainer;
  10114. if(start.nodeType == 1 && link){
  10115. start = start.childNodes[range.startOffset];
  10116. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  10117. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  10118. }
  10119. }
  10120. if( !rngClone.collapsed || link){
  10121. range.removeInlineStyle( 'a' );
  10122. rngClone = range.cloneRange();
  10123. }
  10124. if ( rngClone.collapsed ) {
  10125. var a = range.document.createElement( 'a'),
  10126. text = '';
  10127. if(opt.textValue){
  10128. text = utils.html(opt.textValue);
  10129. delete opt.textValue;
  10130. }else{
  10131. text = utils.html(opt.href);
  10132. }
  10133. domUtils.setAttributes( a, opt );
  10134. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  10135. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  10136. range.setStartAfter(start).collapse(true);
  10137. }
  10138. a[browser.ie ? 'innerText' : 'textContent'] = text;
  10139. range.insertNode(a).selectNode( a );
  10140. } else {
  10141. range.applyInlineStyle( 'a', opt );
  10142. }
  10143. }
  10144. UE.commands['link'] = {
  10145. execCommand : function( cmdName, opt ) {
  10146. var range;
  10147. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  10148. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  10149. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  10150. doLink(range=this.selection.getRange(),opt,this);
  10151. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  10152. range.collapse().select(true);
  10153. },
  10154. queryCommandValue : function() {
  10155. var range = this.selection.getRange(),
  10156. node;
  10157. if ( range.collapsed ) {
  10158. // node = this.selection.getStart();
  10159. //在ie下getstart()取值偏上了
  10160. node = range.startContainer;
  10161. node = node.nodeType == 1 ? node : node.parentNode;
  10162. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  10163. return node;
  10164. }
  10165. } else {
  10166. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  10167. range.shrinkBoundary();
  10168. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  10169. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  10170. common = range.getCommonAncestor();
  10171. node = domUtils.findParentByTagName( common, 'a', true );
  10172. if ( !node && common.nodeType == 1){
  10173. var as = common.getElementsByTagName( 'a' ),
  10174. ps,pe;
  10175. for ( var i = 0,ci; ci = as[i++]; ) {
  10176. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  10177. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  10178. &&
  10179. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  10180. ) {
  10181. node = ci;
  10182. break;
  10183. }
  10184. }
  10185. }
  10186. return node;
  10187. }
  10188. },
  10189. queryCommandState : function() {
  10190. //判断如果是视频的话连接不可用
  10191. //fix 853
  10192. var img = this.selection.getRange().getClosedNode(),
  10193. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  10194. return flag ? -1 : 0;
  10195. }
  10196. };
  10197. };
  10198. /**
  10199. * 清除格式
  10200. * @file
  10201. * @since 1.2.6.1
  10202. */
  10203. /**
  10204. * 清除文字样式
  10205. * @command removeformat
  10206. * @method execCommand
  10207. * @param { String } cmd 命令字符串
  10208. * @param {String} tags 以逗号隔开的标签。如:strong
  10209. * @param {String} style 样式如:color
  10210. * @param {String} attrs 属性如:width
  10211. * @example
  10212. * ```javascript
  10213. * editor.execCommand( 'removeformat', 'strong','color','width' );
  10214. * ```
  10215. */
  10216. UE.plugins['removeformat'] = function(){
  10217. var me = this;
  10218. me.setOpt({
  10219. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  10220. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  10221. });
  10222. me.commands['removeformat'] = {
  10223. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  10224. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  10225. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  10226. range = new dom.Range( this.document ),
  10227. bookmark,node,parent,
  10228. filter = function( node ) {
  10229. return node.nodeType == 1;
  10230. };
  10231. function isRedundantSpan (node) {
  10232. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  10233. return 0;
  10234. }
  10235. if (browser.ie) {
  10236. //ie 下判断实效,所以只能简单用style来判断
  10237. //return node.style.cssText == '' ? 1 : 0;
  10238. var attrs = node.attributes;
  10239. if ( attrs.length ) {
  10240. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  10241. if ( attrs[i].specified ) {
  10242. return 0;
  10243. }
  10244. }
  10245. return 1;
  10246. }
  10247. }
  10248. return !node.attributes.length;
  10249. }
  10250. function doRemove( range ) {
  10251. var bookmark1 = range.createBookmark();
  10252. if ( range.collapsed ) {
  10253. range.enlarge( true );
  10254. }
  10255. //不能把a标签切了
  10256. if(!notIncludeA){
  10257. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  10258. if(aNode){
  10259. range.setStartBefore(aNode);
  10260. }
  10261. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  10262. if(aNode){
  10263. range.setEndAfter(aNode);
  10264. }
  10265. }
  10266. bookmark = range.createBookmark();
  10267. node = bookmark.start;
  10268. //切开始
  10269. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10270. domUtils.breakParent( node, parent );
  10271. domUtils.clearEmptySibling( node );
  10272. }
  10273. if ( bookmark.end ) {
  10274. //切结束
  10275. node = bookmark.end;
  10276. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10277. domUtils.breakParent( node, parent );
  10278. domUtils.clearEmptySibling( node );
  10279. }
  10280. //开始去除样式
  10281. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  10282. next;
  10283. while ( current ) {
  10284. if ( current == bookmark.end ) {
  10285. break;
  10286. }
  10287. next = domUtils.getNextDomNode( current, true, filter );
  10288. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  10289. if ( tagReg.test( current.tagName ) ) {
  10290. if ( style ) {
  10291. domUtils.removeStyle( current, style );
  10292. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  10293. domUtils.remove( current, true );
  10294. }
  10295. } else {
  10296. domUtils.remove( current, true );
  10297. }
  10298. } else {
  10299. //trace:939 不能把list上的样式去掉
  10300. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  10301. domUtils.removeAttributes( current, removeFormatAttributes );
  10302. if ( isRedundantSpan( current ) ){
  10303. domUtils.remove( current, true );
  10304. }
  10305. }
  10306. }
  10307. }
  10308. current = next;
  10309. }
  10310. }
  10311. //trace:1035
  10312. //trace:1096 不能把td上的样式去掉,比如边框
  10313. var pN = bookmark.start.parentNode;
  10314. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  10315. domUtils.removeAttributes( pN,removeFormatAttributes );
  10316. }
  10317. pN = bookmark.end.parentNode;
  10318. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  10319. domUtils.removeAttributes( pN,removeFormatAttributes );
  10320. }
  10321. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  10322. //清除冗余的代码 <b><bookmark></b>
  10323. var node = range.startContainer,
  10324. tmp,
  10325. collapsed = range.collapsed;
  10326. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10327. tmp = node.parentNode;
  10328. range.setStartBefore(node);
  10329. //trace:937
  10330. //更新结束边界
  10331. if(range.startContainer === range.endContainer){
  10332. range.endOffset--;
  10333. }
  10334. domUtils.remove(node);
  10335. node = tmp;
  10336. }
  10337. if(!collapsed){
  10338. node = range.endContainer;
  10339. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10340. tmp = node.parentNode;
  10341. range.setEndBefore(node);
  10342. domUtils.remove(node);
  10343. node = tmp;
  10344. }
  10345. }
  10346. }
  10347. range = this.selection.getRange();
  10348. doRemove( range );
  10349. range.select();
  10350. }
  10351. };
  10352. };
  10353. /**
  10354. * 首行缩进
  10355. * @file
  10356. * @since 1.2.6.1
  10357. */
  10358. /**
  10359. * 缩进
  10360. * @command indent
  10361. * @method execCommand
  10362. * @param { String } cmd 命令字符串
  10363. * @example
  10364. * ```javascript
  10365. * editor.execCommand( 'indent' );
  10366. * ```
  10367. */
  10368. UE.commands['indent'] = {
  10369. execCommand : function() {
  10370. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  10371. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  10372. },
  10373. queryCommandState : function() {
  10374. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  10375. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  10376. }
  10377. };
  10378. /**
  10379. * 打印
  10380. * @file
  10381. * @since 1.2.6.1
  10382. */
  10383. /**
  10384. * 打印
  10385. * @command print
  10386. * @method execCommand
  10387. * @param { String } cmd 命令字符串
  10388. * @example
  10389. * ```javascript
  10390. * editor.execCommand( 'print' );
  10391. * ```
  10392. */
  10393. UE.commands['print'] = {
  10394. execCommand : function(){
  10395. this.window.print();
  10396. },
  10397. notNeedUndo : 1
  10398. };
  10399. /**
  10400. * 段落样式
  10401. * @file
  10402. * @since 1.2.6.1
  10403. */
  10404. /**
  10405. * 段落格式
  10406. * @command paragraph
  10407. * @method execCommand
  10408. * @param { String } cmd 命令字符串
  10409. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  10410. * @param {Object} attrs 标签的属性
  10411. * @example
  10412. * ```javascript
  10413. * editor.execCommand( 'Paragraph','h1','{
  10414. * class:'test'
  10415. * }' );
  10416. * ```
  10417. */
  10418. /**
  10419. * 返回选区内节点标签名
  10420. * @command paragraph
  10421. * @method queryCommandValue
  10422. * @param { String } cmd 命令字符串
  10423. * @return { String } 节点标签名
  10424. * @example
  10425. * ```javascript
  10426. * editor.queryCommandValue( 'Paragraph' );
  10427. * ```
  10428. */
  10429. UE.plugins['paragraph'] = function() {
  10430. var me = this,
  10431. block = domUtils.isBlockElm,
  10432. notExchange = ['TD','LI','PRE'],
  10433. doParagraph = function(range,style,attrs,sourceCmdName){
  10434. var bookmark = range.createBookmark(),
  10435. filterFn = function( node ) {
  10436. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  10437. },
  10438. para;
  10439. range.enlarge( true );
  10440. var bookmark2 = range.createBookmark(),
  10441. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  10442. tmpRange = range.cloneRange(),
  10443. tmpNode;
  10444. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  10445. if ( current.nodeType == 3 || !block( current ) ) {
  10446. tmpRange.setStartBefore( current );
  10447. while ( current && current !== bookmark2.end && !block( current ) ) {
  10448. tmpNode = current;
  10449. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  10450. return !block( node );
  10451. } );
  10452. }
  10453. tmpRange.setEndAfter( tmpNode );
  10454. para = range.document.createElement( style );
  10455. if(attrs){
  10456. domUtils.setAttributes(para,attrs);
  10457. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  10458. para.style.cssText = attrs.style;
  10459. }
  10460. }
  10461. para.appendChild( tmpRange.extractContents() );
  10462. //需要内容占位
  10463. if(domUtils.isEmptyNode(para)){
  10464. domUtils.fillChar(range.document,para);
  10465. }
  10466. tmpRange.insertNode( para );
  10467. var parent = para.parentNode;
  10468. //如果para上一级是一个block元素且不是body,td就删除它
  10469. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  10470. //存储dir,style
  10471. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  10472. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  10473. //trace:1070
  10474. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  10475. //trace:1030
  10476. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  10477. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  10478. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  10479. }
  10480. //trace:1706 选择的就是h1-6要删除
  10481. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  10482. domUtils.setAttributes(parent,attrs);
  10483. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  10484. parent.style.cssText = attrs.style;
  10485. }
  10486. domUtils.remove(para,true);
  10487. para = parent;
  10488. }else{
  10489. domUtils.remove( para.parentNode, true );
  10490. }
  10491. }
  10492. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  10493. current = parent;
  10494. }else{
  10495. current = para;
  10496. }
  10497. current = domUtils.getNextDomNode( current, false, filterFn );
  10498. } else {
  10499. current = domUtils.getNextDomNode( current, true, filterFn );
  10500. }
  10501. }
  10502. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  10503. };
  10504. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  10505. me.commands['paragraph'] = {
  10506. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  10507. var range = this.selection.getRange();
  10508. //闭合时单独处理
  10509. if(range.collapsed){
  10510. var txt = this.document.createTextNode('p');
  10511. range.insertNode(txt);
  10512. //去掉冗余的fillchar
  10513. if(browser.ie){
  10514. var node = txt.previousSibling;
  10515. if(node && domUtils.isWhitespace(node)){
  10516. domUtils.remove(node);
  10517. }
  10518. node = txt.nextSibling;
  10519. if(node && domUtils.isWhitespace(node)){
  10520. domUtils.remove(node);
  10521. }
  10522. }
  10523. }
  10524. range = doParagraph(range,style,attrs,sourceCmdName);
  10525. if(txt){
  10526. range.setStartBefore(txt).collapse(true);
  10527. pN = txt.parentNode;
  10528. domUtils.remove(txt);
  10529. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  10530. domUtils.fillNode(this.document,pN);
  10531. }
  10532. }
  10533. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  10534. var child = range.startContainer.childNodes[range.startOffset];
  10535. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  10536. range.setStart(child,0).collapse(true);
  10537. }
  10538. }
  10539. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  10540. range.select();
  10541. return true;
  10542. },
  10543. queryCommandValue : function() {
  10544. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  10545. return node ? node.tagName.toLowerCase() : '';
  10546. }
  10547. };
  10548. };
  10549. /**
  10550. * 插入时间和日期
  10551. * @file
  10552. * @since 1.2.6.1
  10553. */
  10554. /**
  10555. * 插入时间,默认格式:12:59:59
  10556. * @command time
  10557. * @method execCommand
  10558. * @param { String } cmd 命令字符串
  10559. * @example
  10560. * ```javascript
  10561. * editor.execCommand( 'time');
  10562. * ```
  10563. */
  10564. /**
  10565. * 插入日期,默认格式:2013-08-30
  10566. * @command date
  10567. * @method execCommand
  10568. * @param { String } cmd 命令字符串
  10569. * @example
  10570. * ```javascript
  10571. * editor.execCommand( 'date');
  10572. * ```
  10573. */
  10574. UE.commands['time'] = UE.commands["date"] = {
  10575. execCommand : function(cmd, format){
  10576. var date = new Date;
  10577. function formatTime(date, format) {
  10578. var hh = ('0' + date.getHours()).slice(-2),
  10579. ii = ('0' + date.getMinutes()).slice(-2),
  10580. ss = ('0' + date.getSeconds()).slice(-2);
  10581. format = format || 'hh:ii:ss';
  10582. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  10583. }
  10584. function formatDate(date, format) {
  10585. var yyyy = ('000' + date.getFullYear()).slice(-4),
  10586. yy = yyyy.slice(-2),
  10587. mm = ('0' + (date.getMonth()+1)).slice(-2),
  10588. dd = ('0' + date.getDate()).slice(-2);
  10589. format = format || 'yyyy-mm-dd';
  10590. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  10591. }
  10592. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  10593. }
  10594. };
  10595. /**
  10596. * 段前段后间距插件
  10597. * @file
  10598. * @since 1.2.6.1
  10599. */
  10600. /**
  10601. * 设置段间距
  10602. * @command rowspacing
  10603. * @method execCommand
  10604. * @param { String } cmd 命令字符串
  10605. * @param { String } value 段间距的值,以px为单位
  10606. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  10607. * @example
  10608. * ```javascript
  10609. * editor.execCommand( 'rowspacing', '10', 'top' );
  10610. * ```
  10611. */
  10612. UE.plugins['rowspacing'] = function(){
  10613. var me = this;
  10614. me.setOpt({
  10615. 'rowspacingtop':['5', '10', '15', '20', '25'],
  10616. 'rowspacingbottom':['5', '10', '15', '20', '25']
  10617. });
  10618. me.commands['rowspacing'] = {
  10619. execCommand : function( cmdName,value,dir ) {
  10620. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  10621. return true;
  10622. },
  10623. queryCommandValue : function(cmdName,dir) {
  10624. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  10625. value;
  10626. //trace:1026
  10627. if(pN){
  10628. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  10629. return !value ? 0 : value;
  10630. }
  10631. return 0;
  10632. }
  10633. };
  10634. };
  10635. /**
  10636. * 设置行内间距
  10637. * @file
  10638. * @since 1.2.6.1
  10639. */
  10640. UE.plugins['lineheight'] = function(){
  10641. var me = this;
  10642. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  10643. /**
  10644. * 行距
  10645. * @command lineheight
  10646. * @method execCommand
  10647. * @param { String } cmdName 命令字符串
  10648. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  10649. * @example
  10650. * ```javascript
  10651. * editor.execCommand( 'lineheight', 1.5);
  10652. * ```
  10653. */
  10654. /**
  10655. * 查询当前选区内容的行高大小
  10656. * @command lineheight
  10657. * @method queryCommandValue
  10658. * @param { String } cmd 命令字符串
  10659. * @return { String } 返回当前行高大小
  10660. * @example
  10661. * ```javascript
  10662. * editor.queryCommandValue( 'lineheight' );
  10663. * ```
  10664. */
  10665. me.commands['lineheight'] = {
  10666. execCommand : function( cmdName,value ) {
  10667. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  10668. return true;
  10669. },
  10670. queryCommandValue : function() {
  10671. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  10672. if(pN){
  10673. var value = domUtils.getComputedStyle(pN,'line-height');
  10674. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  10675. }
  10676. }
  10677. };
  10678. };
  10679. ///import core
  10680. ///commands 字数统计
  10681. ///commandsName WordCount,wordCount
  10682. ///commandsTitle 字数统计
  10683. /*
  10684. * Created by JetBrains WebStorm.
  10685. * User: taoqili
  10686. * Date: 11-9-7
  10687. * Time: 下午8:18
  10688. * To change this template use File | Settings | File Templates.
  10689. */
  10690. UE.plugins['wordcount'] = function(){
  10691. var me = this;
  10692. me.setOpt('wordCount',true);
  10693. me.addListener('contentchange',function(){
  10694. me.fireEvent('wordcount');
  10695. });
  10696. var timer;
  10697. me.addListener('ready',function(){
  10698. var me = this;
  10699. domUtils.on(me.body,"keyup",function(evt){
  10700. var code = evt.keyCode||evt.which,
  10701. //忽略的按键,ctr,alt,shift,方向键
  10702. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  10703. if(code in ignores) return;
  10704. clearTimeout(timer);
  10705. timer = setTimeout(function(){
  10706. me.fireEvent('wordcount');
  10707. },200)
  10708. })
  10709. });
  10710. };
  10711. UE.plugins['dragdrop'] = function (){
  10712. var me = this;
  10713. me.ready(function(){
  10714. domUtils.on(this.body,'dragend',function(){
  10715. var rng = me.selection.getRange();
  10716. var node = rng.getClosedNode()||me.selection.getStart();
  10717. if(node && node.tagName == 'IMG'){
  10718. var pre = node.previousSibling,next;
  10719. while(next = node.nextSibling){
  10720. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  10721. domUtils.remove(next)
  10722. }else{
  10723. break;
  10724. }
  10725. }
  10726. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  10727. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  10728. pre.appendChild(node);
  10729. domUtils.moveChild(next,pre);
  10730. domUtils.remove(next);
  10731. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  10732. next.insertBefore(node,next.firstChild);
  10733. }
  10734. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  10735. domUtils.remove(pre)
  10736. }
  10737. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  10738. domUtils.remove(next)
  10739. }
  10740. rng.selectNode(node).select();
  10741. me.fireEvent('saveScene');
  10742. }
  10743. }
  10744. })
  10745. });
  10746. me.addListener('keyup', function(type, evt) {
  10747. var keyCode = evt.keyCode || evt.which;
  10748. if (keyCode == 13) {
  10749. var rng = me.selection.getRange(),node;
  10750. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  10751. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  10752. domUtils.removeStyle(node,'text-align')
  10753. }
  10754. }
  10755. }
  10756. })
  10757. };
  10758. /**
  10759. * undo redo
  10760. * @file
  10761. * @since 1.2.6.1
  10762. */
  10763. /**
  10764. * 撤销上一次执行的命令
  10765. * @command undo
  10766. * @method execCommand
  10767. * @param { String } cmd 命令字符串
  10768. * @example
  10769. * ```javascript
  10770. * editor.execCommand( 'undo' );
  10771. * ```
  10772. */
  10773. /**
  10774. * 重做上一次执行的命令
  10775. * @command redo
  10776. * @method execCommand
  10777. * @param { String } cmd 命令字符串
  10778. * @example
  10779. * ```javascript
  10780. * editor.execCommand( 'redo' );
  10781. * ```
  10782. */
  10783. UE.plugins['undo'] = function () {
  10784. var saveSceneTimer;
  10785. var me = this,
  10786. maxUndoCount = me.options.maxUndoCount || 20,
  10787. maxInputCount = me.options.maxInputCount || 20,
  10788. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  10789. var noNeedFillCharTags = {
  10790. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  10791. };
  10792. var orgState = me.options.autoClearEmptyNode;
  10793. function compareAddr(indexA, indexB) {
  10794. if (indexA.length != indexB.length)
  10795. return 0;
  10796. for (var i = 0, l = indexA.length; i < l; i++) {
  10797. if (indexA[i] != indexB[i])
  10798. return 0
  10799. }
  10800. return 1;
  10801. }
  10802. function compareRangeAddress(rngAddrA, rngAddrB) {
  10803. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  10804. return 0;
  10805. }
  10806. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  10807. return 0;
  10808. }
  10809. return 1;
  10810. }
  10811. function UndoManager() {
  10812. this.list = [];
  10813. this.index = 0;
  10814. this.hasUndo = false;
  10815. this.hasRedo = false;
  10816. this.undo = function () {
  10817. if (this.hasUndo) {
  10818. if (!this.list[this.index - 1] && this.list.length == 1) {
  10819. this.reset();
  10820. return;
  10821. }
  10822. while (this.list[this.index].content == this.list[this.index - 1].content) {
  10823. this.index--;
  10824. if (this.index == 0) {
  10825. return this.restore(0);
  10826. }
  10827. }
  10828. this.restore(--this.index);
  10829. }
  10830. };
  10831. this.redo = function () {
  10832. if (this.hasRedo) {
  10833. while (this.list[this.index].content == this.list[this.index + 1].content) {
  10834. this.index++;
  10835. if (this.index == this.list.length - 1) {
  10836. return this.restore(this.index);
  10837. }
  10838. }
  10839. this.restore(++this.index);
  10840. }
  10841. };
  10842. this.restore = function () {
  10843. var me = this.editor;
  10844. var scene = this.list[this.index];
  10845. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  10846. me.options.autoClearEmptyNode = false;
  10847. me.filterInputRule(root);
  10848. me.options.autoClearEmptyNode = orgState;
  10849. //trace:873
  10850. //去掉展位符
  10851. me.document.body.innerHTML = root.toHtml();
  10852. me.fireEvent('afterscencerestore');
  10853. //处理undo后空格不展位的问题
  10854. if (browser.ie) {
  10855. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  10856. if(domUtils.isEmptyNode(node)){
  10857. domUtils.fillNode(me.document, node);
  10858. }
  10859. })
  10860. }
  10861. try{
  10862. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  10863. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  10864. }catch(e){}
  10865. this.update();
  10866. this.clearKey();
  10867. //不能把自己reset了
  10868. me.fireEvent('reset', true);
  10869. };
  10870. this.getScene = function () {
  10871. var me = this.editor;
  10872. var rng = me.selection.getRange(),
  10873. rngAddress = rng.createAddress(false,true);
  10874. me.fireEvent('beforegetscene');
  10875. var root = UE.htmlparser(me.body.innerHTML);
  10876. me.options.autoClearEmptyNode = false;
  10877. me.filterOutputRule(root);
  10878. me.options.autoClearEmptyNode = orgState;
  10879. var cont = root.toHtml();
  10880. //trace:3461
  10881. //这个会引起回退时导致空格丢失的情况
  10882. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  10883. me.fireEvent('aftergetscene');
  10884. return {
  10885. address:rngAddress,
  10886. content:cont
  10887. }
  10888. };
  10889. this.save = function (notCompareRange,notSetCursor) {
  10890. clearTimeout(saveSceneTimer);
  10891. var currentScene = this.getScene(notSetCursor),
  10892. lastScene = this.list[this.index];
  10893. //内容相同位置相同不存
  10894. if (lastScene && lastScene.content == currentScene.content &&
  10895. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  10896. ) {
  10897. return;
  10898. }
  10899. this.list = this.list.slice(0, this.index + 1);
  10900. this.list.push(currentScene);
  10901. //如果大于最大数量了,就把最前的剔除
  10902. if (this.list.length > maxUndoCount) {
  10903. this.list.shift();
  10904. }
  10905. this.index = this.list.length - 1;
  10906. this.clearKey();
  10907. //跟新undo/redo状态
  10908. this.update();
  10909. };
  10910. this.update = function () {
  10911. this.hasRedo = !!this.list[this.index + 1];
  10912. this.hasUndo = !!this.list[this.index - 1];
  10913. };
  10914. this.reset = function () {
  10915. this.list = [];
  10916. this.index = 0;
  10917. this.hasUndo = false;
  10918. this.hasRedo = false;
  10919. this.clearKey();
  10920. };
  10921. this.clearKey = function () {
  10922. keycont = 0;
  10923. lastKeyCode = null;
  10924. };
  10925. }
  10926. me.undoManger = new UndoManager();
  10927. me.undoManger.editor = me;
  10928. function saveScene() {
  10929. this.undoManger.save();
  10930. }
  10931. me.addListener('saveScene', function () {
  10932. var args = Array.prototype.splice.call(arguments,1);
  10933. this.undoManger.save.apply(this.undoManger,args);
  10934. });
  10935. // me.addListener('beforeexeccommand', saveScene);
  10936. // me.addListener('afterexeccommand', saveScene);
  10937. me.addListener('reset', function (type, exclude) {
  10938. if (!exclude) {
  10939. this.undoManger.reset();
  10940. }
  10941. });
  10942. me.commands['redo'] = me.commands['undo'] = {
  10943. execCommand:function (cmdName) {
  10944. this.undoManger[cmdName]();
  10945. },
  10946. queryCommandState:function (cmdName) {
  10947. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  10948. },
  10949. notNeedUndo:1
  10950. };
  10951. var keys = {
  10952. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  10953. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  10954. 37:1, 38:1, 39:1, 40:1
  10955. },
  10956. keycont = 0,
  10957. lastKeyCode;
  10958. //输入法状态下不计算字符数
  10959. var inputType = false;
  10960. me.addListener('ready', function () {
  10961. domUtils.on(this.body, 'compositionstart', function () {
  10962. inputType = true;
  10963. });
  10964. domUtils.on(this.body, 'compositionend', function () {
  10965. inputType = false;
  10966. })
  10967. });
  10968. //快捷键
  10969. me.addshortcutkey({
  10970. "Undo":"ctrl+90", //undo
  10971. "Redo":"ctrl+89" //redo
  10972. });
  10973. var isCollapsed = true;
  10974. me.addListener('keydown', function (type, evt) {
  10975. var me = this;
  10976. var keyCode = evt.keyCode || evt.which;
  10977. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  10978. if (inputType)
  10979. return;
  10980. if(!me.selection.getRange().collapsed){
  10981. me.undoManger.save(false,true);
  10982. isCollapsed = false;
  10983. return;
  10984. }
  10985. if (me.undoManger.list.length == 0) {
  10986. me.undoManger.save(true);
  10987. }
  10988. clearTimeout(saveSceneTimer);
  10989. function save(cont){
  10990. if (cont.selection.getRange().collapsed)
  10991. cont.fireEvent('contentchange');
  10992. cont.undoManger.save(false,true);
  10993. cont.fireEvent('selectionchange');
  10994. }
  10995. saveSceneTimer = setTimeout(function(){
  10996. if(inputType){
  10997. var interalTimer = setInterval(function(){
  10998. if(!inputType){
  10999. save(me);
  11000. clearInterval(interalTimer)
  11001. }
  11002. },300)
  11003. return;
  11004. }
  11005. save(me);
  11006. },200);
  11007. lastKeyCode = keyCode;
  11008. keycont++;
  11009. if (keycont >= maxInputCount ) {
  11010. save(me)
  11011. }
  11012. }
  11013. });
  11014. me.addListener('keyup', function (type, evt) {
  11015. var keyCode = evt.keyCode || evt.which;
  11016. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  11017. if (inputType)
  11018. return;
  11019. if(!isCollapsed){
  11020. this.undoManger.save(false,true);
  11021. isCollapsed = true;
  11022. }
  11023. }
  11024. });
  11025. //扩展实例,添加关闭和开启命令undo
  11026. me.stopCmdUndo = function(){
  11027. me.__hasEnterExecCommand = true;
  11028. };
  11029. me.startCmdUndo = function(){
  11030. me.__hasEnterExecCommand = false;
  11031. }
  11032. };
  11033. ///import core
  11034. ///import plugins/inserthtml.js
  11035. ///import plugins/undo.js
  11036. ///import plugins/serialize.js
  11037. ///commands 粘贴
  11038. ///commandsName PastePlain
  11039. ///commandsTitle 纯文本粘贴模式
  11040. /*
  11041. ** @description 粘贴
  11042. * @author zhanyi
  11043. */
  11044. UE.plugins['paste'] = function () {
  11045. function getClipboardData(callback) {
  11046. var doc = this.document;
  11047. if (doc.getElementById('baidu_pastebin')) {
  11048. return;
  11049. }
  11050. var range = this.selection.getRange(),
  11051. bk = range.createBookmark(),
  11052. //创建剪贴的容器div
  11053. pastebin = doc.createElement('div');
  11054. pastebin.id = 'baidu_pastebin';
  11055. // Safari 要求div必须有内容,才能粘贴内容进来
  11056. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  11057. doc.body.appendChild(pastebin);
  11058. //trace:717 隐藏的span不能得到top
  11059. //bk.start.innerHTML = '&nbsp;';
  11060. bk.start.style.display = '';
  11061. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  11062. //要在现在光标平行的位置加入,否则会出现跳动的问题
  11063. domUtils.getXY(bk.start).y + 'px';
  11064. range.selectNodeContents(pastebin).select(true);
  11065. setTimeout(function () {
  11066. if (browser.webkit) {
  11067. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  11068. if (domUtils.isEmptyNode(pi)) {
  11069. domUtils.remove(pi);
  11070. } else {
  11071. pastebin = pi;
  11072. break;
  11073. }
  11074. }
  11075. }
  11076. try {
  11077. pastebin.parentNode.removeChild(pastebin);
  11078. } catch (e) {
  11079. }
  11080. range.moveToBookmark(bk).select(true);
  11081. callback(pastebin);
  11082. }, 0);
  11083. }
  11084. var me = this;
  11085. var txtContent, htmlContent, address;
  11086. function filter(div) {
  11087. var html;
  11088. if (div.firstChild) {
  11089. //去掉cut中添加的边界值
  11090. var nodes = domUtils.getElementsByTagName(div, 'span');
  11091. for (var i = 0, ni; ni = nodes[i++];) {
  11092. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  11093. domUtils.remove(ni);
  11094. }
  11095. }
  11096. if (browser.webkit) {
  11097. var brs = div.querySelectorAll('div br');
  11098. for (var i = 0, bi; bi = brs[i++];) {
  11099. var pN = bi.parentNode;
  11100. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  11101. pN.innerHTML = '<p><br/></p>';
  11102. domUtils.remove(pN);
  11103. }
  11104. }
  11105. var divs = div.querySelectorAll('#baidu_pastebin');
  11106. for (var i = 0, di; di = divs[i++];) {
  11107. var tmpP = me.document.createElement('p');
  11108. di.parentNode.insertBefore(tmpP, di);
  11109. while (di.firstChild) {
  11110. tmpP.appendChild(di.firstChild);
  11111. }
  11112. domUtils.remove(di);
  11113. }
  11114. var metas = div.querySelectorAll('meta');
  11115. for (var i = 0, ci; ci = metas[i++];) {
  11116. domUtils.remove(ci);
  11117. }
  11118. var brs = div.querySelectorAll('br');
  11119. for (i = 0; ci = brs[i++];) {
  11120. if (/^apple-/i.test(ci.className)) {
  11121. domUtils.remove(ci);
  11122. }
  11123. }
  11124. }
  11125. if (browser.gecko) {
  11126. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  11127. for (i = 0; ci = dirtyNodes[i++];) {
  11128. ci.removeAttribute('_moz_dirty');
  11129. }
  11130. }
  11131. if (!browser.ie) {
  11132. var spans = div.querySelectorAll('span.Apple-style-span');
  11133. for (var i = 0, ci; ci = spans[i++];) {
  11134. domUtils.remove(ci, true);
  11135. }
  11136. }
  11137. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  11138. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  11139. //过滤word粘贴过来的冗余属性
  11140. html = UE.filterWord(html);
  11141. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  11142. var root = UE.htmlparser(html);
  11143. //如果给了过滤规则就先进行过滤
  11144. if (me.options.filterRules) {
  11145. UE.filterNode(root, me.options.filterRules);
  11146. }
  11147. //执行默认的处理
  11148. me.filterInputRule(root);
  11149. //针对chrome的处理
  11150. if (browser.webkit) {
  11151. var br = root.lastChild();
  11152. if (br && br.type == 'element' && br.tagName == 'br') {
  11153. root.removeChild(br)
  11154. }
  11155. utils.each(me.body.querySelectorAll('div'), function (node) {
  11156. if (domUtils.isEmptyBlock(node)) {
  11157. domUtils.remove(node,true)
  11158. }
  11159. })
  11160. }
  11161. html = {'html': root.toHtml()};
  11162. me.fireEvent('beforepaste', html, root);
  11163. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  11164. if(!html.html){
  11165. return;
  11166. }
  11167. root = UE.htmlparser(html.html,true);
  11168. //如果开启了纯文本模式
  11169. if (me.queryCommandState('pasteplain') === 1) {
  11170. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  11171. } else {
  11172. //文本模式
  11173. UE.filterNode(root, me.options.filterTxtRules);
  11174. txtContent = root.toHtml();
  11175. //完全模式
  11176. htmlContent = html.html;
  11177. address = me.selection.getRange().createAddress(true);
  11178. me.execCommand('insertHtml', htmlContent, true);
  11179. }
  11180. me.fireEvent("afterpaste", html);
  11181. }
  11182. }
  11183. me.addListener('pasteTransfer', function (cmd, plainType) {
  11184. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  11185. var range = me.selection.getRange();
  11186. range.moveToAddress(address, true);
  11187. if (!range.collapsed) {
  11188. while (!domUtils.isBody(range.startContainer)
  11189. ) {
  11190. var start = range.startContainer;
  11191. if(start.nodeType == 1){
  11192. start = start.childNodes[range.startOffset];
  11193. if(!start){
  11194. range.setStartBefore(range.startContainer);
  11195. continue;
  11196. }
  11197. var pre = start.previousSibling;
  11198. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  11199. range.setStartBefore(pre)
  11200. }
  11201. }
  11202. if(range.startOffset == 0){
  11203. range.setStartBefore(range.startContainer);
  11204. }else{
  11205. break;
  11206. }
  11207. }
  11208. while (!domUtils.isBody(range.endContainer)
  11209. ) {
  11210. var end = range.endContainer;
  11211. if(end.nodeType == 1){
  11212. end = end.childNodes[range.endOffset];
  11213. if(!end){
  11214. range.setEndAfter(range.endContainer);
  11215. continue;
  11216. }
  11217. var next = end.nextSibling;
  11218. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  11219. range.setEndAfter(next)
  11220. }
  11221. }
  11222. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  11223. range.setEndAfter(range.endContainer);
  11224. }else{
  11225. break;
  11226. }
  11227. }
  11228. }
  11229. range.deleteContents();
  11230. range.select(true);
  11231. me.__hasEnterExecCommand = true;
  11232. var html = htmlContent;
  11233. if (plainType === 2) {
  11234. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  11235. tagName = tagName.toLowerCase();
  11236. if ({img: 1}[tagName]) {
  11237. return a;
  11238. }
  11239. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  11240. if ({
  11241. 'src': 1,
  11242. 'href': 1,
  11243. 'name': 1
  11244. }[atr.toLowerCase()]) {
  11245. return atr + '=' + val + ' '
  11246. }
  11247. return ''
  11248. });
  11249. if ({
  11250. 'span': 1,
  11251. 'div': 1
  11252. }[tagName]) {
  11253. return ''
  11254. } else {
  11255. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  11256. }
  11257. });
  11258. } else if (plainType) {
  11259. html = txtContent;
  11260. }
  11261. me.execCommand('inserthtml', html, true);
  11262. me.__hasEnterExecCommand = false;
  11263. var rng = me.selection.getRange();
  11264. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  11265. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  11266. ) {
  11267. rng.setStartBefore(rng.startContainer);
  11268. }
  11269. var tmpAddress = rng.createAddress(true);
  11270. address.endAddress = tmpAddress.startAddress;
  11271. }
  11272. });
  11273. me.addListener('ready', function () {
  11274. domUtils.on(me.body, 'cut', function () {
  11275. var range = me.selection.getRange();
  11276. if (!range.collapsed && me.undoManger) {
  11277. me.undoManger.save();
  11278. }
  11279. });
  11280. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  11281. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  11282. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  11283. return;
  11284. }
  11285. getClipboardData.call(me, function (div) {
  11286. filter(div);
  11287. });
  11288. });
  11289. });
  11290. };
  11291. ///import core
  11292. ///import plugins/undo.js
  11293. ///commands 设置回车标签p或br
  11294. ///commandsName EnterKey
  11295. ///commandsTitle 设置回车标签p或br
  11296. /*
  11297. * @description 处理回车
  11298. * @author zhanyi
  11299. */
  11300. UE.plugins['enterkey'] = function() {
  11301. var hTag,
  11302. me = this,
  11303. tag = me.options.enterTag;
  11304. me.addListener('keyup', function(type, evt) {
  11305. var keyCode = evt.keyCode || evt.which;
  11306. if (keyCode == 13) {
  11307. var range = me.selection.getRange(),
  11308. start = range.startContainer,
  11309. doSave;
  11310. //修正在h1-h6里边回车后不能嵌套p的问题
  11311. if (!browser.ie) {
  11312. if (/h\d/i.test(hTag)) {
  11313. if (browser.gecko) {
  11314. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  11315. if (!h) {
  11316. me.document.execCommand('formatBlock', false, '<p>');
  11317. doSave = 1;
  11318. }
  11319. } else {
  11320. //chrome remove div
  11321. if (start.nodeType == 1) {
  11322. var tmp = me.document.createTextNode(''),div;
  11323. range.insertNode(tmp);
  11324. div = domUtils.findParentByTagName(tmp, 'div', true);
  11325. if (div) {
  11326. var p = me.document.createElement('p');
  11327. while (div.firstChild) {
  11328. p.appendChild(div.firstChild);
  11329. }
  11330. div.parentNode.insertBefore(p, div);
  11331. domUtils.remove(div);
  11332. range.setStartBefore(tmp).setCursor();
  11333. doSave = 1;
  11334. }
  11335. domUtils.remove(tmp);
  11336. }
  11337. }
  11338. if (me.undoManger && doSave) {
  11339. me.undoManger.save();
  11340. }
  11341. }
  11342. //没有站位符,会出现多行的问题
  11343. browser.opera && range.select();
  11344. }else{
  11345. me.fireEvent('saveScene',true,true)
  11346. }
  11347. }
  11348. });
  11349. me.addListener('keydown', function(type, evt) {
  11350. var keyCode = evt.keyCode || evt.which;
  11351. if (keyCode == 13) {//回车
  11352. if(me.fireEvent('beforeenterkeydown')){
  11353. domUtils.preventDefault(evt);
  11354. return;
  11355. }
  11356. me.fireEvent('saveScene',true,true);
  11357. hTag = '';
  11358. var range = me.selection.getRange();
  11359. if (!range.collapsed) {
  11360. //跨td不能删
  11361. var start = range.startContainer,
  11362. end = range.endContainer,
  11363. startTd = domUtils.findParentByTagName(start, 'td', true),
  11364. endTd = domUtils.findParentByTagName(end, 'td', true);
  11365. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  11366. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  11367. return;
  11368. }
  11369. }
  11370. if (tag == 'p') {
  11371. if (!browser.ie) {
  11372. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  11373. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  11374. //trace:2431
  11375. if (!start && !browser.opera) {
  11376. me.document.execCommand('formatBlock', false, '<p>');
  11377. if (browser.gecko) {
  11378. range = me.selection.getRange();
  11379. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  11380. start && domUtils.removeDirtyAttr(start);
  11381. }
  11382. } else {
  11383. hTag = start.tagName;
  11384. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  11385. }
  11386. }
  11387. } else {
  11388. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  11389. if (!range.collapsed) {
  11390. range.deleteContents();
  11391. start = range.startContainer;
  11392. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  11393. while (start.nodeType == 1) {
  11394. if (dtd.$empty[start.tagName]) {
  11395. range.setStartBefore(start).setCursor();
  11396. if (me.undoManger) {
  11397. me.undoManger.save();
  11398. }
  11399. return false;
  11400. }
  11401. if (!start.firstChild) {
  11402. var br = range.document.createElement('br');
  11403. start.appendChild(br);
  11404. range.setStart(start, 0).setCursor();
  11405. if (me.undoManger) {
  11406. me.undoManger.save();
  11407. }
  11408. return false;
  11409. }
  11410. start = start.firstChild;
  11411. }
  11412. if (start === range.startContainer.childNodes[range.startOffset]) {
  11413. br = range.document.createElement('br');
  11414. range.insertNode(br).setCursor();
  11415. } else {
  11416. range.setStart(start, 0).setCursor();
  11417. }
  11418. } else {
  11419. br = range.document.createElement('br');
  11420. range.insertNode(br).setStartAfter(br).setCursor();
  11421. }
  11422. } else {
  11423. br = range.document.createElement('br');
  11424. range.insertNode(br);
  11425. var parent = br.parentNode;
  11426. if (parent.lastChild === br) {
  11427. br.parentNode.insertBefore(br.cloneNode(true), br);
  11428. range.setStartBefore(br);
  11429. } else {
  11430. range.setStartAfter(br);
  11431. }
  11432. range.setCursor();
  11433. }
  11434. }
  11435. }
  11436. });
  11437. };
  11438. /*
  11439. * 处理特殊键的兼容性问题
  11440. */
  11441. UE.plugins['keystrokes'] = function() {
  11442. var me = this;
  11443. var collapsed = true;
  11444. me.addListener('keydown', function(type, evt) {
  11445. var keyCode = evt.keyCode || evt.which,
  11446. rng = me.selection.getRange();
  11447. //处理全选的情况
  11448. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  11449. || keyCode >= 48 && keyCode <= 57 ||
  11450. keyCode >= 96 && keyCode <= 111 || {
  11451. 13:1,
  11452. 8:1,
  11453. 46:1
  11454. }[keyCode])
  11455. ){
  11456. var tmpNode = rng.startContainer;
  11457. if(domUtils.isFillChar(tmpNode)){
  11458. rng.setStartBefore(tmpNode)
  11459. }
  11460. tmpNode = rng.endContainer;
  11461. if(domUtils.isFillChar(tmpNode)){
  11462. rng.setEndAfter(tmpNode)
  11463. }
  11464. rng.txtToElmBoundary();
  11465. //结束边界可能放到了br的前边,要把br包含进来
  11466. // x[xxx]<br/>
  11467. if(rng.endContainer && rng.endContainer.nodeType == 1){
  11468. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  11469. if(tmpNode && domUtils.isBr(tmpNode)){
  11470. rng.setEndAfter(tmpNode);
  11471. }
  11472. }
  11473. if(rng.startOffset == 0){
  11474. tmpNode = rng.startContainer;
  11475. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  11476. tmpNode = rng.endContainer;
  11477. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  11478. me.fireEvent('saveScene');
  11479. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  11480. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  11481. me._selectionChange();
  11482. return;
  11483. }
  11484. }
  11485. }
  11486. }
  11487. //处理backspace
  11488. if (keyCode == 8) {
  11489. rng = me.selection.getRange();
  11490. collapsed = rng.collapsed;
  11491. if(me.fireEvent('delkeydown',evt)){
  11492. return;
  11493. }
  11494. var start,end;
  11495. //避免按两次删除才能生效的问题
  11496. if(rng.collapsed && rng.inFillChar()){
  11497. start = rng.startContainer;
  11498. if(domUtils.isFillChar(start)){
  11499. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  11500. domUtils.remove(start)
  11501. }else{
  11502. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  11503. rng.startOffset--;
  11504. rng.collapse(true).select(true)
  11505. }
  11506. }
  11507. //解决选中control元素不能删除的问题
  11508. if (start = rng.getClosedNode()) {
  11509. me.fireEvent('saveScene');
  11510. rng.setStartBefore(start);
  11511. domUtils.remove(start);
  11512. rng.setCursor();
  11513. me.fireEvent('saveScene');
  11514. domUtils.preventDefault(evt);
  11515. return;
  11516. }
  11517. //阻止在table上的删除
  11518. if (!browser.ie) {
  11519. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  11520. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  11521. if (start && !end || !start && end || start !== end) {
  11522. evt.preventDefault();
  11523. return;
  11524. }
  11525. }
  11526. }
  11527. //处理tab键的逻辑
  11528. if (keyCode == 9) {
  11529. //不处理以下标签
  11530. var excludeTagNameForTabKey = {
  11531. 'ol' : 1,
  11532. 'ul' : 1,
  11533. 'table':1
  11534. };
  11535. //处理组件里的tab按下事件
  11536. if(me.fireEvent('tabkeydown',evt)){
  11537. domUtils.preventDefault(evt);
  11538. return;
  11539. }
  11540. var range = me.selection.getRange();
  11541. me.fireEvent('saveScene');
  11542. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  11543. txt += tabNode;
  11544. }
  11545. var span = me.document.createElement('span');
  11546. span.innerHTML = txt + domUtils.fillChar;
  11547. if (range.collapsed) {
  11548. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  11549. } else {
  11550. var filterFn = function(node) {
  11551. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  11552. };
  11553. //普通的情况
  11554. start = domUtils.findParent(range.startContainer, filterFn,true);
  11555. end = domUtils.findParent(range.endContainer, filterFn,true);
  11556. if (start && end && start === end) {
  11557. range.deleteContents();
  11558. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  11559. } else {
  11560. var bookmark = range.createBookmark();
  11561. range.enlarge(true);
  11562. var bookmark2 = range.createBookmark(),
  11563. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  11564. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  11565. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  11566. current = domUtils.getNextDomNode(current, false, filterFn);
  11567. }
  11568. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  11569. }
  11570. }
  11571. domUtils.preventDefault(evt)
  11572. }
  11573. //trace:1634
  11574. //ff的del键在容器空的时候,也会删除
  11575. if(browser.gecko && keyCode == 46){
  11576. range = me.selection.getRange();
  11577. if(range.collapsed){
  11578. start = range.startContainer;
  11579. if(domUtils.isEmptyBlock(start)){
  11580. var parent = start.parentNode;
  11581. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  11582. start = parent;
  11583. parent = parent.parentNode;
  11584. }
  11585. if(start === parent.lastChild)
  11586. evt.preventDefault();
  11587. return;
  11588. }
  11589. }
  11590. }
  11591. });
  11592. me.addListener('keyup', function(type, evt) {
  11593. var keyCode = evt.keyCode || evt.which,
  11594. rng,me = this;
  11595. if(keyCode == 8){
  11596. if(me.fireEvent('delkeyup')){
  11597. return;
  11598. }
  11599. rng = me.selection.getRange();
  11600. if(rng.collapsed){
  11601. var tmpNode,
  11602. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  11603. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  11604. if(domUtils.isEmptyBlock(tmpNode)){
  11605. var pre = tmpNode.previousSibling;
  11606. if(pre && pre.nodeName != 'TABLE'){
  11607. domUtils.remove(tmpNode);
  11608. rng.setStartAtLast(pre).setCursor(false,true);
  11609. return;
  11610. }else{
  11611. var next = tmpNode.nextSibling;
  11612. if(next && next.nodeName != 'TABLE'){
  11613. domUtils.remove(tmpNode);
  11614. rng.setStartAtFirst(next).setCursor(false,true);
  11615. return;
  11616. }
  11617. }
  11618. }
  11619. }
  11620. //处理当删除到body时,要重新给p标签展位
  11621. if(domUtils.isBody(rng.startContainer)){
  11622. var tmpNode = domUtils.createElement(me.document,'p',{
  11623. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  11624. });
  11625. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  11626. }
  11627. }
  11628. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  11629. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  11630. if(browser.ie){
  11631. var span = rng.document.createElement('span');
  11632. rng.insertNode(span).setStartBefore(span).collapse(true);
  11633. rng.select();
  11634. domUtils.remove(span)
  11635. }else{
  11636. rng.select()
  11637. }
  11638. }
  11639. }
  11640. })
  11641. };
  11642. ///import core
  11643. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  11644. ///commandsName FixImgClick
  11645. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  11646. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  11647. UE.plugins['fiximgclick'] = (function () {
  11648. function Scale() {
  11649. this.editor = null;
  11650. this.resizer = null;
  11651. this.cover = null;
  11652. this.doc = document;
  11653. this.prePos = {x: 0, y: 0};
  11654. this.startPos = {x: 0, y: 0};
  11655. }
  11656. (function () {
  11657. var rect = [
  11658. //[left, top, width, height]
  11659. [0, 0, -1, -1],
  11660. [0, 0, 0, -1],
  11661. [0, 0, 1, -1],
  11662. [0, 0, -1, 0],
  11663. [0, 0, 1, 0],
  11664. [0, 0, -1, 1],
  11665. [0, 0, 0, 1],
  11666. [0, 0, 1, 1]
  11667. ];
  11668. Scale.prototype = {
  11669. init: function (editor) {
  11670. var me = this;
  11671. me.editor = editor;
  11672. me.startPos = this.prePos = {x: 0, y: 0};
  11673. me.dragId = -1;
  11674. var hands = [],
  11675. cover = me.cover = document.createElement('div'),
  11676. resizer = me.resizer = document.createElement('div');
  11677. cover.id = me.editor.ui.id + '_imagescale_cover';
  11678. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  11679. domUtils.on(cover, 'mousedown click', function () {
  11680. me.hide();
  11681. });
  11682. for (i = 0; i < 8; i++) {
  11683. hands.push('<span class="edui-editor-scale-hand' + i + '"></span>');
  11684. }
  11685. resizer.id = me.editor.ui.id + '_imagescale';
  11686. resizer.className = 'edui-editor-scale';
  11687. resizer.innerHTML = hands.join('');
  11688. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  11689. me.editor.ui.getDom().appendChild(cover);
  11690. me.editor.ui.getDom().appendChild(resizer);
  11691. me.initStyle();
  11692. me.initEvents();
  11693. },
  11694. initStyle: function () {
  11695. utils.cssRule('imagescale', '.edui-editor-scale{position:absolute;border:1px solid #38B2CE;}' +
  11696. '.edui-editor-scale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  11697. + '.edui-editor-scale .edui-editor-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  11698. + '.edui-editor-scale .edui-editor-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  11699. + '.edui-editor-scale .edui-editor-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  11700. + '.edui-editor-scale .edui-editor-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  11701. + '.edui-editor-scale .edui-editor-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  11702. + '.edui-editor-scale .edui-editor-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  11703. + '.edui-editor-scale .edui-editor-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  11704. + '.edui-editor-scale .edui-editor-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  11705. },
  11706. initEvents: function () {
  11707. var me = this;
  11708. me.startPos.x = me.startPos.y = 0;
  11709. me.isDraging = false;
  11710. },
  11711. _eventHandler: function (e) {
  11712. var me = this;
  11713. switch (e.type) {
  11714. case 'mousedown':
  11715. var hand = e.target || e.srcElement, hand;
  11716. if (hand.className.indexOf('edui-editor-scale-hand') != -1 && me.dragId == -1) {
  11717. me.dragId = hand.className.slice(-1);
  11718. me.startPos.x = me.prePos.x = e.clientX;
  11719. me.startPos.y = me.prePos.y = e.clientY;
  11720. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  11721. }
  11722. break;
  11723. case 'mousemove':
  11724. if (me.dragId != -1) {
  11725. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  11726. me.prePos.x = e.clientX;
  11727. me.prePos.y = e.clientY;
  11728. me.updateTargetElement();
  11729. }
  11730. break;
  11731. case 'mouseup':
  11732. if (me.dragId != -1) {
  11733. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  11734. me.updateTargetElement();
  11735. if (me.target.parentNode) me.attachTo(me.target);
  11736. me.dragId = -1;
  11737. }
  11738. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  11739. me.editor.fireEvent('contentchange');
  11740. break;
  11741. default:
  11742. break;
  11743. }
  11744. },
  11745. updateTargetElement: function () {
  11746. var me = this,
  11747. targetPos;
  11748. domUtils.setStyles(me.target, {
  11749. 'width': me.resizer.style.width,
  11750. 'height': me.resizer.style.height
  11751. });
  11752. me.attachTo(me.target);
  11753. },
  11754. updateContainerStyle: function (dir, offset) {
  11755. var me = this,
  11756. dom = me.resizer, tmp;
  11757. if (rect[dir][0] != 0) {
  11758. tmp = parseInt(dom.style.left) + offset.x;
  11759. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  11760. }
  11761. if (rect[dir][1] != 0) {
  11762. tmp = parseInt(dom.style.top) + offset.y;
  11763. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  11764. }
  11765. if (rect[dir][2] != 0) {
  11766. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  11767. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  11768. }
  11769. if (rect[dir][3] != 0) {
  11770. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  11771. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  11772. }
  11773. },
  11774. _validScaledProp: function (prop, value) {
  11775. var ele = this.resizer,
  11776. wrap = document;
  11777. value = isNaN(value) ? 0 : value;
  11778. switch (prop) {
  11779. case 'left':
  11780. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  11781. case 'top':
  11782. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  11783. case 'width':
  11784. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  11785. case 'height':
  11786. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  11787. }
  11788. },
  11789. hideCover: function () {
  11790. this.cover.style.display = 'none';
  11791. },
  11792. showCover: function () {
  11793. var me = this,
  11794. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  11795. iframePos = domUtils.getXY(me.editor.iframe);
  11796. domUtils.setStyles(me.cover, {
  11797. 'width': me.editor.iframe.offsetWidth + 'px',
  11798. 'height': me.editor.iframe.offsetHeight + 'px',
  11799. 'top': iframePos.y - editorPos.y + 'px',
  11800. 'left': iframePos.x - editorPos.x + 'px',
  11801. 'position': 'absolute',
  11802. 'display': ''
  11803. })
  11804. },
  11805. show: function (targetObj) {
  11806. var me = this;
  11807. me.resizer.style.display = 'block';
  11808. if(targetObj) me.attachTo(targetObj);
  11809. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  11810. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  11811. me.showCover();
  11812. me.editor.fireEvent('afterscaleshow', me);
  11813. me.editor.fireEvent('saveScene');
  11814. },
  11815. hide: function () {
  11816. var me = this;
  11817. me.hideCover();
  11818. me.resizer.style.display = 'none';
  11819. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  11820. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  11821. me.editor.fireEvent('afterscalehide', me);
  11822. },
  11823. proxy: function( fn, context ) {
  11824. return function(e) {
  11825. return fn.apply( context || this, arguments);
  11826. };
  11827. },
  11828. attachTo: function (targetObj) {
  11829. var me = this,
  11830. target = me.target = targetObj,
  11831. resizer = this.resizer,
  11832. imgPos = domUtils.getXY(target),
  11833. iframePos = domUtils.getXY(me.editor.iframe),
  11834. editorPos = domUtils.getXY(resizer.parentNode);
  11835. domUtils.setStyles(resizer, {
  11836. 'width': target.width + 'px',
  11837. 'height': target.height + 'px',
  11838. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  11839. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  11840. });
  11841. }
  11842. }
  11843. })();
  11844. return function () {
  11845. var me = this,
  11846. imageScale;
  11847. me.setOpt('imageScaleEnabled', true);
  11848. if ( !browser.ie && me.options.imageScaleEnabled) {
  11849. me.addListener('click', function (type, e) {
  11850. var range = me.selection.getRange(),
  11851. img = range.getClosedNode();
  11852. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  11853. if (!imageScale) {
  11854. imageScale = new Scale();
  11855. imageScale.init(me);
  11856. me.ui.getDom().appendChild(imageScale.resizer);
  11857. var _keyDownHandler = function (e) {
  11858. imageScale.hide();
  11859. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  11860. }, _mouseDownHandler = function (e) {
  11861. var ele = e.target || e.srcElement;
  11862. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-scale') == -1)) {
  11863. _keyDownHandler(e);
  11864. }
  11865. }, timer;
  11866. me.addListener('afterscaleshow', function (e) {
  11867. me.addListener('beforekeydown', _keyDownHandler);
  11868. me.addListener('beforemousedown', _mouseDownHandler);
  11869. domUtils.on(document, 'keydown', _keyDownHandler);
  11870. domUtils.on(document,'mousedown', _mouseDownHandler);
  11871. me.selection.getNative().removeAllRanges();
  11872. });
  11873. me.addListener('afterscalehide', function (e) {
  11874. me.removeListener('beforekeydown', _keyDownHandler);
  11875. me.removeListener('beforemousedown', _mouseDownHandler);
  11876. domUtils.un(document, 'keydown', _keyDownHandler);
  11877. domUtils.un(document,'mousedown', _mouseDownHandler);
  11878. var target = imageScale.target;
  11879. if (target.parentNode) {
  11880. me.selection.getRange().selectNode(target).select();
  11881. }
  11882. });
  11883. //TODO 有iframe的情况,mousedown不能往下传。。
  11884. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  11885. me.selection.getNative().removeAllRanges();
  11886. var ele = e.target || e.srcElement;
  11887. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  11888. timer = setTimeout(function () {
  11889. imageScale.hide();
  11890. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  11891. }, 200);
  11892. }
  11893. });
  11894. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  11895. var ele = e.target || e.srcElement;
  11896. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  11897. clearTimeout(timer);
  11898. }
  11899. });
  11900. }
  11901. imageScale.show(img);
  11902. } else {
  11903. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  11904. }
  11905. });
  11906. }
  11907. if (browser.webkit) {
  11908. me.addListener('click', function (type, e) {
  11909. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  11910. var range = new dom.Range(me.document);
  11911. range.selectNode(e.target).select();
  11912. }
  11913. });
  11914. }
  11915. }
  11916. })();
  11917. ///import core
  11918. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  11919. ///commandsName AutoHeight,autoHeightEnabled
  11920. ///commandsTitle 自动增高
  11921. /*
  11922. * @description 自动伸展
  11923. * @author zhanyi
  11924. */
  11925. UE.plugins['autoheight'] = function () {
  11926. var me = this;
  11927. //提供开关,就算加载也可以关闭
  11928. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  11929. if (!me.autoHeightEnabled) {
  11930. return;
  11931. }
  11932. var bakOverflow,
  11933. lastHeight = 0,
  11934. options = me.options,
  11935. currentHeight,
  11936. timer;
  11937. function adjustHeight() {
  11938. var me = this;
  11939. clearTimeout(timer);
  11940. if(isFullscreen)return;
  11941. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  11942. timer = setTimeout(function(){
  11943. var node = me.body.lastChild;
  11944. while(node && node.nodeType != 1){
  11945. node = node.previousSibling;
  11946. }
  11947. if(node && node.nodeType == 1){
  11948. node.style.clear = 'both';
  11949. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  11950. if (currentHeight != lastHeight) {
  11951. me.setHeight(currentHeight,true);
  11952. lastHeight = currentHeight;
  11953. }
  11954. domUtils.removeStyle(node,'clear');
  11955. }
  11956. },50)
  11957. }
  11958. }
  11959. var isFullscreen;
  11960. me.addListener('fullscreenchanged',function(cmd,f){
  11961. isFullscreen = f
  11962. });
  11963. me.addListener('destroy', function () {
  11964. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  11965. });
  11966. me.enableAutoHeight = function () {
  11967. var me = this;
  11968. if (!me.autoHeightEnabled) {
  11969. return;
  11970. }
  11971. var doc = me.document;
  11972. me.autoHeightEnabled = true;
  11973. bakOverflow = doc.body.style.overflowY;
  11974. doc.body.style.overflowY = 'hidden';
  11975. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  11976. //ff不给事件算得不对
  11977. setTimeout(function () {
  11978. adjustHeight.call(me);
  11979. }, browser.gecko ? 100 : 0);
  11980. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11981. };
  11982. me.disableAutoHeight = function () {
  11983. me.body.style.overflowY = bakOverflow || '';
  11984. me.removeListener('contentchange', adjustHeight);
  11985. me.removeListener('keyup', adjustHeight);
  11986. me.removeListener('mouseup', adjustHeight);
  11987. me.autoHeightEnabled = false;
  11988. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11989. };
  11990. me.addListener('ready', function () {
  11991. me.enableAutoHeight();
  11992. //trace:1764
  11993. var timer;
  11994. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  11995. clearTimeout(timer);
  11996. timer = setTimeout(function () {
  11997. //trace:3681
  11998. adjustHeight.call(me);
  11999. }, 100);
  12000. });
  12001. });
  12002. };
  12003. ///import core
  12004. ///commands 悬浮工具栏
  12005. ///commandsName AutoFloat,autoFloatEnabled
  12006. ///commandsTitle 悬浮工具栏
  12007. /*
  12008. * modified by chengchao01
  12009. *
  12010. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  12011. */
  12012. UE.plugins['autofloat'] = function() {
  12013. var me = this,
  12014. lang = me.getLang();
  12015. me.setOpt({
  12016. topOffset:0
  12017. });
  12018. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  12019. topOffset = me.options.topOffset;
  12020. //如果不固定toolbar的位置,则直接退出
  12021. if(!optsAutoFloatEnabled){
  12022. return;
  12023. }
  12024. var uiUtils = UE.ui.uiUtils,
  12025. LteIE6 = browser.ie && browser.version <= 6,
  12026. quirks = browser.quirks;
  12027. function checkHasUI(){
  12028. if(!UE.ui){
  12029. alert(lang.autofloatMsg);
  12030. return 0;
  12031. }
  12032. return 1;
  12033. }
  12034. function fixIE6FixedPos(){
  12035. var docStyle = document.body.style;
  12036. docStyle.backgroundImage = 'url("about:blank")';
  12037. docStyle.backgroundAttachment = 'fixed';
  12038. }
  12039. var bakCssText,
  12040. placeHolder = document.createElement('div'),
  12041. toolbarBox,orgTop,
  12042. getPosition,
  12043. flag =true; //ie7模式下需要偏移
  12044. function setFloating(){
  12045. var toobarBoxPos = domUtils.getXY(toolbarBox),
  12046. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  12047. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  12048. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  12049. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  12050. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  12051. if (LteIE6 || (quirks && browser.ie)) {
  12052. if(toolbarBox.style.position != 'absolute'){
  12053. toolbarBox.style.position = 'absolute';
  12054. }
  12055. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  12056. } else {
  12057. if (browser.ie7Compat && flag) {
  12058. flag = false;
  12059. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  12060. }
  12061. if(toolbarBox.style.position != 'fixed'){
  12062. toolbarBox.style.position = 'fixed';
  12063. toolbarBox.style.top = topOffset +"px";
  12064. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  12065. }
  12066. }
  12067. }
  12068. function unsetFloating(){
  12069. flag = true;
  12070. if(placeHolder.parentNode){
  12071. placeHolder.parentNode.removeChild(placeHolder);
  12072. }
  12073. toolbarBox.style.cssText = bakCssText;
  12074. }
  12075. function updateFloating(){
  12076. var rect3 = getPosition(me.container);
  12077. var offset=me.options.toolbarTopOffset||0;
  12078. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  12079. setFloating();
  12080. }else{
  12081. unsetFloating();
  12082. }
  12083. }
  12084. var defer_updateFloating = utils.defer(function(){
  12085. updateFloating();
  12086. },browser.ie ? 200 : 100,true);
  12087. me.addListener('destroy',function(){
  12088. domUtils.un(window, ['scroll','resize'], updateFloating);
  12089. me.removeListener('keydown', defer_updateFloating);
  12090. });
  12091. me.addListener('ready', function(){
  12092. if(checkHasUI(me)){
  12093. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  12094. if(!me.ui){
  12095. return;
  12096. }
  12097. getPosition = uiUtils.getClientRect;
  12098. toolbarBox = me.ui.getDom('toolbarbox');
  12099. orgTop = getPosition(toolbarBox).top;
  12100. bakCssText = toolbarBox.style.cssText;
  12101. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  12102. if(LteIE6){
  12103. fixIE6FixedPos();
  12104. }
  12105. domUtils.on(window, ['scroll','resize'], updateFloating);
  12106. me.addListener('keydown', defer_updateFloating);
  12107. me.addListener('beforefullscreenchange', function (t, enabled){
  12108. if (enabled) {
  12109. unsetFloating();
  12110. }
  12111. });
  12112. me.addListener('fullscreenchanged', function (t, enabled){
  12113. if (!enabled) {
  12114. updateFloating();
  12115. }
  12116. });
  12117. me.addListener('sourcemodechanged', function (t, enabled){
  12118. setTimeout(function (){
  12119. updateFloating();
  12120. },0);
  12121. });
  12122. me.addListener("clearDoc",function(){
  12123. setTimeout(function(){
  12124. updateFloating();
  12125. },0);
  12126. })
  12127. }
  12128. });
  12129. };
  12130. /**
  12131. * 纯文本粘贴插件
  12132. * @file
  12133. * @since 1.2.6.1
  12134. */
  12135. UE.plugins['pasteplain'] = function(){
  12136. var me = this;
  12137. me.setOpt({
  12138. 'pasteplain':false,
  12139. 'filterTxtRules' : function(){
  12140. function transP(node){
  12141. node.tagName = 'p';
  12142. node.setStyle();
  12143. }
  12144. function removeNode(node){
  12145. node.parentNode.removeChild(node,true)
  12146. }
  12147. return {
  12148. //直接删除及其字节点内容
  12149. '-' : 'script style object iframe embed input select',
  12150. 'p': {$:{}},
  12151. 'br':{$:{}},
  12152. div: function (node) {
  12153. var tmpNode, p = UE.uNode.createElement('p');
  12154. while (tmpNode = node.firstChild()) {
  12155. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  12156. p.appendChild(tmpNode);
  12157. } else {
  12158. if (p.firstChild()) {
  12159. node.parentNode.insertBefore(p, node);
  12160. p = UE.uNode.createElement('p');
  12161. } else {
  12162. node.parentNode.insertBefore(tmpNode, node);
  12163. }
  12164. }
  12165. }
  12166. if (p.firstChild()) {
  12167. node.parentNode.insertBefore(p, node);
  12168. }
  12169. node.parentNode.removeChild(node);
  12170. },
  12171. ol: removeNode,
  12172. ul: removeNode,
  12173. dl:removeNode,
  12174. dt:removeNode,
  12175. dd:removeNode,
  12176. 'li':removeNode,
  12177. 'caption':transP,
  12178. 'th':transP,
  12179. 'tr':transP,
  12180. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  12181. 'td':function(node){
  12182. //没有内容的td直接删掉
  12183. var txt = !!node.innerText();
  12184. if(txt){
  12185. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  12186. }
  12187. node.parentNode.removeChild(node,node.innerText())
  12188. }
  12189. }
  12190. }()
  12191. });
  12192. //暂时这里支持一下老版本的属性
  12193. var pasteplain = me.options.pasteplain;
  12194. /**
  12195. * 启用或取消纯文本粘贴模式
  12196. * @command pasteplain
  12197. * @method execCommand
  12198. * @param { String } cmd 命令字符串
  12199. * @example
  12200. * ```javascript
  12201. * editor.queryCommandState( 'pasteplain' );
  12202. * ```
  12203. */
  12204. /**
  12205. * 查询当前是否处于纯文本粘贴模式
  12206. * @command pasteplain
  12207. * @method queryCommandState
  12208. * @param { String } cmd 命令字符串
  12209. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  12210. * @example
  12211. * ```javascript
  12212. * editor.queryCommandState( 'pasteplain' );
  12213. * ```
  12214. */
  12215. me.commands['pasteplain'] = {
  12216. queryCommandState: function (){
  12217. return pasteplain ? 1 : 0;
  12218. },
  12219. execCommand: function (){
  12220. pasteplain = !pasteplain|0;
  12221. },
  12222. notNeedUndo : 1
  12223. };
  12224. };
  12225. /**
  12226. * video插件, 为UEditor提供视频插入支持
  12227. * @file
  12228. * @since 1.2.6.1
  12229. */
  12230. UE.plugins['video'] = function (){
  12231. var me =this;
  12232. /*
  12233. * 创建插入视频字符窜
  12234. * @param url 视频地址
  12235. * @param width 视频宽度
  12236. * @param height 视频高度
  12237. * @param align 视频对齐
  12238. * @param toEmbed 是否以flash代替显示
  12239. * @param addParagraph 是否需要添加P 标签
  12240. */
  12241. function creatInsertStr(url,width,height,id,align,classname,type){
  12242. var str;
  12243. switch (type){
  12244. case 'image':
  12245. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname + '"' +
  12246. ' 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 + ';': '')+'" />'
  12247. break;
  12248. case 'embed':
  12249. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  12250. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  12251. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  12252. break;
  12253. case 'video':
  12254. var ext = url.substr(url.lastIndexOf('.') + 1);
  12255. if(ext == 'ogv') ext = 'ogg';
  12256. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + '" ' + (align ? ' style="float:' + align + '"': '') +
  12257. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  12258. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  12259. break;
  12260. }
  12261. return str;
  12262. }
  12263. function switchImgAndVideo(root,img2video){
  12264. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  12265. var className = node.getAttr('class');
  12266. if(className && className.indexOf('edui-faked-video') != -1){
  12267. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  12268. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  12269. }
  12270. if(className && className.indexOf('edui-upload-video') != -1){
  12271. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  12272. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  12273. }
  12274. })
  12275. }
  12276. me.addOutputRule(function(root){
  12277. switchImgAndVideo(root,true)
  12278. });
  12279. me.addInputRule(function(root){
  12280. switchImgAndVideo(root)
  12281. });
  12282. /**
  12283. * 插入视频
  12284. * @command insertvideo
  12285. * @method execCommand
  12286. * @param { String } cmd 命令字符串
  12287. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  12288. * @example
  12289. * ```javascript
  12290. *
  12291. * var videoAttr = {
  12292. * //视频地址
  12293. * url: 'http://www.youku.com/xxx',
  12294. * //视频宽高值, 单位px
  12295. * width: 200,
  12296. * height: 100
  12297. * };
  12298. *
  12299. * //editor 是编辑器实例
  12300. * //向编辑器插入单个视频
  12301. * editor.execCommand( 'insertvideo', videoAttr );
  12302. * ```
  12303. */
  12304. /**
  12305. * 插入视频
  12306. * @command insertvideo
  12307. * @method execCommand
  12308. * @param { String } cmd 命令字符串
  12309. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  12310. * @example
  12311. * ```javascript
  12312. *
  12313. * var videoAttr1 = {
  12314. * //视频地址
  12315. * url: 'http://www.youku.com/xxx',
  12316. * //视频宽高值, 单位px
  12317. * width: 200,
  12318. * height: 100
  12319. * },
  12320. * videoAttr2 = {
  12321. * //视频地址
  12322. * url: 'http://www.youku.com/xxx',
  12323. * //视频宽高值, 单位px
  12324. * width: 200,
  12325. * height: 100
  12326. * }
  12327. *
  12328. * //editor 是编辑器实例
  12329. * //该方法将会向编辑器内插入两个视频
  12330. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  12331. * ```
  12332. */
  12333. /**
  12334. * 查询当前光标所在处是否是一个视频
  12335. * @command insertvideo
  12336. * @method queryCommandState
  12337. * @param { String } cmd 需要查询的命令字符串
  12338. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  12339. * @example
  12340. * ```javascript
  12341. *
  12342. * //editor 是编辑器实例
  12343. * editor.queryCommandState( 'insertvideo' );
  12344. * ```
  12345. */
  12346. me.commands["insertvideo"] = {
  12347. execCommand: function (cmd, videoObjs, type){
  12348. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  12349. var html = [],id = 'tmpVedio', cl;
  12350. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  12351. vi = videoObjs[i];
  12352. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  12353. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  12354. }
  12355. me.execCommand("inserthtml",html.join(""),true);
  12356. var rng = this.selection.getRange();
  12357. for(var i= 0,len=videoObjs.length;i<len;i++){
  12358. var img = this.document.getElementById('tmpVedio'+i);
  12359. domUtils.removeAttributes(img,'id');
  12360. rng.selectNode(img).select();
  12361. me.execCommand('imagefloat',videoObjs[i].align)
  12362. }
  12363. },
  12364. queryCommandState : function(){
  12365. var img = me.selection.getRange().getClosedNode(),
  12366. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  12367. return flag ? 1 : 0;
  12368. }
  12369. };
  12370. };
  12371. /**
  12372. * Created with JetBrains WebStorm.
  12373. * User: taoqili
  12374. * Date: 13-1-18
  12375. * Time: 上午11:09
  12376. * To change this template use File | Settings | File Templates.
  12377. */
  12378. /**
  12379. * UE表格操作类
  12380. * @param table
  12381. * @constructor
  12382. */
  12383. (function () {
  12384. var UETable = UE.UETable = function (table) {
  12385. this.table = table;
  12386. this.indexTable = [];
  12387. this.selectedTds = [];
  12388. this.cellsRange = {};
  12389. this.update(table);
  12390. };
  12391. //===以下为静态工具方法===
  12392. UETable.removeSelectedClass = function (cells) {
  12393. utils.each(cells, function (cell) {
  12394. domUtils.removeClasses(cell, "selectTdClass");
  12395. })
  12396. };
  12397. UETable.addSelectedClass = function (cells) {
  12398. utils.each(cells, function (cell) {
  12399. domUtils.addClass(cell, "selectTdClass");
  12400. })
  12401. };
  12402. UETable.isEmptyBlock = function (node) {
  12403. var reg = new RegExp(domUtils.fillChar, 'g');
  12404. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  12405. return 0;
  12406. }
  12407. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  12408. if (node.getElementsByTagName(i).length) {
  12409. return 0;
  12410. }
  12411. }
  12412. return 1;
  12413. };
  12414. UETable.getWidth = function (cell) {
  12415. if (!cell)return 0;
  12416. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  12417. };
  12418. /**
  12419. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  12420. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  12421. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  12422. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  12423. */
  12424. UETable.getTableCellAlignState = function ( cells ) {
  12425. !utils.isArray( cells ) && ( cells = [cells] );
  12426. var result = {},
  12427. status = ['align', 'valign'],
  12428. tempStatus = null,
  12429. isSame = true;//状态是否相同
  12430. utils.each( cells, function( cellNode ){
  12431. utils.each( status, function( currentState ){
  12432. tempStatus = cellNode.getAttribute( currentState );
  12433. if( !result[ currentState ] && tempStatus ) {
  12434. result[ currentState ] = tempStatus;
  12435. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  12436. isSame = false;
  12437. return false;
  12438. }
  12439. } );
  12440. return isSame;
  12441. });
  12442. return isSame ? result : null;
  12443. };
  12444. /**
  12445. * 根据当前选区获取相关的table信息
  12446. * @return {Object}
  12447. */
  12448. UETable.getTableItemsByRange = function (editor) {
  12449. var start = editor.selection.getStart();
  12450. //ff下会选中bookmark
  12451. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 ) {
  12452. start = start.nextSibling;
  12453. }
  12454. //在table或者td边缘有可能存在选中tr的情况
  12455. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  12456. tr = cell && cell.parentNode,
  12457. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  12458. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  12459. return {
  12460. cell:cell,
  12461. tr:tr,
  12462. table:table,
  12463. caption:caption
  12464. }
  12465. };
  12466. UETable.getUETableBySelected = function (editor) {
  12467. var table = UETable.getTableItemsByRange(editor).table;
  12468. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  12469. return table.ueTable;
  12470. }
  12471. return null;
  12472. };
  12473. UETable.getDefaultValue = function (editor, table) {
  12474. var borderMap = {
  12475. thin:'0px',
  12476. medium:'1px',
  12477. thick:'2px'
  12478. },
  12479. tableBorder, tdPadding, tdBorder, tmpValue;
  12480. if (!table) {
  12481. table = editor.document.createElement('table');
  12482. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  12483. editor.body.appendChild(table);
  12484. var td = table.getElementsByTagName('td')[0];
  12485. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  12486. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12487. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  12488. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12489. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  12490. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12491. domUtils.remove(table);
  12492. return {
  12493. tableBorder:tableBorder,
  12494. tdPadding:tdPadding,
  12495. tdBorder:tdBorder
  12496. };
  12497. } else {
  12498. td = table.getElementsByTagName('td')[0];
  12499. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  12500. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12501. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  12502. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12503. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  12504. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12505. return {
  12506. tableBorder:tableBorder,
  12507. tdPadding:tdPadding,
  12508. tdBorder:tdBorder
  12509. };
  12510. }
  12511. };
  12512. /**
  12513. * 根据当前点击的td或者table获取索引对象
  12514. * @param tdOrTable
  12515. */
  12516. UETable.getUETable = function (tdOrTable) {
  12517. var tag = tdOrTable.tagName.toLowerCase();
  12518. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  12519. if (!tdOrTable.ueTable) {
  12520. tdOrTable.ueTable = new UETable(tdOrTable);
  12521. }
  12522. return tdOrTable.ueTable;
  12523. };
  12524. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  12525. if (!cell || utils.isString(cell)) {
  12526. return this.table.ownerDocument.createElement(cell || 'td');
  12527. }
  12528. var flag = domUtils.hasClass(cell, "selectTdClass");
  12529. flag && domUtils.removeClasses(cell, "selectTdClass");
  12530. var tmpCell = cell.cloneNode(true);
  12531. if (ignoreMerge) {
  12532. tmpCell.rowSpan = tmpCell.colSpan = 1;
  12533. }
  12534. //去掉宽高
  12535. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  12536. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  12537. tmpCell.style.borderLeftStyle = "";
  12538. tmpCell.style.borderTopStyle = "";
  12539. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  12540. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  12541. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  12542. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  12543. flag && domUtils.addClass(cell, "selectTdClass");
  12544. return tmpCell;
  12545. }
  12546. UETable.prototype = {
  12547. getMaxRows:function () {
  12548. var rows = this.table.rows, maxLen = 1;
  12549. for (var i = 0, row; row = rows[i]; i++) {
  12550. var currentMax = 1;
  12551. for (var j = 0, cj; cj = row.cells[j++];) {
  12552. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  12553. }
  12554. maxLen = Math.max(currentMax + i, maxLen);
  12555. }
  12556. return maxLen;
  12557. },
  12558. /**
  12559. * 获取当前表格的最大列数
  12560. */
  12561. getMaxCols:function () {
  12562. var rows = this.table.rows, maxLen = 0, cellRows = {};
  12563. for (var i = 0, row; row = rows[i]; i++) {
  12564. var cellsNum = 0;
  12565. for (var j = 0, cj; cj = row.cells[j++];) {
  12566. cellsNum += (cj.colSpan || 1);
  12567. if (cj.rowSpan && cj.rowSpan > 1) {
  12568. for (var k = 1; k < cj.rowSpan; k++) {
  12569. if (!cellRows['row_' + (i + k)]) {
  12570. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  12571. } else {
  12572. cellRows['row_' + (i + k)]++
  12573. }
  12574. }
  12575. }
  12576. }
  12577. cellsNum += cellRows['row_' + i] || 0;
  12578. maxLen = Math.max(cellsNum, maxLen);
  12579. }
  12580. return maxLen;
  12581. },
  12582. getCellColIndex:function (cell) {
  12583. },
  12584. /**
  12585. * 获取当前cell旁边的单元格,
  12586. * @param cell
  12587. * @param right
  12588. */
  12589. getHSideCell:function (cell, right) {
  12590. try {
  12591. var cellInfo = this.getCellInfo(cell),
  12592. previewRowIndex, previewColIndex;
  12593. var len = this.selectedTds.length,
  12594. range = this.cellsRange;
  12595. //首行或者首列没有前置单元格
  12596. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12597. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  12598. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12599. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  12600. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  12601. } catch (e) {
  12602. showError(e);
  12603. }
  12604. },
  12605. getTabNextCell:function (cell, preRowIndex) {
  12606. var cellInfo = this.getCellInfo(cell),
  12607. rowIndex = preRowIndex || cellInfo.rowIndex,
  12608. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  12609. nextCell;
  12610. try {
  12611. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  12612. } catch (e) {
  12613. try {
  12614. rowIndex = rowIndex * 1 + 1;
  12615. colIndex = 0;
  12616. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  12617. } catch (e) {
  12618. }
  12619. }
  12620. return nextCell;
  12621. },
  12622. /**
  12623. * 获取视觉上的后置单元格
  12624. * @param cell
  12625. * @param bottom
  12626. */
  12627. getVSideCell:function (cell, bottom, ignoreRange) {
  12628. try {
  12629. var cellInfo = this.getCellInfo(cell),
  12630. nextRowIndex, nextColIndex;
  12631. var len = this.selectedTds.length && !ignoreRange,
  12632. range = this.cellsRange;
  12633. //末行或者末列没有后置单元格
  12634. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12635. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12636. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12637. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12638. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12639. } catch (e) {
  12640. showError(e);
  12641. }
  12642. },
  12643. /**
  12644. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  12645. */
  12646. getSameEndPosCells:function (cell, xOrY) {
  12647. try {
  12648. var flag = (xOrY.toLowerCase() === "x"),
  12649. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  12650. rows = this.table.rows,
  12651. cells = null, returns = [];
  12652. for (var i = 0; i < this.rowsNum; i++) {
  12653. cells = rows[i].cells;
  12654. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  12655. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  12656. //对应行的td已经被上面行rowSpan了
  12657. if (tmpEnd > end && flag) break;
  12658. if (cell == tmpCell || end == tmpEnd) {
  12659. //只获取单一的单元格
  12660. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  12661. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  12662. returns.push(tmpCell);
  12663. }
  12664. if (flag) break;
  12665. }
  12666. }
  12667. }
  12668. return returns;
  12669. } catch (e) {
  12670. showError(e);
  12671. }
  12672. },
  12673. setCellContent:function (cell, content) {
  12674. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  12675. },
  12676. cloneCell:UETable.cloneCell,
  12677. /**
  12678. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  12679. */
  12680. getSameStartPosXCells:function (cell) {
  12681. try {
  12682. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  12683. rows = this.table.rows, cells , returns = [];
  12684. for (var i = 0; i < this.rowsNum; i++) {
  12685. cells = rows[i].cells;
  12686. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  12687. var tmpStart = domUtils.getXY(tmpCell).x;
  12688. if (tmpStart > start) break;
  12689. if (tmpStart == start && tmpCell.colSpan == 1) {
  12690. returns.push(tmpCell);
  12691. break;
  12692. }
  12693. }
  12694. }
  12695. return returns;
  12696. } catch (e) {
  12697. showError(e);
  12698. }
  12699. },
  12700. /**
  12701. * 更新table对应的索引表
  12702. */
  12703. update:function (table) {
  12704. this.table = table || this.table;
  12705. this.selectedTds = [];
  12706. this.cellsRange = {};
  12707. this.indexTable = [];
  12708. var rows = this.table.rows,
  12709. rowsNum = this.getMaxRows(),
  12710. dNum = rowsNum - rows.length,
  12711. colsNum = this.getMaxCols();
  12712. while (dNum--) {
  12713. this.table.insertRow(rows.length);
  12714. }
  12715. this.rowsNum = rowsNum;
  12716. this.colsNum = colsNum;
  12717. for (var i = 0, len = rows.length; i < len; i++) {
  12718. this.indexTable[i] = new Array(colsNum);
  12719. }
  12720. //填充索引表
  12721. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  12722. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  12723. //修正整行被rowSpan时导致的行数计算错误
  12724. if (cell.rowSpan > rowsNum) {
  12725. cell.rowSpan = rowsNum;
  12726. }
  12727. var colIndex = cellIndex,
  12728. rowSpan = cell.rowSpan || 1,
  12729. colSpan = cell.colSpan || 1;
  12730. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  12731. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  12732. for (var j = 0; j < rowSpan; j++) {
  12733. for (var k = 0; k < colSpan; k++) {
  12734. this.indexTable[rowIndex + j][colIndex + k] = {
  12735. rowIndex:rowIndex,
  12736. cellIndex:cellIndex,
  12737. colIndex:colIndex,
  12738. rowSpan:rowSpan,
  12739. colSpan:colSpan
  12740. }
  12741. }
  12742. }
  12743. }
  12744. }
  12745. //修复残缺td
  12746. for (j = 0; j < rowsNum; j++) {
  12747. for (k = 0; k < colsNum; k++) {
  12748. if (this.indexTable[j][k] === undefined) {
  12749. row = rows[j];
  12750. cell = row.cells[row.cells.length - 1];
  12751. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  12752. this.setCellContent(cell);
  12753. if (cell.colSpan !== 1)cell.colSpan = 1;
  12754. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  12755. row.appendChild(cell);
  12756. this.indexTable[j][k] = {
  12757. rowIndex:j,
  12758. cellIndex:cell.cellIndex,
  12759. colIndex:k,
  12760. rowSpan:1,
  12761. colSpan:1
  12762. }
  12763. }
  12764. }
  12765. }
  12766. //当框选后删除行或者列后撤销,需要重建选区。
  12767. var tds = domUtils.getElementsByTagName(this.table, "td"),
  12768. selectTds = [];
  12769. utils.each(tds, function (td) {
  12770. if (domUtils.hasClass(td, "selectTdClass")) {
  12771. selectTds.push(td);
  12772. }
  12773. });
  12774. if (selectTds.length) {
  12775. var start = selectTds[0],
  12776. end = selectTds[selectTds.length - 1],
  12777. startInfo = this.getCellInfo(start),
  12778. endInfo = this.getCellInfo(end);
  12779. this.selectedTds = selectTds;
  12780. this.cellsRange = {
  12781. beginRowIndex:startInfo.rowIndex,
  12782. beginColIndex:startInfo.colIndex,
  12783. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  12784. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  12785. };
  12786. }
  12787. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  12788. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  12789. domUtils.addClass(this.table.rows[0], "firstRow");
  12790. for(var i = 1; i< this.table.rows.length; i++) {
  12791. domUtils.removeClasses(this.table.rows[i], "firstRow");
  12792. }
  12793. }
  12794. },
  12795. /**
  12796. * 获取单元格的索引信息
  12797. */
  12798. getCellInfo:function (cell) {
  12799. if (!cell) return;
  12800. var cellIndex = cell.cellIndex,
  12801. rowIndex = cell.parentNode.rowIndex,
  12802. rowInfo = this.indexTable[rowIndex],
  12803. numCols = this.colsNum;
  12804. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  12805. var cellInfo = rowInfo[colIndex];
  12806. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  12807. return cellInfo;
  12808. }
  12809. }
  12810. },
  12811. /**
  12812. * 根据行列号获取单元格
  12813. */
  12814. getCell:function (rowIndex, cellIndex) {
  12815. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  12816. },
  12817. /**
  12818. * 删除单元格
  12819. */
  12820. deleteCell:function (cell, rowIndex) {
  12821. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  12822. var row = this.table.rows[rowIndex];
  12823. row.deleteCell(cell.cellIndex);
  12824. },
  12825. /**
  12826. * 根据始末两个单元格获取被框选的所有单元格范围
  12827. */
  12828. getCellsRange:function (cellA, cellB) {
  12829. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  12830. var tmpBeginRowIndex = beginRowIndex,
  12831. tmpBeginColIndex = beginColIndex,
  12832. tmpEndRowIndex = endRowIndex,
  12833. tmpEndColIndex = endColIndex,
  12834. cellInfo, colIndex, rowIndex;
  12835. // 通过indexTable检查是否存在超出TableRange上边界的情况
  12836. if (beginRowIndex > 0) {
  12837. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  12838. cellInfo = me.indexTable[beginRowIndex][colIndex];
  12839. rowIndex = cellInfo.rowIndex;
  12840. if (rowIndex < beginRowIndex) {
  12841. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  12842. }
  12843. }
  12844. }
  12845. // 通过indexTable检查是否存在超出TableRange右边界的情况
  12846. if (endColIndex < me.colsNum) {
  12847. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  12848. cellInfo = me.indexTable[rowIndex][endColIndex];
  12849. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  12850. if (colIndex > endColIndex) {
  12851. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  12852. }
  12853. }
  12854. }
  12855. // 检查是否有超出TableRange下边界的情况
  12856. if (endRowIndex < me.rowsNum) {
  12857. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  12858. cellInfo = me.indexTable[endRowIndex][colIndex];
  12859. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  12860. if (rowIndex > endRowIndex) {
  12861. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  12862. }
  12863. }
  12864. }
  12865. // 检查是否有超出TableRange左边界的情况
  12866. if (beginColIndex > 0) {
  12867. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  12868. cellInfo = me.indexTable[rowIndex][beginColIndex];
  12869. colIndex = cellInfo.colIndex;
  12870. if (colIndex < beginColIndex) {
  12871. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  12872. }
  12873. }
  12874. }
  12875. //递归调用直至所有完成所有框选单元格的扩展
  12876. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  12877. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  12878. } else {
  12879. // 不需要扩展TableRange的情况
  12880. return {
  12881. beginRowIndex:beginRowIndex,
  12882. beginColIndex:beginColIndex,
  12883. endRowIndex:endRowIndex,
  12884. endColIndex:endColIndex
  12885. };
  12886. }
  12887. }
  12888. try {
  12889. var me = this,
  12890. cellAInfo = me.getCellInfo(cellA);
  12891. if (cellA === cellB) {
  12892. return {
  12893. beginRowIndex:cellAInfo.rowIndex,
  12894. beginColIndex:cellAInfo.colIndex,
  12895. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  12896. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  12897. };
  12898. }
  12899. var cellBInfo = me.getCellInfo(cellB);
  12900. // 计算TableRange的四个边
  12901. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  12902. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  12903. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  12904. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  12905. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  12906. } catch (e) {
  12907. //throw e;
  12908. }
  12909. },
  12910. /**
  12911. * 依据cellsRange获取对应的单元格集合
  12912. */
  12913. getCells:function (range) {
  12914. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  12915. this.clearSelected();
  12916. var beginRowIndex = range.beginRowIndex,
  12917. beginColIndex = range.beginColIndex,
  12918. endRowIndex = range.endRowIndex,
  12919. endColIndex = range.endColIndex,
  12920. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  12921. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  12922. for (var j = beginColIndex; j <= endColIndex; j++) {
  12923. cellInfo = this.indexTable[i][j];
  12924. rowIndex = cellInfo.rowIndex;
  12925. colIndex = cellInfo.colIndex;
  12926. // 如果Cells里已经包含了此Cell则跳过
  12927. var key = rowIndex + '|' + colIndex;
  12928. if (tdHash[key]) continue;
  12929. tdHash[key] = 1;
  12930. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  12931. return null;
  12932. }
  12933. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  12934. }
  12935. }
  12936. return returnTds;
  12937. },
  12938. /**
  12939. * 清理已经选中的单元格
  12940. */
  12941. clearSelected:function () {
  12942. UETable.removeSelectedClass(this.selectedTds);
  12943. this.selectedTds = [];
  12944. this.cellsRange = {};
  12945. },
  12946. /**
  12947. * 根据range设置已经选中的单元格
  12948. */
  12949. setSelected:function (range) {
  12950. var cells = this.getCells(range);
  12951. UETable.addSelectedClass(cells);
  12952. this.selectedTds = cells;
  12953. this.cellsRange = range;
  12954. },
  12955. isFullRow:function () {
  12956. var range = this.cellsRange;
  12957. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  12958. },
  12959. isFullCol:function () {
  12960. var range = this.cellsRange,
  12961. table = this.table,
  12962. ths = table.getElementsByTagName("th"),
  12963. rows = range.endRowIndex - range.beginRowIndex + 1;
  12964. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  12965. },
  12966. /**
  12967. * 获取视觉上的前置单元格,默认是左边,top传入时
  12968. * @param cell
  12969. * @param top
  12970. */
  12971. getNextCell:function (cell, bottom, ignoreRange) {
  12972. try {
  12973. var cellInfo = this.getCellInfo(cell),
  12974. nextRowIndex, nextColIndex;
  12975. var len = this.selectedTds.length && !ignoreRange,
  12976. range = this.cellsRange;
  12977. //末行或者末列没有后置单元格
  12978. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12979. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12980. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12981. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12982. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12983. } catch (e) {
  12984. showError(e);
  12985. }
  12986. },
  12987. getPreviewCell:function (cell, top) {
  12988. try {
  12989. var cellInfo = this.getCellInfo(cell),
  12990. previewRowIndex, previewColIndex;
  12991. var len = this.selectedTds.length,
  12992. range = this.cellsRange;
  12993. //首行或者首列没有前置单元格
  12994. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12995. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  12996. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  12997. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12998. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  12999. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  13000. } catch (e) {
  13001. showError(e);
  13002. }
  13003. },
  13004. /**
  13005. * 移动单元格中的内容
  13006. */
  13007. moveContent:function (cellTo, cellFrom) {
  13008. if (UETable.isEmptyBlock(cellFrom)) return;
  13009. if (UETable.isEmptyBlock(cellTo)) {
  13010. cellTo.innerHTML = cellFrom.innerHTML;
  13011. return;
  13012. }
  13013. var child = cellTo.lastChild;
  13014. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  13015. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  13016. }
  13017. while (child = cellFrom.firstChild) {
  13018. cellTo.appendChild(child);
  13019. }
  13020. },
  13021. /**
  13022. * 向右合并单元格
  13023. */
  13024. mergeRight:function (cell) {
  13025. var cellInfo = this.getCellInfo(cell),
  13026. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  13027. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  13028. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  13029. //合并
  13030. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  13031. //被合并的单元格不应存在宽度属性
  13032. cell.removeAttribute("width");
  13033. //移动内容
  13034. this.moveContent(cell, rightCell);
  13035. //删掉被合并的Cell
  13036. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  13037. this.update();
  13038. },
  13039. /**
  13040. * 向下合并单元格
  13041. */
  13042. mergeDown:function (cell) {
  13043. var cellInfo = this.getCellInfo(cell),
  13044. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  13045. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  13046. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  13047. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  13048. cell.removeAttribute("height");
  13049. this.moveContent(cell, downCell);
  13050. this.deleteCell(downCell, downCellInfo.rowIndex);
  13051. this.update();
  13052. },
  13053. /**
  13054. * 合并整个range中的内容
  13055. */
  13056. mergeRange:function () {
  13057. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  13058. var range = this.cellsRange,
  13059. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  13060. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  13061. var index = this.indexTable,
  13062. info = this.getCellInfo(leftTopCell);
  13063. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  13064. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  13065. }
  13066. // 删除剩余的Cells
  13067. var cells = this.getCells(range);
  13068. for(var i= 0,ci;ci=cells[i++];){
  13069. if (ci !== leftTopCell) {
  13070. this.moveContent(leftTopCell, ci);
  13071. this.deleteCell(ci);
  13072. }
  13073. }
  13074. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  13075. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  13076. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  13077. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  13078. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  13079. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  13080. leftTopCell.colSpan = 1;
  13081. }
  13082. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  13083. var rowIndex = leftTopCell.parentNode.rowIndex;
  13084. //解决IE下的表格操作问题
  13085. if( this.table.deleteRow ) {
  13086. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  13087. this.table.deleteRow(curIndex);
  13088. }
  13089. } else {
  13090. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  13091. var row = this.table.rows[rowIndex + 1];
  13092. row.parentNode.removeChild(row);
  13093. }
  13094. }
  13095. leftTopCell.rowSpan = 1;
  13096. }
  13097. this.update();
  13098. },
  13099. /**
  13100. * 插入一行单元格
  13101. */
  13102. insertRow:function (rowIndex, sourceCell) {
  13103. var numCols = this.colsNum,
  13104. table = this.table,
  13105. row = table.insertRow(rowIndex), cell,
  13106. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  13107. function replaceTdToTh(colIndex, cell, tableRow) {
  13108. if (colIndex == 0) {
  13109. var tr = tableRow.nextSibling || tableRow.previousSibling,
  13110. th = tr.cells[colIndex];
  13111. if (th.tagName == 'TH') {
  13112. th = cell.ownerDocument.createElement("th");
  13113. th.appendChild(cell.firstChild);
  13114. tableRow.insertBefore(th, cell);
  13115. domUtils.remove(cell)
  13116. }
  13117. }else{
  13118. if (cell.tagName == 'TH') {
  13119. var td = cell.ownerDocument.createElement("td");
  13120. td.appendChild(cell.firstChild);
  13121. tableRow.insertBefore(td, cell);
  13122. domUtils.remove(cell)
  13123. }
  13124. }
  13125. }
  13126. //首行直接插入,无需考虑部分单元格被rowspan的情况
  13127. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  13128. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  13129. cell = this.cloneCell(sourceCell, true);
  13130. this.setCellContent(cell);
  13131. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13132. row.appendChild(cell);
  13133. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  13134. }
  13135. } else {
  13136. var infoRow = this.indexTable[rowIndex],
  13137. cellIndex = 0;
  13138. for (colIndex = 0; colIndex < numCols; colIndex++) {
  13139. var cellInfo = infoRow[colIndex];
  13140. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  13141. if (cellInfo.rowIndex < rowIndex) {
  13142. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  13143. cell.rowSpan = cellInfo.rowSpan + 1;
  13144. } else {
  13145. cell = this.cloneCell(sourceCell, true);
  13146. this.setCellContent(cell);
  13147. row.appendChild(cell);
  13148. }
  13149. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  13150. }
  13151. }
  13152. //框选时插入不触发contentchange,需要手动更新索引。
  13153. this.update();
  13154. return row;
  13155. },
  13156. /**
  13157. * 删除一行单元格
  13158. * @param rowIndex
  13159. */
  13160. deleteRow:function (rowIndex) {
  13161. var row = this.table.rows[rowIndex],
  13162. infoRow = this.indexTable[rowIndex],
  13163. colsNum = this.colsNum,
  13164. count = 0; //处理计数
  13165. for (var colIndex = 0; colIndex < colsNum;) {
  13166. var cellInfo = infoRow[colIndex],
  13167. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  13168. if (cell.rowSpan > 1) {
  13169. if (cellInfo.rowIndex == rowIndex) {
  13170. var clone = cell.cloneNode(true);
  13171. clone.rowSpan = cell.rowSpan - 1;
  13172. clone.innerHTML = "";
  13173. cell.rowSpan = 1;
  13174. var nextRowIndex = rowIndex + 1,
  13175. nextRow = this.table.rows[nextRowIndex],
  13176. insertCellIndex,
  13177. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  13178. if (preMerged < colIndex) {
  13179. insertCellIndex = colIndex - preMerged - 1;
  13180. //nextRow.insertCell(insertCellIndex);
  13181. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  13182. } else {
  13183. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  13184. }
  13185. count += 1;
  13186. //cell.parentNode.removeChild(cell);
  13187. }
  13188. }
  13189. colIndex += cell.colSpan || 1;
  13190. }
  13191. var deleteTds = [], cacheMap = {};
  13192. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  13193. var tmpRowIndex = infoRow[colIndex].rowIndex,
  13194. tmpCellIndex = infoRow[colIndex].cellIndex,
  13195. key = tmpRowIndex + "_" + tmpCellIndex;
  13196. if (cacheMap[key])continue;
  13197. cacheMap[key] = 1;
  13198. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  13199. deleteTds.push(cell);
  13200. }
  13201. var mergeTds = [];
  13202. utils.each(deleteTds, function (td) {
  13203. if (td.rowSpan == 1) {
  13204. td.parentNode.removeChild(td);
  13205. } else {
  13206. mergeTds.push(td);
  13207. }
  13208. });
  13209. utils.each(mergeTds, function (td) {
  13210. td.rowSpan--;
  13211. });
  13212. row.parentNode.removeChild(row);
  13213. //浏览器方法本身存在bug,采用自定义方法删除
  13214. //this.table.deleteRow(rowIndex);
  13215. this.update();
  13216. },
  13217. insertCol:function (colIndex, sourceCell, defaultValue) {
  13218. var rowsNum = this.rowsNum,
  13219. rowIndex = 0,
  13220. tableRow, cell,
  13221. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  13222. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  13223. function replaceTdToTh(rowIndex, cell, tableRow) {
  13224. if (rowIndex == 0) {
  13225. var th = cell.nextSibling || cell.previousSibling;
  13226. if (th.tagName == 'TH') {
  13227. th = cell.ownerDocument.createElement("th");
  13228. th.appendChild(cell.firstChild);
  13229. tableRow.insertBefore(th, cell);
  13230. domUtils.remove(cell)
  13231. }
  13232. }else{
  13233. if (cell.tagName == 'TH') {
  13234. var td = cell.ownerDocument.createElement("td");
  13235. td.appendChild(cell.firstChild);
  13236. tableRow.insertBefore(td, cell);
  13237. domUtils.remove(cell)
  13238. }
  13239. }
  13240. }
  13241. var preCell;
  13242. if (colIndex == 0 || colIndex == this.colsNum) {
  13243. for (; rowIndex < rowsNum; rowIndex++) {
  13244. tableRow = this.table.rows[rowIndex];
  13245. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  13246. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  13247. this.setCellContent(cell);
  13248. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13249. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  13250. if (!colIndex) {
  13251. tableRow.insertBefore(cell, tableRow.cells[0]);
  13252. } else {
  13253. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  13254. }
  13255. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  13256. }
  13257. } else {
  13258. for (; rowIndex < rowsNum; rowIndex++) {
  13259. var cellInfo = this.indexTable[rowIndex][colIndex];
  13260. if (cellInfo.colIndex < colIndex) {
  13261. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  13262. cell.colSpan = cellInfo.colSpan + 1;
  13263. } else {
  13264. tableRow = this.table.rows[rowIndex];
  13265. preCell = tableRow.cells[cellInfo.cellIndex];
  13266. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  13267. this.setCellContent(cell);
  13268. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13269. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  13270. //防止IE下报错
  13271. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  13272. }
  13273. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  13274. }
  13275. }
  13276. //框选时插入不触发contentchange,需要手动更新索引
  13277. this.update();
  13278. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  13279. },
  13280. updateWidth:function (width, defaultValue) {
  13281. var table = this.table,
  13282. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  13283. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  13284. table.setAttribute("width", tmpWidth);
  13285. return;
  13286. }
  13287. var tds = domUtils.getElementsByTagName(this.table, "td th");
  13288. utils.each(tds, function (td) {
  13289. td.setAttribute("width", width);
  13290. })
  13291. },
  13292. deleteCol:function (colIndex) {
  13293. var indexTable = this.indexTable,
  13294. tableRows = this.table.rows,
  13295. backTableWidth = this.table.getAttribute("width"),
  13296. backTdWidth = 0,
  13297. rowsNum = this.rowsNum,
  13298. cacheMap = {};
  13299. for (var rowIndex = 0; rowIndex < rowsNum;) {
  13300. var infoRow = indexTable[rowIndex],
  13301. cellInfo = infoRow[colIndex],
  13302. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  13303. // 跳过已经处理过的Cell
  13304. if (cacheMap[key])continue;
  13305. cacheMap[key] = 1;
  13306. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  13307. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  13308. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  13309. if (cell.colSpan > 1) {
  13310. cell.colSpan--;
  13311. } else {
  13312. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  13313. }
  13314. rowIndex += cellInfo.rowSpan || 1;
  13315. }
  13316. this.table.setAttribute("width", backTableWidth - backTdWidth);
  13317. this.update();
  13318. },
  13319. splitToCells:function (cell) {
  13320. var me = this,
  13321. cells = this.splitToRows(cell);
  13322. utils.each(cells, function (cell) {
  13323. me.splitToCols(cell);
  13324. })
  13325. },
  13326. splitToRows:function (cell) {
  13327. var cellInfo = this.getCellInfo(cell),
  13328. rowIndex = cellInfo.rowIndex,
  13329. colIndex = cellInfo.colIndex,
  13330. results = [];
  13331. // 修改Cell的rowSpan
  13332. cell.rowSpan = 1;
  13333. results.push(cell);
  13334. // 补齐单元格
  13335. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  13336. if (i == rowIndex)continue;
  13337. var tableRow = this.table.rows[i],
  13338. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  13339. tmpCell.colSpan = cellInfo.colSpan;
  13340. this.setCellContent(tmpCell);
  13341. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13342. tmpCell.setAttribute('align', cell.getAttribute('align'));
  13343. if (cell.style.cssText) {
  13344. tmpCell.style.cssText = cell.style.cssText;
  13345. }
  13346. results.push(tmpCell);
  13347. }
  13348. this.update();
  13349. return results;
  13350. },
  13351. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  13352. var indexRow = this.indexTable[rowIndex],
  13353. num = 0;
  13354. for (var i = 0; i < colIndex;) {
  13355. var colSpan = indexRow[i].colSpan,
  13356. tmpRowIndex = indexRow[i].rowIndex;
  13357. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  13358. i += colSpan;
  13359. }
  13360. return num;
  13361. },
  13362. splitToCols:function (cell) {
  13363. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  13364. cellInfo = this.getCellInfo(cell),
  13365. rowIndex = cellInfo.rowIndex,
  13366. colIndex = cellInfo.colIndex,
  13367. results = [];
  13368. // 修改Cell的rowSpan
  13369. cell.colSpan = 1;
  13370. cell.setAttribute("width", backWidth);
  13371. results.push(cell);
  13372. // 补齐单元格
  13373. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  13374. if (j == colIndex)continue;
  13375. var tableRow = this.table.rows[rowIndex],
  13376. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  13377. tmpCell.rowSpan = cellInfo.rowSpan;
  13378. this.setCellContent(tmpCell);
  13379. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13380. tmpCell.setAttribute('align', cell.getAttribute('align'));
  13381. tmpCell.setAttribute('width', backWidth);
  13382. if (cell.style.cssText) {
  13383. tmpCell.style.cssText = cell.style.cssText;
  13384. }
  13385. //处理th的情况
  13386. if (cell.tagName == 'TH') {
  13387. var th = cell.ownerDocument.createElement('th');
  13388. th.appendChild(tmpCell.firstChild);
  13389. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13390. th.rowSpan = tmpCell.rowSpan;
  13391. tableRow.insertBefore(th, tmpCell);
  13392. domUtils.remove(tmpCell);
  13393. }
  13394. results.push(tmpCell);
  13395. }
  13396. this.update();
  13397. return results;
  13398. },
  13399. isLastCell:function (cell, rowsNum, colsNum) {
  13400. rowsNum = rowsNum || this.rowsNum;
  13401. colsNum = colsNum || this.colsNum;
  13402. var cellInfo = this.getCellInfo(cell);
  13403. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  13404. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  13405. },
  13406. getLastCell:function (cells) {
  13407. cells = cells || this.table.getElementsByTagName("td");
  13408. var firstInfo = this.getCellInfo(cells[0]);
  13409. var me = this, last = cells[0],
  13410. tr = last.parentNode,
  13411. cellsNum = 0, cols = 0, rows;
  13412. utils.each(cells, function (cell) {
  13413. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  13414. cellsNum += cell.rowSpan * cell.colSpan || 1;
  13415. });
  13416. rows = cellsNum / cols;
  13417. utils.each(cells, function (cell) {
  13418. if (me.isLastCell(cell, rows, cols)) {
  13419. last = cell;
  13420. return false;
  13421. }
  13422. });
  13423. return last;
  13424. },
  13425. selectRow:function (rowIndex) {
  13426. var indexRow = this.indexTable[rowIndex],
  13427. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  13428. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  13429. range = this.getCellsRange(start, end);
  13430. this.setSelected(range);
  13431. },
  13432. selectTable:function () {
  13433. var tds = this.table.getElementsByTagName("td"),
  13434. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  13435. this.setSelected(range);
  13436. },
  13437. setBackground:function (cells, value) {
  13438. if (typeof value === "string") {
  13439. utils.each(cells, function (cell) {
  13440. cell.style.backgroundColor = value;
  13441. })
  13442. } else if (typeof value === "object") {
  13443. value = utils.extend({
  13444. repeat:true,
  13445. colorList:["#ddd", "#fff"]
  13446. }, value);
  13447. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  13448. count = 0,
  13449. colors = value.colorList,
  13450. getColor = function (list, index, repeat) {
  13451. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  13452. };
  13453. for (var i = 0, cell; cell = cells[i++];) {
  13454. var cellInfo = this.getCellInfo(cell);
  13455. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  13456. }
  13457. }
  13458. },
  13459. removeBackground:function (cells) {
  13460. utils.each(cells, function (cell) {
  13461. cell.style.backgroundColor = "";
  13462. })
  13463. }
  13464. };
  13465. function showError(e) {
  13466. }
  13467. })();
  13468. /**
  13469. * Created with JetBrains PhpStorm.
  13470. * User: taoqili
  13471. * Date: 13-2-20
  13472. * Time: 下午6:25
  13473. * To change this template use File | Settings | File Templates.
  13474. */
  13475. ;
  13476. (function () {
  13477. var UT = UE.UETable,
  13478. getTableItemsByRange = function (editor) {
  13479. return UT.getTableItemsByRange(editor);
  13480. },
  13481. getUETableBySelected = function (editor) {
  13482. return UT.getUETableBySelected(editor)
  13483. },
  13484. getDefaultValue = function (editor, table) {
  13485. return UT.getDefaultValue(editor, table);
  13486. },
  13487. getUETable = function (tdOrTable) {
  13488. return UT.getUETable(tdOrTable);
  13489. };
  13490. UE.commands['inserttable'] = {
  13491. queryCommandState: function () {
  13492. return getTableItemsByRange(this).table ? -1 : 0;
  13493. },
  13494. execCommand: function (cmd, opt) {
  13495. function createTable(opt, tdWidth) {
  13496. var html = [],
  13497. rowsNum = opt.numRows,
  13498. colsNum = opt.numCols;
  13499. for (var r = 0; r < rowsNum; r++) {
  13500. html.push('<tr>');
  13501. for (var c = 0; c < colsNum; c++) {
  13502. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  13503. }
  13504. html.push('</tr>')
  13505. }
  13506. //禁止指定table-width
  13507. return '<table><tbody>' + html.join('') + '</tbody></table>'
  13508. }
  13509. if (!opt) {
  13510. opt = utils.extend({}, {
  13511. numCols: this.options.defaultCols,
  13512. numRows: this.options.defaultRows,
  13513. tdvalign: this.options.tdvalign
  13514. })
  13515. }
  13516. var me = this;
  13517. var range = this.selection.getRange(),
  13518. start = range.startContainer,
  13519. firstParentBlock = domUtils.findParent(start, function (node) {
  13520. return domUtils.isBlockElm(node);
  13521. }, true) || me.body;
  13522. var defaultValue = getDefaultValue(me),
  13523. tableWidth = firstParentBlock.offsetWidth,
  13524. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  13525. //todo其他属性
  13526. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  13527. me.execCommand("inserthtml", createTable(opt, tdWidth));
  13528. }
  13529. };
  13530. UE.commands['insertparagraphbeforetable'] = {
  13531. queryCommandState: function () {
  13532. return getTableItemsByRange(this).cell ? 0 : -1;
  13533. },
  13534. execCommand: function () {
  13535. var table = getTableItemsByRange(this).table;
  13536. if (table) {
  13537. var p = this.document.createElement("p");
  13538. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  13539. table.parentNode.insertBefore(p, table);
  13540. this.selection.getRange().setStart(p, 0).setCursor();
  13541. }
  13542. }
  13543. };
  13544. UE.commands['deletetable'] = {
  13545. queryCommandState: function () {
  13546. var rng = this.selection.getRange();
  13547. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  13548. },
  13549. execCommand: function (cmd, table) {
  13550. var rng = this.selection.getRange();
  13551. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  13552. if (table) {
  13553. var next = table.nextSibling;
  13554. if (!next) {
  13555. next = domUtils.createElement(this.document, 'p', {
  13556. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  13557. });
  13558. table.parentNode.insertBefore(next, table);
  13559. }
  13560. domUtils.remove(table);
  13561. rng = this.selection.getRange();
  13562. if (next.nodeType == 3) {
  13563. rng.setStartBefore(next)
  13564. } else {
  13565. rng.setStart(next, 0)
  13566. }
  13567. rng.setCursor(false, true)
  13568. this.fireEvent("tablehasdeleted")
  13569. }
  13570. }
  13571. };
  13572. UE.commands['cellalign'] = {
  13573. queryCommandState: function () {
  13574. return getSelectedArr(this).length ? 0 : -1
  13575. },
  13576. execCommand: function (cmd, align) {
  13577. var selectedTds = getSelectedArr(this);
  13578. if (selectedTds.length) {
  13579. for (var i = 0, ci; ci = selectedTds[i++];) {
  13580. ci.setAttribute('align', align);
  13581. }
  13582. }
  13583. }
  13584. };
  13585. UE.commands['cellvalign'] = {
  13586. queryCommandState: function () {
  13587. return getSelectedArr(this).length ? 0 : -1;
  13588. },
  13589. execCommand: function (cmd, valign) {
  13590. var selectedTds = getSelectedArr(this);
  13591. if (selectedTds.length) {
  13592. for (var i = 0, ci; ci = selectedTds[i++];) {
  13593. ci.setAttribute('vAlign', valign);
  13594. }
  13595. }
  13596. }
  13597. };
  13598. UE.commands['insertcaption'] = {
  13599. queryCommandState: function () {
  13600. var table = getTableItemsByRange(this).table;
  13601. if (table) {
  13602. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  13603. }
  13604. return -1;
  13605. },
  13606. execCommand: function () {
  13607. var table = getTableItemsByRange(this).table;
  13608. if (table) {
  13609. var caption = this.document.createElement('caption');
  13610. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  13611. table.insertBefore(caption, table.firstChild);
  13612. var range = this.selection.getRange();
  13613. range.setStart(caption, 0).setCursor();
  13614. }
  13615. }
  13616. };
  13617. UE.commands['deletecaption'] = {
  13618. queryCommandState: function () {
  13619. var rng = this.selection.getRange(),
  13620. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13621. if (table) {
  13622. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  13623. }
  13624. return -1;
  13625. },
  13626. execCommand: function () {
  13627. var rng = this.selection.getRange(),
  13628. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13629. if (table) {
  13630. domUtils.remove(table.getElementsByTagName('caption')[0]);
  13631. var range = this.selection.getRange();
  13632. range.setStart(table.rows[0].cells[0], 0).setCursor();
  13633. }
  13634. }
  13635. };
  13636. UE.commands['inserttitle'] = {
  13637. queryCommandState: function () {
  13638. var table = getTableItemsByRange(this).table;
  13639. if (table) {
  13640. var firstRow = table.rows[0];
  13641. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  13642. }
  13643. return -1;
  13644. },
  13645. execCommand: function () {
  13646. var table = getTableItemsByRange(this).table;
  13647. if (table) {
  13648. getUETable(table).insertRow(0, 'th');
  13649. }
  13650. var th = table.getElementsByTagName('th')[0];
  13651. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  13652. }
  13653. };
  13654. UE.commands['deletetitle'] = {
  13655. queryCommandState: function () {
  13656. var table = getTableItemsByRange(this).table;
  13657. if (table) {
  13658. var firstRow = table.rows[0];
  13659. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  13660. }
  13661. return -1;
  13662. },
  13663. execCommand: function () {
  13664. var table = getTableItemsByRange(this).table;
  13665. if (table) {
  13666. domUtils.remove(table.rows[0])
  13667. }
  13668. var td = table.getElementsByTagName('td')[0];
  13669. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  13670. }
  13671. };
  13672. UE.commands['inserttitlecol'] = {
  13673. queryCommandState: function () {
  13674. var table = getTableItemsByRange(this).table;
  13675. if (table) {
  13676. var lastRow = table.rows[table.rows.length-1];
  13677. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  13678. }
  13679. return -1;
  13680. },
  13681. execCommand: function (cmd) {
  13682. var table = getTableItemsByRange(this).table;
  13683. if (table) {
  13684. getUETable(table).insertCol(0, 'th');
  13685. }
  13686. resetTdWidth(table, this);
  13687. var th = table.getElementsByTagName('th')[0];
  13688. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  13689. }
  13690. };
  13691. UE.commands['deletetitlecol'] = {
  13692. queryCommandState: function () {
  13693. var table = getTableItemsByRange(this).table;
  13694. if (table) {
  13695. var lastRow = table.rows[table.rows.length-1];
  13696. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  13697. }
  13698. return -1;
  13699. },
  13700. execCommand: function () {
  13701. var table = getTableItemsByRange(this).table;
  13702. if (table) {
  13703. for(var i = 0; i< table.rows.length; i++ ){
  13704. domUtils.remove(table.rows[i].children[0])
  13705. }
  13706. }
  13707. resetTdWidth(table, this);
  13708. var td = table.getElementsByTagName('td')[0];
  13709. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  13710. }
  13711. };
  13712. UE.commands["mergeright"] = {
  13713. queryCommandState: function (cmd) {
  13714. var tableItems = getTableItemsByRange(this);
  13715. if (!tableItems.cell) return -1;
  13716. var ut = getUETable(tableItems.table);
  13717. if (ut.selectedTds.length) return -1;
  13718. var cellInfo = ut.getCellInfo(tableItems.cell),
  13719. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  13720. if (rightColIndex >= ut.colsNum) return -1;
  13721. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  13722. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  13723. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  13724. },
  13725. execCommand: function (cmd) {
  13726. var rng = this.selection.getRange(),
  13727. bk = rng.createBookmark(true);
  13728. var cell = getTableItemsByRange(this).cell,
  13729. ut = getUETable(cell);
  13730. ut.mergeRight(cell);
  13731. rng.moveToBookmark(bk).select();
  13732. }
  13733. };
  13734. UE.commands["mergedown"] = {
  13735. queryCommandState: function (cmd) {
  13736. var tableItems = getTableItemsByRange(this),
  13737. cell = tableItems.cell;
  13738. if (!cell || cell.tagName == "TH") return -1;
  13739. var ut = getUETable(tableItems.table);
  13740. if (ut.selectedTds.length)return -1;
  13741. var cellInfo = ut.getCellInfo(tableItems.cell),
  13742. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  13743. // 如果处于最下边则不能f向右合并
  13744. if (downRowIndex >= ut.rowsNum) return -1;
  13745. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  13746. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  13747. return (downCellInfo.colIndex == cellInfo.colIndex
  13748. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  13749. },
  13750. execCommand: function () {
  13751. var rng = this.selection.getRange(),
  13752. bk = rng.createBookmark(true);
  13753. var cell = getTableItemsByRange(this).cell,
  13754. ut = getUETable(cell);
  13755. ut.mergeDown(cell);
  13756. rng.moveToBookmark(bk).select();
  13757. }
  13758. };
  13759. UE.commands["mergecells"] = {
  13760. queryCommandState: function () {
  13761. return getUETableBySelected(this) ? 0 : -1;
  13762. },
  13763. execCommand: function () {
  13764. var ut = getUETableBySelected(this);
  13765. if (ut && ut.selectedTds.length) {
  13766. var cell = ut.selectedTds[0];
  13767. ut.mergeRange();
  13768. var rng = this.selection.getRange();
  13769. if (domUtils.isEmptyBlock(cell)) {
  13770. rng.setStart(cell, 0).collapse(true)
  13771. } else {
  13772. rng.selectNodeContents(cell)
  13773. }
  13774. rng.select();
  13775. }
  13776. }
  13777. };
  13778. UE.commands["insertrow"] = {
  13779. queryCommandState: function () {
  13780. var tableItems = getTableItemsByRange(this),
  13781. cell = tableItems.cell;
  13782. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  13783. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  13784. },
  13785. execCommand: function () {
  13786. var rng = this.selection.getRange(),
  13787. bk = rng.createBookmark(true);
  13788. var tableItems = getTableItemsByRange(this),
  13789. cell = tableItems.cell,
  13790. table = tableItems.table,
  13791. ut = getUETable(table),
  13792. cellInfo = ut.getCellInfo(cell);
  13793. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  13794. if (!ut.selectedTds.length) {
  13795. ut.insertRow(cellInfo.rowIndex, cell);
  13796. } else {
  13797. var range = ut.cellsRange;
  13798. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  13799. ut.insertRow(range.beginRowIndex, cell);
  13800. }
  13801. }
  13802. rng.moveToBookmark(bk).select();
  13803. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  13804. }
  13805. };
  13806. //后插入行
  13807. UE.commands["insertrownext"] = {
  13808. queryCommandState: function () {
  13809. var tableItems = getTableItemsByRange(this),
  13810. cell = tableItems.cell;
  13811. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  13812. },
  13813. execCommand: function () {
  13814. var rng = this.selection.getRange(),
  13815. bk = rng.createBookmark(true);
  13816. var tableItems = getTableItemsByRange(this),
  13817. cell = tableItems.cell,
  13818. table = tableItems.table,
  13819. ut = getUETable(table),
  13820. cellInfo = ut.getCellInfo(cell);
  13821. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  13822. if (!ut.selectedTds.length) {
  13823. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  13824. } else {
  13825. var range = ut.cellsRange;
  13826. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  13827. ut.insertRow(range.endRowIndex + 1, cell);
  13828. }
  13829. }
  13830. rng.moveToBookmark(bk).select();
  13831. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  13832. }
  13833. };
  13834. UE.commands["deleterow"] = {
  13835. queryCommandState: function () {
  13836. var tableItems = getTableItemsByRange(this);
  13837. if (!tableItems.cell) {
  13838. return -1;
  13839. }
  13840. },
  13841. execCommand: function () {
  13842. var cell = getTableItemsByRange(this).cell,
  13843. ut = getUETable(cell),
  13844. cellsRange = ut.cellsRange,
  13845. cellInfo = ut.getCellInfo(cell),
  13846. preCell = ut.getVSideCell(cell),
  13847. nextCell = ut.getVSideCell(cell, true),
  13848. rng = this.selection.getRange();
  13849. if (utils.isEmptyObject(cellsRange)) {
  13850. ut.deleteRow(cellInfo.rowIndex);
  13851. } else {
  13852. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  13853. ut.deleteRow(cellsRange.beginRowIndex);
  13854. }
  13855. }
  13856. var table = ut.table;
  13857. if (!table.getElementsByTagName('td').length) {
  13858. var nextSibling = table.nextSibling;
  13859. domUtils.remove(table);
  13860. if (nextSibling) {
  13861. rng.setStart(nextSibling, 0).setCursor(false, true);
  13862. }
  13863. } else {
  13864. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  13865. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  13866. } else {
  13867. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  13868. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  13869. }
  13870. }
  13871. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  13872. }
  13873. };
  13874. UE.commands["insertcol"] = {
  13875. queryCommandState: function (cmd) {
  13876. var tableItems = getTableItemsByRange(this),
  13877. cell = tableItems.cell;
  13878. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  13879. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  13880. },
  13881. execCommand: function (cmd) {
  13882. var rng = this.selection.getRange(),
  13883. bk = rng.createBookmark(true);
  13884. if (this.queryCommandState(cmd) == -1)return;
  13885. var cell = getTableItemsByRange(this).cell,
  13886. ut = getUETable(cell),
  13887. cellInfo = ut.getCellInfo(cell);
  13888. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  13889. if (!ut.selectedTds.length) {
  13890. ut.insertCol(cellInfo.colIndex, cell);
  13891. } else {
  13892. var range = ut.cellsRange;
  13893. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  13894. ut.insertCol(range.beginColIndex, cell);
  13895. }
  13896. }
  13897. rng.moveToBookmark(bk).select(true);
  13898. }
  13899. };
  13900. UE.commands["insertcolnext"] = {
  13901. queryCommandState: function () {
  13902. var tableItems = getTableItemsByRange(this),
  13903. cell = tableItems.cell;
  13904. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  13905. },
  13906. execCommand: function () {
  13907. var rng = this.selection.getRange(),
  13908. bk = rng.createBookmark(true);
  13909. var cell = getTableItemsByRange(this).cell,
  13910. ut = getUETable(cell),
  13911. cellInfo = ut.getCellInfo(cell);
  13912. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  13913. if (!ut.selectedTds.length) {
  13914. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  13915. } else {
  13916. var range = ut.cellsRange;
  13917. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  13918. ut.insertCol(range.endColIndex + 1, cell);
  13919. }
  13920. }
  13921. rng.moveToBookmark(bk).select();
  13922. }
  13923. };
  13924. UE.commands["deletecol"] = {
  13925. queryCommandState: function () {
  13926. var tableItems = getTableItemsByRange(this);
  13927. if (!tableItems.cell) return -1;
  13928. },
  13929. execCommand: function () {
  13930. var cell = getTableItemsByRange(this).cell,
  13931. ut = getUETable(cell),
  13932. range = ut.cellsRange,
  13933. cellInfo = ut.getCellInfo(cell),
  13934. preCell = ut.getHSideCell(cell),
  13935. nextCell = ut.getHSideCell(cell, true);
  13936. if (utils.isEmptyObject(range)) {
  13937. ut.deleteCol(cellInfo.colIndex);
  13938. } else {
  13939. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  13940. ut.deleteCol(range.beginColIndex);
  13941. }
  13942. }
  13943. var table = ut.table,
  13944. rng = this.selection.getRange();
  13945. if (!table.getElementsByTagName('td').length) {
  13946. var nextSibling = table.nextSibling;
  13947. domUtils.remove(table);
  13948. if (nextSibling) {
  13949. rng.setStart(nextSibling, 0).setCursor(false, true);
  13950. }
  13951. } else {
  13952. if (domUtils.inDoc(cell, this.document)) {
  13953. rng.setStart(cell, 0).setCursor(false, true);
  13954. } else {
  13955. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  13956. rng.selectNodeContents(nextCell).setCursor(false, true);
  13957. } else {
  13958. if (preCell && domUtils.inDoc(preCell, this.document)) {
  13959. rng.selectNodeContents(preCell).setCursor(true, true);
  13960. }
  13961. }
  13962. }
  13963. }
  13964. }
  13965. };
  13966. UE.commands["splittocells"] = {
  13967. queryCommandState: function () {
  13968. var tableItems = getTableItemsByRange(this),
  13969. cell = tableItems.cell;
  13970. if (!cell) return -1;
  13971. var ut = getUETable(tableItems.table);
  13972. if (ut.selectedTds.length > 0) return -1;
  13973. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  13974. },
  13975. execCommand: function () {
  13976. var rng = this.selection.getRange(),
  13977. bk = rng.createBookmark(true);
  13978. var cell = getTableItemsByRange(this).cell,
  13979. ut = getUETable(cell);
  13980. ut.splitToCells(cell);
  13981. rng.moveToBookmark(bk).select();
  13982. }
  13983. };
  13984. UE.commands["splittorows"] = {
  13985. queryCommandState: function () {
  13986. var tableItems = getTableItemsByRange(this),
  13987. cell = tableItems.cell;
  13988. if (!cell) return -1;
  13989. var ut = getUETable(tableItems.table);
  13990. if (ut.selectedTds.length > 0) return -1;
  13991. return cell && cell.rowSpan > 1 ? 0 : -1;
  13992. },
  13993. execCommand: function () {
  13994. var rng = this.selection.getRange(),
  13995. bk = rng.createBookmark(true);
  13996. var cell = getTableItemsByRange(this).cell,
  13997. ut = getUETable(cell);
  13998. ut.splitToRows(cell);
  13999. rng.moveToBookmark(bk).select();
  14000. }
  14001. };
  14002. UE.commands["splittocols"] = {
  14003. queryCommandState: function () {
  14004. var tableItems = getTableItemsByRange(this),
  14005. cell = tableItems.cell;
  14006. if (!cell) return -1;
  14007. var ut = getUETable(tableItems.table);
  14008. if (ut.selectedTds.length > 0) return -1;
  14009. return cell && cell.colSpan > 1 ? 0 : -1;
  14010. },
  14011. execCommand: function () {
  14012. var rng = this.selection.getRange(),
  14013. bk = rng.createBookmark(true);
  14014. var cell = getTableItemsByRange(this).cell,
  14015. ut = getUETable(cell);
  14016. ut.splitToCols(cell);
  14017. rng.moveToBookmark(bk).select();
  14018. }
  14019. };
  14020. UE.commands["adaptbytext"] =
  14021. UE.commands["adaptbywindow"] = {
  14022. queryCommandState: function () {
  14023. return getTableItemsByRange(this).table ? 0 : -1
  14024. },
  14025. execCommand: function (cmd) {
  14026. var tableItems = getTableItemsByRange(this),
  14027. table = tableItems.table;
  14028. if (table) {
  14029. if (cmd == 'adaptbywindow') {
  14030. resetTdWidth(table, this);
  14031. } else {
  14032. var cells = domUtils.getElementsByTagName(table, "td th");
  14033. utils.each(cells, function (cell) {
  14034. cell.removeAttribute("width");
  14035. });
  14036. table.removeAttribute("width");
  14037. }
  14038. }
  14039. }
  14040. };
  14041. //平均分配各列
  14042. UE.commands['averagedistributecol'] = {
  14043. queryCommandState: function () {
  14044. var ut = getUETableBySelected(this);
  14045. if (!ut) return -1;
  14046. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  14047. },
  14048. execCommand: function (cmd) {
  14049. var me = this,
  14050. ut = getUETableBySelected(me);
  14051. function getAverageWidth() {
  14052. var tb = ut.table,
  14053. averageWidth, sumWidth = 0, colsNum = 0,
  14054. tbAttr = getDefaultValue(me, tb);
  14055. if (ut.isFullRow()) {
  14056. sumWidth = tb.offsetWidth;
  14057. colsNum = ut.colsNum;
  14058. } else {
  14059. var begin = ut.cellsRange.beginColIndex,
  14060. end = ut.cellsRange.endColIndex,
  14061. node;
  14062. for (var i = begin; i <= end;) {
  14063. node = ut.selectedTds[i];
  14064. sumWidth += node.offsetWidth;
  14065. i += node.colSpan;
  14066. colsNum += 1;
  14067. }
  14068. }
  14069. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  14070. return averageWidth;
  14071. }
  14072. function setAverageWidth(averageWidth) {
  14073. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  14074. node.setAttribute("width", "");
  14075. });
  14076. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  14077. utils.each(cells, function (node) {
  14078. if (node.colSpan == 1) {
  14079. node.setAttribute("width", averageWidth);
  14080. }
  14081. });
  14082. }
  14083. if (ut && ut.selectedTds.length) {
  14084. setAverageWidth(getAverageWidth());
  14085. }
  14086. }
  14087. };
  14088. //平均分配各行
  14089. UE.commands['averagedistributerow'] = {
  14090. queryCommandState: function () {
  14091. var ut = getUETableBySelected(this);
  14092. if (!ut) return -1;
  14093. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  14094. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  14095. },
  14096. execCommand: function (cmd) {
  14097. var me = this,
  14098. ut = getUETableBySelected(me);
  14099. function getAverageHeight() {
  14100. var averageHeight, rowNum, sumHeight = 0,
  14101. tb = ut.table,
  14102. tbAttr = getDefaultValue(me, tb),
  14103. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  14104. if (ut.isFullCol()) {
  14105. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  14106. thArr = domUtils.getElementsByTagName(tb, "th"),
  14107. captionHeight, thHeight;
  14108. if (captionArr.length > 0) {
  14109. captionHeight = captionArr[0].offsetHeight;
  14110. }
  14111. if (thArr.length > 0) {
  14112. thHeight = thArr[0].offsetHeight;
  14113. }
  14114. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  14115. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  14116. } else {
  14117. var begin = ut.cellsRange.beginRowIndex,
  14118. end = ut.cellsRange.endRowIndex,
  14119. count = 0,
  14120. trs = domUtils.getElementsByTagName(tb, "tr");
  14121. for (var i = begin; i <= end; i++) {
  14122. sumHeight += trs[i].offsetHeight;
  14123. count += 1;
  14124. }
  14125. rowNum = count;
  14126. }
  14127. //ie8下是混杂模式
  14128. if (browser.ie && browser.version < 9) {
  14129. averageHeight = Math.ceil(sumHeight / rowNum);
  14130. } else {
  14131. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  14132. }
  14133. return averageHeight;
  14134. }
  14135. function setAverageHeight(averageHeight) {
  14136. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  14137. utils.each(cells, function (node) {
  14138. if (node.rowSpan == 1) {
  14139. node.setAttribute("height", averageHeight);
  14140. }
  14141. });
  14142. }
  14143. if (ut && ut.selectedTds.length) {
  14144. setAverageHeight(getAverageHeight());
  14145. }
  14146. }
  14147. };
  14148. //单元格对齐方式
  14149. UE.commands['cellalignment'] = {
  14150. queryCommandState: function () {
  14151. return getTableItemsByRange(this).table ? 0 : -1
  14152. },
  14153. execCommand: function (cmd, data) {
  14154. var me = this,
  14155. ut = getUETableBySelected(me);
  14156. if (!ut) {
  14157. var start = me.selection.getStart(),
  14158. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  14159. if (!/caption/ig.test(cell.tagName)) {
  14160. domUtils.setAttributes(cell, data);
  14161. } else {
  14162. cell.style.textAlign = data.align;
  14163. cell.style.verticalAlign = data.vAlign;
  14164. }
  14165. me.selection.getRange().setCursor(true);
  14166. } else {
  14167. utils.each(ut.selectedTds, function (cell) {
  14168. domUtils.setAttributes(cell, data);
  14169. });
  14170. }
  14171. },
  14172. /**
  14173. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  14174. * @see UE.UETable.getTableCellAlignState
  14175. */
  14176. queryCommandValue: function (cmd) {
  14177. var activeMenuCell = getTableItemsByRange( this).cell;
  14178. if( !activeMenuCell ) {
  14179. activeMenuCell = getSelectedArr(this)[0];
  14180. }
  14181. if (!activeMenuCell) {
  14182. return null;
  14183. } else {
  14184. //获取同时选中的其他单元格
  14185. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  14186. !cells.length && ( cells = activeMenuCell );
  14187. return UE.UETable.getTableCellAlignState(cells);
  14188. }
  14189. }
  14190. };
  14191. //表格对齐方式
  14192. UE.commands['tablealignment'] = {
  14193. queryCommandState: function () {
  14194. if (browser.ie && browser.version < 8) {
  14195. return -1;
  14196. }
  14197. return getTableItemsByRange(this).table ? 0 : -1
  14198. },
  14199. execCommand: function (cmd, value) {
  14200. var me = this,
  14201. start = me.selection.getStart(),
  14202. table = start && domUtils.findParentByTagName(start, ["table"], true);
  14203. if (table) {
  14204. table.setAttribute("align",value);
  14205. }
  14206. }
  14207. };
  14208. //表格属性
  14209. UE.commands['edittable'] = {
  14210. queryCommandState: function () {
  14211. return getTableItemsByRange(this).table ? 0 : -1
  14212. },
  14213. execCommand: function (cmd, color) {
  14214. var rng = this.selection.getRange(),
  14215. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  14216. if (table) {
  14217. var arr = domUtils.getElementsByTagName(table, "td").concat(
  14218. domUtils.getElementsByTagName(table, "th"),
  14219. domUtils.getElementsByTagName(table, "caption")
  14220. );
  14221. utils.each(arr, function (node) {
  14222. node.style.borderColor = color;
  14223. });
  14224. }
  14225. }
  14226. };
  14227. //单元格属性
  14228. UE.commands['edittd'] = {
  14229. queryCommandState: function () {
  14230. return getTableItemsByRange(this).table ? 0 : -1
  14231. },
  14232. execCommand: function (cmd, bkColor) {
  14233. var me = this,
  14234. ut = getUETableBySelected(me);
  14235. if (!ut) {
  14236. var start = me.selection.getStart(),
  14237. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  14238. if (cell) {
  14239. cell.style.backgroundColor = bkColor;
  14240. }
  14241. } else {
  14242. utils.each(ut.selectedTds, function (cell) {
  14243. cell.style.backgroundColor = bkColor;
  14244. });
  14245. }
  14246. }
  14247. };
  14248. UE.commands["settablebackground"] = {
  14249. queryCommandState: function () {
  14250. return getSelectedArr(this).length > 1 ? 0 : -1;
  14251. },
  14252. execCommand: function (cmd, value) {
  14253. var cells, ut;
  14254. cells = getSelectedArr(this);
  14255. ut = getUETable(cells[0]);
  14256. ut.setBackground(cells, value);
  14257. }
  14258. };
  14259. UE.commands["cleartablebackground"] = {
  14260. queryCommandState: function () {
  14261. var cells = getSelectedArr(this);
  14262. if (!cells.length)return -1;
  14263. for (var i = 0, cell; cell = cells[i++];) {
  14264. if (cell.style.backgroundColor !== "") return 0;
  14265. }
  14266. return -1;
  14267. },
  14268. execCommand: function () {
  14269. var cells = getSelectedArr(this),
  14270. ut = getUETable(cells[0]);
  14271. ut.removeBackground(cells);
  14272. }
  14273. };
  14274. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  14275. queryCommandState: function (cmd) {
  14276. var table = getTableItemsByRange(this).table;
  14277. if (!table) return -1;
  14278. var interlaced = table.getAttribute("interlaced");
  14279. if (cmd == "interlacetable") {
  14280. //TODO 待定
  14281. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  14282. return (interlaced === "enabled") ? -1 : 0;
  14283. } else {
  14284. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  14285. }
  14286. },
  14287. execCommand: function (cmd, classList) {
  14288. var table = getTableItemsByRange(this).table;
  14289. if (cmd == "interlacetable") {
  14290. table.setAttribute("interlaced", "enabled");
  14291. this.fireEvent("interlacetable", table, classList);
  14292. } else {
  14293. table.setAttribute("interlaced", "disabled");
  14294. this.fireEvent("uninterlacetable", table);
  14295. }
  14296. }
  14297. };
  14298. UE.commands["setbordervisible"] = {
  14299. queryCommandState: function (cmd) {
  14300. var table = getTableItemsByRange(this).table;
  14301. if (!table) return -1;
  14302. return 0;
  14303. },
  14304. execCommand: function () {
  14305. var table = getTableItemsByRange(this).table;
  14306. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  14307. td.style.borderWidth = '1px';
  14308. td.style.borderStyle = 'solid';
  14309. })
  14310. }
  14311. };
  14312. function resetTdWidth(table, editor) {
  14313. var tds = domUtils.getElementsByTagName(table,'td th');
  14314. utils.each(tds, function (td) {
  14315. td.removeAttribute("width");
  14316. });
  14317. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  14318. var tdsWidths = [];
  14319. setTimeout(function () {
  14320. utils.each(tds, function (td) {
  14321. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  14322. })
  14323. utils.each(tds, function (td,i) {
  14324. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  14325. })
  14326. }, 0);
  14327. }
  14328. function getTableWidth(editor, needIEHack, defaultValue) {
  14329. var body = editor.body;
  14330. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  14331. }
  14332. function getSelectedArr(editor) {
  14333. var cell = getTableItemsByRange(editor).cell;
  14334. if (cell) {
  14335. var ut = getUETable(cell);
  14336. return ut.selectedTds.length ? ut.selectedTds : [cell];
  14337. } else {
  14338. return [];
  14339. }
  14340. }
  14341. })();
  14342. /**
  14343. * Created with JetBrains PhpStorm.
  14344. * User: taoqili
  14345. * Date: 12-10-12
  14346. * Time: 上午10:05
  14347. * To change this template use File | Settings | File Templates.
  14348. */
  14349. UE.plugins['table'] = function () {
  14350. var me = this,
  14351. tabTimer = null,
  14352. //拖动计时器
  14353. tableDragTimer = null,
  14354. //双击计时器
  14355. tableResizeTimer = null,
  14356. //单元格最小宽度
  14357. cellMinWidth = 5,
  14358. isInResizeBuffer = false,
  14359. //单元格边框大小
  14360. cellBorderWidth = 5,
  14361. //鼠标偏移距离
  14362. offsetOfTableCell = 10,
  14363. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  14364. singleClickState = 0,
  14365. userActionStatus = null,
  14366. //双击允许的时间范围
  14367. dblclickTime = 360,
  14368. UT = UE.UETable,
  14369. getUETable = function (tdOrTable) {
  14370. return UT.getUETable(tdOrTable);
  14371. },
  14372. getUETableBySelected = function (editor) {
  14373. return UT.getUETableBySelected(editor);
  14374. },
  14375. getDefaultValue = function (editor, table) {
  14376. return UT.getDefaultValue(editor, table);
  14377. },
  14378. removeSelectedClass = function (cells) {
  14379. return UT.removeSelectedClass(cells);
  14380. };
  14381. function showError(e) {
  14382. // throw e;
  14383. }
  14384. me.ready(function(){
  14385. var me = this;
  14386. var orgGetText = me.selection.getText;
  14387. me.selection.getText = function(){
  14388. var table = getUETableBySelected(me);
  14389. if(table){
  14390. var str = '';
  14391. utils.each(table.selectedTds,function(td){
  14392. str += td[browser.ie?'innerText':'textContent'];
  14393. })
  14394. return str;
  14395. }else{
  14396. return orgGetText.call(me.selection)
  14397. }
  14398. }
  14399. })
  14400. //处理拖动及框选相关方法
  14401. var startTd = null, //鼠标按下时的锚点td
  14402. currentTd = null, //当前鼠标经过时的td
  14403. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  14404. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  14405. dragButton = null,
  14406. dragOver = false,
  14407. dragLine = null, //模拟的拖动线
  14408. dragTd = null; //发生拖动的目标td
  14409. var mousedown = false,
  14410. //todo 判断混乱模式
  14411. needIEHack = true;
  14412. me.setOpt({
  14413. 'maxColNum':20,
  14414. 'maxRowNum':100,
  14415. 'defaultCols':5,
  14416. 'defaultRows':5,
  14417. 'tdvalign':'top',
  14418. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  14419. 'tableDragable':false,
  14420. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  14421. });
  14422. me.getUETable = getUETable;
  14423. var commands = {
  14424. 'deletetable':1,
  14425. 'inserttable':1,
  14426. 'cellvalign':1,
  14427. 'insertcaption':1,
  14428. 'deletecaption':1,
  14429. 'inserttitle':1,
  14430. 'deletetitle':1,
  14431. "mergeright":1,
  14432. "mergedown":1,
  14433. "mergecells":1,
  14434. "insertrow":1,
  14435. "insertrownext":1,
  14436. "deleterow":1,
  14437. "insertcol":1,
  14438. "insertcolnext":1,
  14439. "deletecol":1,
  14440. "splittocells":1,
  14441. "splittorows":1,
  14442. "splittocols":1,
  14443. "adaptbytext":1,
  14444. "adaptbywindow":1,
  14445. "adaptbycustomer":1,
  14446. "insertparagraph":1,
  14447. "insertparagraphbeforetable":1,
  14448. "averagedistributecol":1,
  14449. "averagedistributerow":1
  14450. };
  14451. me.ready(function () {
  14452. utils.cssRule('table',
  14453. //选中的td上的样式
  14454. '.selectTdClass{background-color:#edf5fa !important}' +
  14455. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  14456. //插入的表格的默认样式
  14457. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  14458. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  14459. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  14460. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  14461. 'table tr.firstRow th{border-top-width:2px;}' +
  14462. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  14463. 'td p{margin:0;padding:0;}', me.document);
  14464. var tableCopyList, isFullCol, isFullRow;
  14465. //注册del/backspace事件
  14466. me.addListener('keydown', function (cmd, evt) {
  14467. var me = this;
  14468. var keyCode = evt.keyCode || evt.which;
  14469. if (keyCode == 8) {
  14470. var ut = getUETableBySelected(me);
  14471. if (ut && ut.selectedTds.length) {
  14472. if (ut.isFullCol()) {
  14473. me.execCommand('deletecol')
  14474. } else if (ut.isFullRow()) {
  14475. me.execCommand('deleterow')
  14476. } else {
  14477. me.fireEvent('delcells');
  14478. }
  14479. domUtils.preventDefault(evt);
  14480. }
  14481. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  14482. range = me.selection.getRange();
  14483. if (range.collapsed && caption && isEmptyBlock(caption)) {
  14484. me.fireEvent('saveScene');
  14485. var table = caption.parentNode;
  14486. domUtils.remove(caption);
  14487. if (table) {
  14488. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  14489. }
  14490. me.fireEvent('saveScene');
  14491. }
  14492. }
  14493. if (keyCode == 46) {
  14494. ut = getUETableBySelected(me);
  14495. if (ut) {
  14496. me.fireEvent('saveScene');
  14497. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  14498. domUtils.fillNode(me.document, ci)
  14499. }
  14500. me.fireEvent('saveScene');
  14501. domUtils.preventDefault(evt);
  14502. }
  14503. }
  14504. if (keyCode == 13) {
  14505. var rng = me.selection.getRange(),
  14506. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  14507. if (caption) {
  14508. var table = domUtils.findParentByTagName(caption, 'table');
  14509. if (!rng.collapsed) {
  14510. rng.deleteContents();
  14511. me.fireEvent('saveScene');
  14512. } else {
  14513. if (caption) {
  14514. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  14515. }
  14516. }
  14517. domUtils.preventDefault(evt);
  14518. return;
  14519. }
  14520. if (rng.collapsed) {
  14521. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  14522. if (table) {
  14523. var cell = table.rows[0].cells[0],
  14524. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  14525. preNode = table.previousSibling;
  14526. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  14527. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  14528. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  14529. me.execCommand('insertparagraphbeforetable');
  14530. domUtils.preventDefault(evt);
  14531. }
  14532. }
  14533. }
  14534. }
  14535. }
  14536. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  14537. tableCopyList = null;
  14538. var ut = getUETableBySelected(me);
  14539. if (ut) {
  14540. var tds = ut.selectedTds;
  14541. isFullCol = ut.isFullCol();
  14542. isFullRow = ut.isFullRow();
  14543. tableCopyList = [
  14544. [ut.cloneCell(tds[0],null,true)]
  14545. ];
  14546. for (var i = 1, ci; ci = tds[i]; i++) {
  14547. if (ci.parentNode !== tds[i - 1].parentNode) {
  14548. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  14549. } else {
  14550. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  14551. }
  14552. }
  14553. }
  14554. }
  14555. });
  14556. me.addListener("tablehasdeleted",function(){
  14557. toggleDraggableState(this, false, "", null);
  14558. if (dragButton)domUtils.remove(dragButton);
  14559. });
  14560. me.addListener('beforepaste', function (cmd, html) {
  14561. var me = this;
  14562. var rng = me.selection.getRange();
  14563. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  14564. var div = me.document.createElement("div");
  14565. div.innerHTML = html.html;
  14566. //trace:3729
  14567. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  14568. return;
  14569. }
  14570. var table = getUETableBySelected(me);
  14571. if (tableCopyList) {
  14572. me.fireEvent('saveScene');
  14573. var rng = me.selection.getRange();
  14574. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  14575. if (td) {
  14576. var ut = getUETable(td);
  14577. if (isFullRow) {
  14578. var rowIndex = ut.getCellInfo(td).rowIndex;
  14579. if (td.tagName == 'TH') {
  14580. rowIndex++;
  14581. }
  14582. for (var i = 0, ci; ci = tableCopyList[i++];) {
  14583. var tr = ut.insertRow(rowIndex++, "td");
  14584. for (var j = 0, cj; cj = ci[j]; j++) {
  14585. var cell = tr.cells[j];
  14586. if (!cell) {
  14587. cell = tr.insertCell(j)
  14588. }
  14589. cell.innerHTML = cj.innerHTML;
  14590. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  14591. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  14592. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  14593. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  14594. }
  14595. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  14596. if (!ci[j])
  14597. break;
  14598. cj.innerHTML = ci[j].innerHTML;
  14599. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  14600. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  14601. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  14602. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  14603. }
  14604. }
  14605. } else {
  14606. if (isFullCol) {
  14607. cellInfo = ut.getCellInfo(td);
  14608. var maxColNum = 0;
  14609. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  14610. maxColNum += cj.colSpan || 1;
  14611. }
  14612. me.__hasEnterExecCommand = true;
  14613. for (i = 0; i < maxColNum; i++) {
  14614. me.execCommand('insertcol');
  14615. }
  14616. me.__hasEnterExecCommand = false;
  14617. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  14618. if (td.tagName == 'TH') {
  14619. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  14620. }
  14621. }
  14622. for (var i = 0, ci; ci = tableCopyList[i++];) {
  14623. tmpNode = td;
  14624. for (var j = 0, cj; cj = ci[j++];) {
  14625. if (td) {
  14626. td.innerHTML = cj.innerHTML;
  14627. //todo 定制处理
  14628. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  14629. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  14630. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  14631. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  14632. preNode = td;
  14633. td = td.nextSibling;
  14634. } else {
  14635. var cloneTd = cj.cloneNode(true);
  14636. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  14637. preNode.parentNode.appendChild(cloneTd)
  14638. }
  14639. }
  14640. td = ut.getNextCell(tmpNode, true, true);
  14641. if (!tableCopyList[i])
  14642. break;
  14643. if (!td) {
  14644. var cellInfo = ut.getCellInfo(tmpNode);
  14645. ut.table.insertRow(ut.table.rows.length);
  14646. ut.update();
  14647. td = ut.getVSideCell(tmpNode, true);
  14648. }
  14649. }
  14650. }
  14651. ut.update();
  14652. } else {
  14653. table = me.document.createElement('table');
  14654. for (var i = 0, ci; ci = tableCopyList[i++];) {
  14655. var tr = table.insertRow(table.rows.length);
  14656. for (var j = 0, cj; cj = ci[j++];) {
  14657. cloneTd = UT.cloneCell(cj,null,true);
  14658. domUtils.removeAttributes(cloneTd, ['class']);
  14659. tr.appendChild(cloneTd)
  14660. }
  14661. if (j == 2 && cloneTd.rowSpan > 1) {
  14662. cloneTd.rowSpan = 1;
  14663. }
  14664. }
  14665. var defaultValue = getDefaultValue(me),
  14666. width = me.body.offsetWidth -
  14667. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  14668. me.execCommand('insertHTML', '<table ' +
  14669. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  14670. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  14671. }
  14672. me.fireEvent('contentchange');
  14673. me.fireEvent('saveScene');
  14674. html.html = '';
  14675. return true;
  14676. } else {
  14677. var div = me.document.createElement("div"), tables;
  14678. div.innerHTML = html.html;
  14679. tables = div.getElementsByTagName("table");
  14680. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  14681. utils.each(tables, function (t) {
  14682. domUtils.remove(t)
  14683. });
  14684. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  14685. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  14686. }
  14687. } else {
  14688. utils.each(tables, function (table) {
  14689. removeStyleSize(table, true);
  14690. domUtils.removeAttributes(table, ['style', 'border']);
  14691. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  14692. if (isEmptyBlock(td)) {
  14693. domUtils.fillNode(me.document, td);
  14694. }
  14695. removeStyleSize(td, true);
  14696. // domUtils.removeAttributes(td, ['style'])
  14697. });
  14698. });
  14699. }
  14700. html.html = div.innerHTML;
  14701. }
  14702. });
  14703. me.addListener('afterpaste', function () {
  14704. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  14705. if (table.offsetWidth > me.body.offsetWidth) {
  14706. var defaultValue = getDefaultValue(me, table);
  14707. 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'
  14708. }
  14709. })
  14710. });
  14711. me.addListener('blur', function () {
  14712. tableCopyList = null;
  14713. });
  14714. var timer;
  14715. me.addListener('keydown', function () {
  14716. clearTimeout(timer);
  14717. timer = setTimeout(function () {
  14718. var rng = me.selection.getRange(),
  14719. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  14720. if (cell) {
  14721. var table = cell.parentNode.parentNode.parentNode;
  14722. if (table.offsetWidth > table.getAttribute("width")) {
  14723. cell.style.wordBreak = "break-all";
  14724. }
  14725. }
  14726. }, 100);
  14727. });
  14728. me.addListener("selectionchange", function () {
  14729. toggleDraggableState(me, false, "", null);
  14730. });
  14731. //内容变化时触发索引更新
  14732. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  14733. me.addListener("contentchange", function () {
  14734. var me = this;
  14735. //尽可能排除一些不需要更新的状况
  14736. hideDragLine(me);
  14737. if (getUETableBySelected(me))return;
  14738. var rng = me.selection.getRange();
  14739. var start = rng.startContainer;
  14740. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  14741. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  14742. if (me.fireEvent("excludetable", table) === true) return;
  14743. table.ueTable = new UT(table);
  14744. //trace:3742
  14745. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  14746. //
  14747. // if (domUtils.isEmptyBlock(td) && td !== start) {
  14748. // domUtils.fillNode(me.document, td);
  14749. // if (browser.ie && browser.version == 6) {
  14750. // td.innerHTML = '&nbsp;'
  14751. // }
  14752. // }
  14753. // });
  14754. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  14755. // if (domUtils.isEmptyBlock(th) && th !== start) {
  14756. // domUtils.fillNode(me.document, th);
  14757. // if (browser.ie && browser.version == 6) {
  14758. // th.innerHTML = '&nbsp;'
  14759. // }
  14760. // }
  14761. // });
  14762. table.onmouseover = function () {
  14763. me.fireEvent('tablemouseover', table);
  14764. };
  14765. table.onmousemove = function () {
  14766. me.fireEvent('tablemousemove', table);
  14767. me.options.tableDragable && toggleDragButton(true, this, me);
  14768. utils.defer(function(){
  14769. me.fireEvent('contentchange',50)
  14770. },true)
  14771. };
  14772. table.onmouseout = function () {
  14773. me.fireEvent('tablemouseout', table);
  14774. toggleDraggableState(me, false, "", null);
  14775. hideDragLine(me);
  14776. };
  14777. table.onclick = function (evt) {
  14778. evt = me.window.event || evt;
  14779. var target = getParentTdOrTh(evt.target || evt.srcElement);
  14780. if (!target)return;
  14781. var ut = getUETable(target),
  14782. table = ut.table,
  14783. cellInfo = ut.getCellInfo(target),
  14784. cellsRange,
  14785. rng = me.selection.getRange();
  14786. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  14787. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  14788. // ut.setSelected(cellsRange);
  14789. // return;
  14790. // }
  14791. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  14792. //
  14793. // return;
  14794. // }
  14795. if (inTableSide(table, target, evt, true)) {
  14796. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  14797. if (evt.shiftKey && ut.selectedTds.length) {
  14798. if (ut.selectedTds[0] !== endTdCol) {
  14799. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  14800. ut.setSelected(cellsRange);
  14801. } else {
  14802. rng && rng.selectNodeContents(endTdCol).select();
  14803. }
  14804. } else {
  14805. if (target !== endTdCol) {
  14806. cellsRange = ut.getCellsRange(target, endTdCol);
  14807. ut.setSelected(cellsRange);
  14808. } else {
  14809. rng && rng.selectNodeContents(endTdCol).select();
  14810. }
  14811. }
  14812. return;
  14813. }
  14814. if (inTableSide(table, target, evt)) {
  14815. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  14816. if (evt.shiftKey && ut.selectedTds.length) {
  14817. if (ut.selectedTds[0] !== endTdRow) {
  14818. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  14819. ut.setSelected(cellsRange);
  14820. } else {
  14821. rng && rng.selectNodeContents(endTdRow).select();
  14822. }
  14823. } else {
  14824. if (target !== endTdRow) {
  14825. cellsRange = ut.getCellsRange(target, endTdRow);
  14826. ut.setSelected(cellsRange);
  14827. } else {
  14828. rng && rng.selectNodeContents(endTdRow).select();
  14829. }
  14830. }
  14831. }
  14832. };
  14833. });
  14834. switchBorderColor(me, true);
  14835. });
  14836. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  14837. domUtils.on(me.document, "mouseout", function (evt) {
  14838. var target = evt.target || evt.srcElement;
  14839. if (target.tagName == "TABLE") {
  14840. toggleDraggableState(me, false, "", null);
  14841. }
  14842. });
  14843. /**
  14844. * 表格隔行变色
  14845. */
  14846. me.addListener("interlacetable",function(type,table,classList){
  14847. if(!table) return;
  14848. var me = this,
  14849. rows = table.rows,
  14850. len = rows.length,
  14851. getClass = function(list,index,repeat){
  14852. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  14853. };
  14854. for(var i = 0;i<len;i++){
  14855. rows[i].className = getClass( classList|| me.options.classList,i,true);
  14856. }
  14857. });
  14858. me.addListener("uninterlacetable",function(type,table){
  14859. if(!table) return;
  14860. var me = this,
  14861. rows = table.rows,
  14862. classList = me.options.classList,
  14863. len = rows.length;
  14864. for(var i = 0;i<len;i++){
  14865. domUtils.removeClasses( rows[i], classList );
  14866. }
  14867. });
  14868. me.addListener("mousedown", mouseDownEvent);
  14869. me.addListener("mouseup", mouseUpEvent);
  14870. //拖动的时候不出发mouseup
  14871. domUtils.on( me.body, 'dragstart', function( evt ){
  14872. mouseUpEvent.call( me, 'dragstart', evt );
  14873. });
  14874. var currentRowIndex = 0;
  14875. me.addListener("mousedown", function () {
  14876. currentRowIndex = 0;
  14877. });
  14878. me.addListener('tabkeydown', function () {
  14879. var range = this.selection.getRange(),
  14880. common = range.getCommonAncestor(true, true),
  14881. table = domUtils.findParentByTagName(common, 'table');
  14882. if (table) {
  14883. if (domUtils.findParentByTagName(common, 'caption', true)) {
  14884. var cell = domUtils.getElementsByTagName(table, 'th td');
  14885. if (cell && cell.length) {
  14886. range.setStart(cell[0], 0).setCursor(false, true)
  14887. }
  14888. } else {
  14889. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  14890. ua = getUETable(cell);
  14891. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  14892. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  14893. if (nextCell) {
  14894. if (isEmptyBlock(nextCell)) {
  14895. range.setStart(nextCell, 0).setCursor(false, true)
  14896. } else {
  14897. range.selectNodeContents(nextCell).select()
  14898. }
  14899. } else {
  14900. me.fireEvent('saveScene');
  14901. me.__hasEnterExecCommand = true;
  14902. this.execCommand('insertrownext');
  14903. me.__hasEnterExecCommand = false;
  14904. range = this.selection.getRange();
  14905. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  14906. me.fireEvent('saveScene');
  14907. }
  14908. }
  14909. return true;
  14910. }
  14911. });
  14912. browser.ie && me.addListener('selectionchange', function () {
  14913. toggleDraggableState(this, false, "", null);
  14914. });
  14915. me.addListener("keydown", function (type, evt) {
  14916. var me = this;
  14917. //处理在表格的最后一个输入tab产生新的表格
  14918. var keyCode = evt.keyCode || evt.which;
  14919. if (keyCode == 8 || keyCode == 46) {
  14920. return;
  14921. }
  14922. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  14923. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  14924. var ut = getUETableBySelected(me);
  14925. if (!ut) return;
  14926. notCtrlKey && ut.clearSelected();
  14927. });
  14928. me.addListener("beforegetcontent", function () {
  14929. switchBorderColor(this, false);
  14930. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  14931. if (domUtils.isEmptyNode(ci)) {
  14932. ci.innerHTML = '&nbsp;'
  14933. }
  14934. });
  14935. });
  14936. me.addListener("aftergetcontent", function () {
  14937. switchBorderColor(this, true);
  14938. });
  14939. me.addListener("getAllHtml", function () {
  14940. removeSelectedClass(me.document.getElementsByTagName("td"));
  14941. });
  14942. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  14943. me.addListener("fullscreenchanged", function (type, fullscreen) {
  14944. if (!fullscreen) {
  14945. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  14946. tables = domUtils.getElementsByTagName(this.body, "table");
  14947. utils.each(tables, function (table) {
  14948. if (table.offsetWidth < me.body.offsetWidth) return false;
  14949. var tds = domUtils.getElementsByTagName(table, "td"),
  14950. backWidths = [];
  14951. utils.each(tds, function (td) {
  14952. backWidths.push(td.offsetWidth);
  14953. });
  14954. for (var i = 0, td; td = tds[i]; i++) {
  14955. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  14956. }
  14957. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  14958. });
  14959. }
  14960. });
  14961. //重写execCommand命令,用于处理框选时的处理
  14962. var oldExecCommand = me.execCommand;
  14963. me.execCommand = function (cmd, datatat) {
  14964. var me = this,
  14965. args = arguments;
  14966. cmd = cmd.toLowerCase();
  14967. var ut = getUETableBySelected(me), tds,
  14968. range = new dom.Range(me.document),
  14969. cmdFun = me.commands[cmd] || UE.commands[cmd],
  14970. result;
  14971. if (!cmdFun) return;
  14972. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  14973. me.__hasEnterExecCommand = true;
  14974. me.fireEvent("beforeexeccommand", cmd);
  14975. tds = ut.selectedTds;
  14976. var lastState = -2, lastValue = -2, value, state;
  14977. for (var i = 0, td; td = tds[i]; i++) {
  14978. if (isEmptyBlock(td)) {
  14979. range.setStart(td, 0).setCursor(false, true)
  14980. } else {
  14981. range.selectNode(td).select(true);
  14982. }
  14983. state = me.queryCommandState(cmd);
  14984. value = me.queryCommandValue(cmd);
  14985. if (state != -1) {
  14986. if (lastState !== state || lastValue !== value) {
  14987. me._ignoreContentChange = true;
  14988. result = oldExecCommand.apply(me, arguments);
  14989. me._ignoreContentChange = false;
  14990. }
  14991. lastState = me.queryCommandState(cmd);
  14992. lastValue = me.queryCommandValue(cmd);
  14993. if (domUtils.isEmptyBlock(td)) {
  14994. domUtils.fillNode(me.document, td)
  14995. }
  14996. }
  14997. }
  14998. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  14999. me.fireEvent('contentchange');
  15000. me.fireEvent("afterexeccommand", cmd);
  15001. me.__hasEnterExecCommand = false;
  15002. me._selectionChange();
  15003. } else {
  15004. result = oldExecCommand.apply(me, arguments);
  15005. }
  15006. return result;
  15007. };
  15008. });
  15009. /**
  15010. * 删除obj的宽高style,改成属性宽高
  15011. * @param obj
  15012. * @param replaceToProperty
  15013. */
  15014. function removeStyleSize(obj, replaceToProperty) {
  15015. removeStyle(obj, "width", true);
  15016. removeStyle(obj, "height", true);
  15017. }
  15018. function removeStyle(obj, styleName, replaceToProperty) {
  15019. if (obj.style[styleName]) {
  15020. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  15021. obj.style[styleName] = "";
  15022. }
  15023. }
  15024. function getParentTdOrTh(ele) {
  15025. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  15026. var td;
  15027. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  15028. return null;
  15029. }
  15030. function isEmptyBlock(node) {
  15031. var reg = new RegExp(domUtils.fillChar, 'g');
  15032. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  15033. return 0;
  15034. }
  15035. for (var n in dtd.$isNotEmpty) {
  15036. if (node.getElementsByTagName(n).length) {
  15037. return 0;
  15038. }
  15039. }
  15040. return 1;
  15041. }
  15042. function mouseCoords(evt) {
  15043. if (evt.pageX || evt.pageY) {
  15044. return { x:evt.pageX, y:evt.pageY };
  15045. }
  15046. return {
  15047. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  15048. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  15049. };
  15050. }
  15051. function mouseMoveEvent(evt) {
  15052. if( isEditorDisabled() ) {
  15053. return;
  15054. }
  15055. try {
  15056. //普通状态下鼠标移动
  15057. var target = getParentTdOrTh(evt.target || evt.srcElement),
  15058. pos;
  15059. //区分用户的行为是拖动还是双击
  15060. if( isInResizeBuffer ) {
  15061. me.body.style.webkitUserSelect = 'none';
  15062. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  15063. clearTableDragTimer();
  15064. isInResizeBuffer = false;
  15065. singleClickState = 0;
  15066. //drag action
  15067. tableBorderDrag(evt);
  15068. }
  15069. }
  15070. //修改单元格大小时的鼠标移动
  15071. if (onDrag && dragTd) {
  15072. singleClickState = 0;
  15073. me.body.style.webkitUserSelect = 'none';
  15074. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  15075. pos = mouseCoords(evt);
  15076. toggleDraggableState(me, true, onDrag, pos, target);
  15077. if (onDrag == "h") {
  15078. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  15079. } else if (onDrag == "v") {
  15080. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  15081. }
  15082. return;
  15083. }
  15084. //当鼠标处于table上时,修改移动过程中的光标状态
  15085. if (target) {
  15086. //针对使用table作为容器的组件不触发拖拽效果
  15087. if (me.fireEvent('excludetable', target) === true)
  15088. return;
  15089. pos = mouseCoords(evt);
  15090. var state = getRelation(target, pos),
  15091. table = domUtils.findParentByTagName(target, "table", true);
  15092. if (inTableSide(table, target, evt, true)) {
  15093. if (me.fireEvent("excludetable", table) === true) return;
  15094. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  15095. } else if (inTableSide(table, target, evt)) {
  15096. if (me.fireEvent("excludetable", table) === true) return;
  15097. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  15098. } else {
  15099. me.body.style.cursor = "text";
  15100. var curCell = target;
  15101. if (/\d/.test(state)) {
  15102. state = state.replace(/\d/, '');
  15103. target = getUETable(target).getPreviewCell(target, state == "v");
  15104. }
  15105. //位于第一行的顶部或者第一列的左边时不可拖动
  15106. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  15107. }
  15108. } else {
  15109. toggleDragButton(false, table, me);
  15110. }
  15111. } catch (e) {
  15112. showError(e);
  15113. }
  15114. }
  15115. var dragButtonTimer;
  15116. function toggleDragButton(show, table, editor) {
  15117. if (!show) {
  15118. if (dragOver)return;
  15119. dragButtonTimer = setTimeout(function () {
  15120. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  15121. }, 2000);
  15122. } else {
  15123. createDragButton(table, editor);
  15124. }
  15125. }
  15126. function createDragButton(table, editor) {
  15127. var pos = domUtils.getXY(table),
  15128. doc = table.ownerDocument;
  15129. if (dragButton && dragButton.parentNode)return dragButton;
  15130. dragButton = doc.createElement("div");
  15131. dragButton.contentEditable = false;
  15132. dragButton.innerHTML = "";
  15133. 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;";
  15134. domUtils.unSelectable(dragButton);
  15135. dragButton.onmouseover = function (evt) {
  15136. dragOver = true;
  15137. };
  15138. dragButton.onmouseout = function (evt) {
  15139. dragOver = false;
  15140. };
  15141. domUtils.on(dragButton, 'click', function (type, evt) {
  15142. doClick(evt, this);
  15143. });
  15144. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  15145. doDblClick(evt);
  15146. });
  15147. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  15148. domUtils.preventDefault(evt);
  15149. });
  15150. var timer;
  15151. function doClick(evt, button) {
  15152. // 部分浏览器下需要清理
  15153. clearTimeout(timer);
  15154. timer = setTimeout(function () {
  15155. editor.fireEvent("tableClicked", table, button);
  15156. }, 300);
  15157. }
  15158. function doDblClick(evt) {
  15159. clearTimeout(timer);
  15160. var ut = getUETable(table),
  15161. start = table.rows[0].cells[0],
  15162. end = ut.getLastCell(),
  15163. range = ut.getCellsRange(start, end);
  15164. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  15165. ut.setSelected(range);
  15166. }
  15167. doc.body.appendChild(dragButton);
  15168. }
  15169. // function inPosition(table, pos) {
  15170. // var tablePos = domUtils.getXY(table),
  15171. // width = table.offsetWidth,
  15172. // height = table.offsetHeight;
  15173. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  15174. // return "topLeft";
  15175. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  15176. // return "bottomRight";
  15177. // }
  15178. // }
  15179. function inTableSide(table, cell, evt, top) {
  15180. var pos = mouseCoords(evt),
  15181. state = getRelation(cell, pos);
  15182. if (top) {
  15183. var caption = table.getElementsByTagName("caption")[0],
  15184. capHeight = caption ? caption.offsetHeight : 0;
  15185. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  15186. } else {
  15187. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  15188. }
  15189. }
  15190. /**
  15191. * 获取拖动时允许的X轴坐标
  15192. * @param dragTd
  15193. * @param evt
  15194. */
  15195. function getPermissionX(dragTd, evt) {
  15196. var ut = getUETable(dragTd);
  15197. if (ut) {
  15198. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  15199. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  15200. mouseX = mouseCoords(evt).x,
  15201. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  15202. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  15203. left += cellMinWidth;
  15204. right -= cellMinWidth;
  15205. return mouseX < left ? left : mouseX > right ? right : mouseX;
  15206. }
  15207. }
  15208. /**
  15209. * 获取拖动时允许的Y轴坐标
  15210. */
  15211. function getPermissionY(dragTd, evt) {
  15212. try {
  15213. var top = domUtils.getXY(dragTd).y,
  15214. mousePosY = mouseCoords(evt).y;
  15215. return mousePosY < top ? top : mousePosY;
  15216. } catch (e) {
  15217. showError(e);
  15218. }
  15219. }
  15220. /**
  15221. * 移动状态切换
  15222. */
  15223. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  15224. try {
  15225. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  15226. if (browser.ie) {
  15227. if (dir && !mousedown && !getUETableBySelected(editor)) {
  15228. getDragLine(editor, editor.document);
  15229. showDragLineAt(dir, cell);
  15230. } else {
  15231. hideDragLine(editor)
  15232. }
  15233. }
  15234. onBorder = draggable;
  15235. } catch (e) {
  15236. showError(e);
  15237. }
  15238. }
  15239. /**
  15240. * 获取与UETable相关的resize line
  15241. * @param uetable UETable对象
  15242. */
  15243. function getResizeLineByUETable() {
  15244. var lineId = '_UETableResizeLine',
  15245. line = this.document.getElementById( lineId );
  15246. if( !line ) {
  15247. line = this.document.createElement("div");
  15248. line.id = lineId;
  15249. line.contnetEditable = false;
  15250. line.setAttribute("unselectable", "on");
  15251. var styles = {
  15252. width: 2*cellBorderWidth + 1 + 'px',
  15253. position: 'absolute',
  15254. 'z-index': 100000,
  15255. cursor: 'col-resize',
  15256. background: 'red',
  15257. display: 'none'
  15258. };
  15259. //切换状态
  15260. line.onmouseout = function(){
  15261. this.style.display = 'none';
  15262. };
  15263. utils.extend( line.style, styles );
  15264. this.document.body.appendChild( line );
  15265. }
  15266. return line;
  15267. }
  15268. /**
  15269. * 更新resize-line
  15270. */
  15271. function updateResizeLine( cell, uetable ) {
  15272. var line = getResizeLineByUETable.call( this ),
  15273. table = uetable.table,
  15274. styles = {
  15275. top: domUtils.getXY( table ).y + 'px',
  15276. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  15277. display: 'block',
  15278. height: table.offsetHeight + 'px'
  15279. };
  15280. utils.extend( line.style, styles );
  15281. }
  15282. /**
  15283. * 显示resize-line
  15284. */
  15285. function showResizeLine( cell ) {
  15286. var uetable = getUETable( cell );
  15287. updateResizeLine.call( this, cell, uetable );
  15288. }
  15289. /**
  15290. * 获取鼠标与当前单元格的相对位置
  15291. * @param ele
  15292. * @param mousePos
  15293. */
  15294. function getRelation(ele, mousePos) {
  15295. var elePos = domUtils.getXY(ele);
  15296. if( !elePos ) {
  15297. return '';
  15298. }
  15299. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  15300. return "h";
  15301. }
  15302. if (mousePos.x - elePos.x < cellBorderWidth) {
  15303. return 'h1'
  15304. }
  15305. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  15306. return "v";
  15307. }
  15308. if (mousePos.y - elePos.y < cellBorderWidth) {
  15309. return 'v1'
  15310. }
  15311. return '';
  15312. }
  15313. function mouseDownEvent(type, evt) {
  15314. if( isEditorDisabled() ) {
  15315. return ;
  15316. }
  15317. userActionStatus = {
  15318. x: evt.clientX,
  15319. y: evt.clientY
  15320. };
  15321. //右键菜单单独处理
  15322. if (evt.button == 2) {
  15323. var ut = getUETableBySelected(me),
  15324. flag = false;
  15325. if (ut) {
  15326. var td = getTargetTd(me, evt);
  15327. utils.each(ut.selectedTds, function (ti) {
  15328. if (ti === td) {
  15329. flag = true;
  15330. }
  15331. });
  15332. if (!flag) {
  15333. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  15334. ut.clearSelected()
  15335. } else {
  15336. td = ut.selectedTds[0];
  15337. setTimeout(function () {
  15338. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  15339. }, 0);
  15340. }
  15341. }
  15342. } else {
  15343. tableClickHander( evt );
  15344. }
  15345. }
  15346. //清除表格的计时器
  15347. function clearTableTimer() {
  15348. tabTimer && clearTimeout( tabTimer );
  15349. tabTimer = null;
  15350. }
  15351. //双击收缩
  15352. function tableDbclickHandler(evt) {
  15353. singleClickState = 0;
  15354. evt = evt || me.window.event;
  15355. var target = getParentTdOrTh(evt.target || evt.srcElement);
  15356. if (target) {
  15357. var h;
  15358. if (h = getRelation(target, mouseCoords(evt))) {
  15359. hideDragLine( me );
  15360. if (h == 'h1') {
  15361. h = 'h';
  15362. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  15363. me.execCommand('adaptbywindow');
  15364. } else {
  15365. target = getUETable(target).getPreviewCell(target);
  15366. if (target) {
  15367. var rng = me.selection.getRange();
  15368. rng.selectNodeContents(target).setCursor(true, true)
  15369. }
  15370. }
  15371. }
  15372. if (h == 'h') {
  15373. var ut = getUETable(target),
  15374. table = ut.table,
  15375. cells = getCellsByMoveBorder( target, table, true );
  15376. cells = extractArray( cells, 'left' );
  15377. ut.width = ut.offsetWidth;
  15378. var oldWidth = [],
  15379. newWidth = [];
  15380. utils.each( cells, function( cell ){
  15381. oldWidth.push( cell.offsetWidth );
  15382. } );
  15383. utils.each( cells, function( cell ){
  15384. cell.removeAttribute("width");
  15385. } );
  15386. window.setTimeout( function(){
  15387. //是否允许改变
  15388. var changeable = true;
  15389. utils.each( cells, function( cell, index ){
  15390. var width = cell.offsetWidth;
  15391. if( width > oldWidth[index] ) {
  15392. changeable = false;
  15393. return false;
  15394. }
  15395. newWidth.push( width );
  15396. } );
  15397. var change = changeable ? newWidth : oldWidth;
  15398. utils.each( cells, function( cell, index ){
  15399. cell.width = change[index] - getTabcellSpace();
  15400. } );
  15401. }, 0 );
  15402. // minWidth -= cellMinWidth;
  15403. //
  15404. // table.removeAttribute("width");
  15405. // utils.each(cells, function (cell) {
  15406. // cell.style.width = "";
  15407. // cell.width -= minWidth;
  15408. // });
  15409. }
  15410. }
  15411. }
  15412. }
  15413. function tableClickHander( evt ) {
  15414. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  15415. //trace:3113
  15416. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  15417. utils.each(me.document.getElementsByTagName('table'), function (t) {
  15418. t.ueTable = null;
  15419. });
  15420. startTd = getTargetTd(me, evt);
  15421. if( !startTd ) return;
  15422. var table = domUtils.findParentByTagName(startTd, "table", true);
  15423. ut = getUETable(table);
  15424. ut && ut.clearSelected();
  15425. //判断当前鼠标状态
  15426. if (!onBorder) {
  15427. me.document.body.style.webkitUserSelect = '';
  15428. mousedown = true;
  15429. me.addListener('mouseover', mouseOverEvent);
  15430. } else {
  15431. //边框上的动作处理
  15432. borderActionHandler( evt );
  15433. }
  15434. }
  15435. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  15436. function borderActionHandler( evt ) {
  15437. if ( browser.ie ) {
  15438. evt = reconstruct(evt );
  15439. }
  15440. clearTableDragTimer();
  15441. //是否正在等待resize的缓冲中
  15442. isInResizeBuffer = true;
  15443. tableDragTimer = setTimeout(function(){
  15444. tableBorderDrag( evt );
  15445. }, dblclickTime);
  15446. }
  15447. function extractArray( originArr, key ) {
  15448. var result = [],
  15449. tmp = null;
  15450. for( var i = 0, len = originArr.length; i<len; i++ ) {
  15451. tmp = originArr[ i ][ key ];
  15452. if( tmp ) {
  15453. result.push( tmp );
  15454. }
  15455. }
  15456. return result;
  15457. }
  15458. function clearTableDragTimer() {
  15459. tableDragTimer && clearTimeout(tableDragTimer);
  15460. tableDragTimer = null;
  15461. }
  15462. function reconstruct( obj ) {
  15463. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  15464. newObj = {};
  15465. if( obj ) {
  15466. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  15467. val=obj[ key ];
  15468. val && (newObj[ key ] = val);
  15469. }
  15470. }
  15471. return newObj;
  15472. }
  15473. //边框拖动
  15474. function tableBorderDrag( evt ) {
  15475. isInResizeBuffer = false;
  15476. if( !startTd ) return;
  15477. var state = Math.abs( userActionStatus.x - evt.clientX ) >= Math.abs( userActionStatus.y - evt.clientY ) ? 'h' : 'v';
  15478. // var state = getRelation(startTd, mouseCoords(evt));
  15479. if (/\d/.test(state)) {
  15480. state = state.replace(/\d/, '');
  15481. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  15482. }
  15483. hideDragLine(me);
  15484. getDragLine(me, me.document);
  15485. me.fireEvent('saveScene');
  15486. showDragLineAt(state, startTd);
  15487. mousedown = true;
  15488. //拖动开始
  15489. onDrag = state;
  15490. dragTd = startTd;
  15491. }
  15492. function mouseUpEvent(type, evt) {
  15493. if( isEditorDisabled() ) {
  15494. return ;
  15495. }
  15496. clearTableDragTimer();
  15497. isInResizeBuffer = false;
  15498. if( onBorder ) {
  15499. singleClickState = ++singleClickState % 3;
  15500. userActionStatus = {
  15501. x: evt.clientX,
  15502. y: evt.clientY
  15503. };
  15504. tableResizeTimer = setTimeout(function(){
  15505. singleClickState > 0 && singleClickState--;
  15506. }, dblclickTime );
  15507. if( singleClickState === 2 ) {
  15508. singleClickState = 0;
  15509. tableDbclickHandler(evt);
  15510. return;
  15511. }
  15512. }
  15513. if (evt.button == 2)return;
  15514. var me = this;
  15515. //清除表格上原生跨选问题
  15516. var range = me.selection.getRange(),
  15517. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  15518. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  15519. if (start || end) {
  15520. if (start === end) {
  15521. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  15522. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  15523. if (start !== end) {
  15524. me.selection.clearRange()
  15525. }
  15526. } else {
  15527. me.selection.clearRange()
  15528. }
  15529. }
  15530. mousedown = false;
  15531. me.document.body.style.webkitUserSelect = '';
  15532. //拖拽状态下的mouseUP
  15533. if ( onDrag && dragTd ) {
  15534. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  15535. singleClickState = 0;
  15536. dragLine = me.document.getElementById('ue_tableDragLine');
  15537. var dragTdPos = domUtils.getXY(dragTd),
  15538. dragLinePos = domUtils.getXY(dragLine);
  15539. switch (onDrag) {
  15540. case "h":
  15541. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  15542. break;
  15543. case "v":
  15544. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  15545. break;
  15546. default:
  15547. }
  15548. onDrag = "";
  15549. dragTd = null;
  15550. hideDragLine(me);
  15551. me.fireEvent('saveScene');
  15552. return;
  15553. }
  15554. //正常状态下的mouseup
  15555. if (!startTd) {
  15556. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  15557. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  15558. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  15559. if (me.fireEvent("excludetable", target) === true) return;
  15560. range = new dom.Range(me.document);
  15561. range.setStart(target, 0).setCursor(false, true);
  15562. }
  15563. } else {
  15564. var ut = getUETable(startTd),
  15565. cell = ut ? ut.selectedTds[0] : null;
  15566. if (cell) {
  15567. range = new dom.Range(me.document);
  15568. if (domUtils.isEmptyBlock(cell)) {
  15569. range.setStart(cell, 0).setCursor(false, true);
  15570. } else {
  15571. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  15572. }
  15573. } else {
  15574. range = me.selection.getRange().shrinkBoundary();
  15575. if (!range.collapsed) {
  15576. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  15577. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  15578. //在table里边的不能清除
  15579. if (start && !end || !start && end || start && end && start !== end) {
  15580. range.setCursor(false, true);
  15581. }
  15582. }
  15583. }
  15584. startTd = null;
  15585. me.removeListener('mouseover', mouseOverEvent);
  15586. }
  15587. me._selectionChange(250, evt);
  15588. }
  15589. function mouseOverEvent(type, evt) {
  15590. if( isEditorDisabled() ) {
  15591. return;
  15592. }
  15593. var me = this,
  15594. tar = evt.target || evt.srcElement;
  15595. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  15596. //需要判断两个TD是否位于同一个表格内
  15597. if (startTd && currentTd &&
  15598. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  15599. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  15600. var ut = getUETable(currentTd);
  15601. if (startTd != currentTd) {
  15602. me.document.body.style.webkitUserSelect = 'none';
  15603. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  15604. var range = ut.getCellsRange(startTd, currentTd);
  15605. ut.setSelected(range);
  15606. } else {
  15607. me.document.body.style.webkitUserSelect = '';
  15608. ut.clearSelected();
  15609. }
  15610. }
  15611. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  15612. }
  15613. function setCellHeight(cell, height, backHeight) {
  15614. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  15615. tmpHeight = backHeight + height;
  15616. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  15617. if (cell.style.height) cell.style.height = "";
  15618. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  15619. }
  15620. function getWidth(cell) {
  15621. if (!cell)return 0;
  15622. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  15623. }
  15624. function changeColWidth(cell, changeValue) {
  15625. var ut = getUETable(cell);
  15626. if (ut) {
  15627. //根据当前移动的边框获取相关的单元格
  15628. var table = ut.table,
  15629. cells = getCellsByMoveBorder( cell, table );
  15630. table.style.width = "";
  15631. table.removeAttribute("width");
  15632. //修正改变量
  15633. changeValue = correctChangeValue( changeValue, cell, cells );
  15634. if (cell.nextSibling) {
  15635. var i=0;
  15636. utils.each( cells, function( cellGroup ){
  15637. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  15638. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  15639. } );
  15640. } else {
  15641. utils.each( cells, function( cellGroup ){
  15642. cellGroup.left.width -= -changeValue;
  15643. } );
  15644. }
  15645. }
  15646. }
  15647. function isEditorDisabled() {
  15648. return me.body.contentEditable === "false";
  15649. }
  15650. function changeRowHeight(td, changeValue) {
  15651. if (Math.abs(changeValue) < 10) return;
  15652. var ut = getUETable(td);
  15653. if (ut) {
  15654. var cells = ut.getSameEndPosCells(td, "y"),
  15655. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  15656. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  15657. for (var i = 0, cell; cell = cells[i++];) {
  15658. setCellHeight(cell, changeValue, backHeight);
  15659. }
  15660. }
  15661. }
  15662. /**
  15663. * 获取调整单元格大小的相关单元格
  15664. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  15665. */
  15666. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  15667. if( !table ) {
  15668. table = domUtils.findParentByTagName( cell, 'table' );
  15669. }
  15670. if( !table ) {
  15671. return null;
  15672. }
  15673. //获取到该单元格所在行的序列号
  15674. var index = domUtils.getNodeIndex( cell ),
  15675. temp = cell,
  15676. rows = table.rows,
  15677. colIndex = 0;
  15678. while( temp ) {
  15679. //获取到当前单元格在未发生单元格合并时的序列
  15680. if( temp.nodeType === 1 ) {
  15681. colIndex += (temp.colSpan || 1);
  15682. }
  15683. temp = temp.previousSibling;
  15684. }
  15685. temp = null;
  15686. //记录想关的单元格
  15687. var borderCells = [];
  15688. utils.each(rows, function( tabRow ){
  15689. var cells = tabRow.cells,
  15690. currIndex = 0;
  15691. utils.each( cells, function( tabCell ){
  15692. currIndex += (tabCell.colSpan || 1);
  15693. if( currIndex === colIndex ) {
  15694. borderCells.push({
  15695. left: tabCell,
  15696. right: tabCell.nextSibling || null
  15697. });
  15698. return false;
  15699. } else if( currIndex > colIndex ) {
  15700. if( isContainMergeCell ) {
  15701. borderCells.push({
  15702. left: tabCell
  15703. });
  15704. }
  15705. return false;
  15706. }
  15707. } );
  15708. });
  15709. return borderCells;
  15710. }
  15711. /**
  15712. * 通过给定的单元格集合获取最小的单元格width
  15713. */
  15714. function getMinWidthByTableCells( cells ) {
  15715. var minWidth = Number.MAX_VALUE;
  15716. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  15717. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  15718. }
  15719. return minWidth;
  15720. }
  15721. function correctChangeValue( changeValue, relatedCell, cells ) {
  15722. //为单元格的paading预留空间
  15723. changeValue -= getTabcellSpace();
  15724. if( changeValue < 0 ) {
  15725. return 0;
  15726. }
  15727. changeValue -= getTableCellWidth( relatedCell );
  15728. //确定方向
  15729. var direction = changeValue < 0 ? 'left':'right';
  15730. changeValue = Math.abs(changeValue);
  15731. //只关心非最后一个单元格就可以
  15732. utils.each( cells, function( cellGroup ){
  15733. var curCell = cellGroup[direction];
  15734. //为单元格保留最小空间
  15735. if( curCell ) {
  15736. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  15737. }
  15738. } );
  15739. //修正越界
  15740. changeValue = changeValue < 0 ? 0 : changeValue;
  15741. return direction === 'left' ? -changeValue : changeValue;
  15742. }
  15743. function getTableCellWidth( cell ) {
  15744. var width = 0,
  15745. //偏移纠正量
  15746. offset = 0,
  15747. width = cell.offsetWidth - getTabcellSpace();
  15748. //最后一个节点纠正一下
  15749. if( !cell.nextSibling ) {
  15750. width -= getTableCellOffset( cell );
  15751. }
  15752. width = width < 0 ? 0 : width;
  15753. try {
  15754. cell.width = width;
  15755. } catch(e) {
  15756. }
  15757. return width;
  15758. }
  15759. /**
  15760. * 获取单元格所在表格的最末单元格的偏移量
  15761. */
  15762. function getTableCellOffset( cell ) {
  15763. tab = domUtils.findParentByTagName( cell, "table", false);
  15764. if( tab.offsetVal === undefined ) {
  15765. var prev = cell.previousSibling;
  15766. if( prev ) {
  15767. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  15768. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  15769. } else {
  15770. tab.offsetVal = 0;
  15771. }
  15772. }
  15773. return tab.offsetVal;
  15774. }
  15775. function getTabcellSpace() {
  15776. if( UT.tabcellSpace === undefined ) {
  15777. var cell = null,
  15778. tab = me.document.createElement("table"),
  15779. tbody = me.document.createElement("tbody"),
  15780. trow = me.document.createElement("tr"),
  15781. tabcell = me.document.createElement("td"),
  15782. mirror = null;
  15783. tabcell.style.cssText = 'border: 0;';
  15784. tabcell.width = 1;
  15785. trow.appendChild( tabcell );
  15786. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  15787. tbody.appendChild( trow );
  15788. tab.appendChild( tbody );
  15789. tab.style.cssText = "visibility: hidden;";
  15790. me.body.appendChild( tab );
  15791. UT.paddingSpace = tabcell.offsetWidth - 1;
  15792. var tmpTabWidth = tab.offsetWidth;
  15793. tabcell.style.cssText = '';
  15794. mirror.style.cssText = '';
  15795. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  15796. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  15797. me.body.removeChild( tab );
  15798. }
  15799. getTabcellSpace = function(){ return UT.tabcellSpace; };
  15800. return UT.tabcellSpace;
  15801. }
  15802. function getDragLine(editor, doc) {
  15803. if (mousedown)return;
  15804. dragLine = editor.document.createElement("div");
  15805. domUtils.setAttributes(dragLine, {
  15806. id:"ue_tableDragLine",
  15807. unselectable:'on',
  15808. contenteditable:false,
  15809. 'onresizestart':'return false',
  15810. 'ondragstart':'return false',
  15811. 'onselectstart':'return false',
  15812. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  15813. });
  15814. editor.body.appendChild(dragLine);
  15815. }
  15816. function hideDragLine(editor) {
  15817. if (mousedown)return;
  15818. var line;
  15819. while (line = editor.document.getElementById('ue_tableDragLine')) {
  15820. domUtils.remove(line)
  15821. }
  15822. }
  15823. /**
  15824. * 依据state(v|h)在cell位置显示横线
  15825. * @param state
  15826. * @param cell
  15827. */
  15828. function showDragLineAt(state, cell) {
  15829. if (!cell) return;
  15830. var table = domUtils.findParentByTagName(cell, "table"),
  15831. caption = table.getElementsByTagName('caption'),
  15832. width = table.offsetWidth,
  15833. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  15834. tablePos = domUtils.getXY(table),
  15835. cellPos = domUtils.getXY(cell), css;
  15836. switch (state) {
  15837. case "h":
  15838. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  15839. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  15840. break;
  15841. case "v":
  15842. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  15843. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  15844. 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)';
  15845. break;
  15846. default:
  15847. }
  15848. }
  15849. /**
  15850. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  15851. * @param editor
  15852. * @param flag
  15853. */
  15854. function switchBorderColor(editor, flag) {
  15855. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  15856. for (var i = 0, node; node = tableArr[i++];) {
  15857. var td = domUtils.getElementsByTagName(node, "td");
  15858. if (td[0]) {
  15859. if (flag) {
  15860. color = (td[0].style.borderColor).replace(/\s/g, "");
  15861. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  15862. domUtils.addClass(node, "noBorderTable")
  15863. } else {
  15864. domUtils.removeClasses(node, "noBorderTable")
  15865. }
  15866. }
  15867. }
  15868. }
  15869. function getTableWidth(editor, needIEHack, defaultValue) {
  15870. var body = editor.body;
  15871. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  15872. }
  15873. /**
  15874. * 获取当前拖动的单元格
  15875. */
  15876. function getTargetTd(editor, evt) {
  15877. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  15878. dir = null;
  15879. if( !target ) {
  15880. return null;
  15881. }
  15882. dir = getRelation( target, mouseCoords( evt ) );
  15883. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  15884. if( !target ) {
  15885. return null;
  15886. }
  15887. if( dir === 'h1' && target.previousSibling ) {
  15888. var position = domUtils.getXY( target),
  15889. cellWidth = target.offsetWidth;
  15890. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  15891. target = target.previousSibling;
  15892. }
  15893. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  15894. var position = domUtils.getXY( target),
  15895. cellHeight = target.offsetHeight;
  15896. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  15897. target = target.parentNode.previousSibling.firstChild;
  15898. }
  15899. }
  15900. //排除了非td内部以及用于代码高亮部分的td
  15901. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  15902. }
  15903. };
  15904. /**
  15905. * Created with JetBrains PhpStorm.
  15906. * User: Jinqn
  15907. * Date: 13-10-12
  15908. * Time: 上午10:20
  15909. * To change this template use File | Settings | File Templates.
  15910. */
  15911. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  15912. var table = this.table,
  15913. rows = table.rows,
  15914. trArray = [],
  15915. flag = rows[0].cells[0].tagName === "TH",
  15916. lastRowIndex = 0;
  15917. if(this.selectedTds.length){
  15918. var range = this.cellsRange,
  15919. len = range.endRowIndex + 1;
  15920. for (var i = range.beginRowIndex; i < len; i++) {
  15921. trArray[i] = rows[i];
  15922. }
  15923. trArray.splice(0,range.beginRowIndex);
  15924. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  15925. }else{
  15926. for (var i = 0,len = rows.length; i < len; i++) {
  15927. trArray[i] = rows[i];
  15928. }
  15929. }
  15930. var Fn = {
  15931. 'reversecurrent': function(td1,td2){
  15932. return 1;
  15933. },
  15934. 'orderbyasc': function(td1,td2){
  15935. var value1 = td1.innerText||td1.textContent,
  15936. value2 = td2.innerText||td2.textContent;
  15937. return value1.localeCompare(value2);
  15938. },
  15939. 'reversebyasc': function(td1,td2){
  15940. var value1 = td1.innerHTML,
  15941. value2 = td2.innerHTML;
  15942. return value2.localeCompare(value1);
  15943. },
  15944. 'orderbynum': function(td1,td2){
  15945. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  15946. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  15947. if(value1) value1 = +value1[0];
  15948. if(value2) value2 = +value2[0];
  15949. return (value1||0) - (value2||0);
  15950. },
  15951. 'reversebynum': function(td1,td2){
  15952. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  15953. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  15954. if(value1) value1 = +value1[0];
  15955. if(value2) value2 = +value2[0];
  15956. return (value2||0) - (value1||0);
  15957. }
  15958. };
  15959. //对表格设置排序的标记data-sort-type
  15960. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  15961. //th不参与排序
  15962. flag && trArray.splice(0, 1);
  15963. trArray = utils.sort(trArray,function (tr1, tr2) {
  15964. var result;
  15965. if (compareFn && typeof compareFn === "function") {
  15966. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  15967. } else if (compareFn && typeof compareFn === "number") {
  15968. result = 1;
  15969. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  15970. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  15971. } else {
  15972. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  15973. }
  15974. return result;
  15975. });
  15976. var fragment = table.ownerDocument.createDocumentFragment();
  15977. for (var j = 0, len = trArray.length; j < len; j++) {
  15978. fragment.appendChild(trArray[j]);
  15979. }
  15980. var tbody = table.getElementsByTagName("tbody")[0];
  15981. if(!lastRowIndex){
  15982. tbody.appendChild(fragment);
  15983. }else{
  15984. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  15985. }
  15986. };
  15987. UE.plugins['tablesort'] = function () {
  15988. var me = this,
  15989. UT = UE.UETable,
  15990. getUETable = function (tdOrTable) {
  15991. return UT.getUETable(tdOrTable);
  15992. },
  15993. getTableItemsByRange = function (editor) {
  15994. return UT.getTableItemsByRange(editor);
  15995. };
  15996. me.ready(function () {
  15997. //添加表格可排序的样式
  15998. utils.cssRule('tablesort',
  15999. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  16000. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  16001. me.document);
  16002. //做单元格合并操作时,清除可排序标识
  16003. me.addListener("afterexeccommand", function (type, cmd) {
  16004. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  16005. this.execCommand('disablesort');
  16006. }
  16007. });
  16008. });
  16009. //表格排序
  16010. UE.commands['sorttable'] = {
  16011. queryCommandState: function () {
  16012. var me = this,
  16013. tableItems = getTableItemsByRange(me);
  16014. if (!tableItems.cell) return -1;
  16015. var table = tableItems.table,
  16016. cells = table.getElementsByTagName("td");
  16017. for (var i = 0, cell; cell = cells[i++];) {
  16018. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  16019. }
  16020. return 0;
  16021. },
  16022. execCommand: function (cmd, fn) {
  16023. var me = this,
  16024. range = me.selection.getRange(),
  16025. bk = range.createBookmark(true),
  16026. tableItems = getTableItemsByRange(me),
  16027. cell = tableItems.cell,
  16028. ut = getUETable(tableItems.table),
  16029. cellInfo = ut.getCellInfo(cell);
  16030. ut.sortTable(cellInfo.cellIndex, fn);
  16031. range.moveToBookmark(bk);
  16032. try{
  16033. range.select();
  16034. }catch(e){}
  16035. }
  16036. };
  16037. //设置表格可排序,清除表格可排序
  16038. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  16039. queryCommandState: function (cmd) {
  16040. var table = getTableItemsByRange(this).table;
  16041. if(table && cmd=='enablesort') {
  16042. var cells = domUtils.getElementsByTagName(table, 'th td');
  16043. for(var i = 0; i<cells.length; i++) {
  16044. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  16045. }
  16046. }
  16047. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  16048. },
  16049. execCommand: function (cmd) {
  16050. var table = getTableItemsByRange(this).table;
  16051. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  16052. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  16053. }
  16054. };
  16055. };
  16056. ///import core
  16057. ///commands 右键菜单
  16058. ///commandsName ContextMenu
  16059. ///commandsTitle 右键菜单
  16060. /*
  16061. * 右键菜单
  16062. * @function
  16063. * @name baidu.editor.plugins.contextmenu
  16064. * @author zhanyi
  16065. */
  16066. UE.plugins['contextmenu'] = function () {
  16067. var me = this,
  16068. lang = me.getLang( "contextMenu" ),
  16069. menu,
  16070. items = me.options.contextMenu || [
  16071. {label:lang['selectall'], cmdName:'selectall'},
  16072. {
  16073. label:lang.cleardoc,
  16074. cmdName:'cleardoc',
  16075. exec:function () {
  16076. if ( confirm( lang.confirmclear ) ) {
  16077. this.execCommand( 'cleardoc' );
  16078. }
  16079. }
  16080. },
  16081. '-',
  16082. {
  16083. label:lang.unlink,
  16084. cmdName:'unlink'
  16085. },
  16086. '-',
  16087. {
  16088. group:lang.paragraph,
  16089. icon:'justifyjustify',
  16090. subMenu:[
  16091. {
  16092. label:lang.justifyleft,
  16093. cmdName:'justify',
  16094. value:'left'
  16095. },
  16096. {
  16097. label:lang.justifyright,
  16098. cmdName:'justify',
  16099. value:'right'
  16100. },
  16101. {
  16102. label:lang.justifycenter,
  16103. cmdName:'justify',
  16104. value:'center'
  16105. },
  16106. {
  16107. label:lang.justifyjustify,
  16108. cmdName:'justify',
  16109. value:'justify'
  16110. }
  16111. ]
  16112. },
  16113. '-',
  16114. {
  16115. group:lang.table,
  16116. icon:'table',
  16117. subMenu:[
  16118. {
  16119. label:lang.inserttable,
  16120. cmdName:'inserttable'
  16121. },
  16122. {
  16123. label:lang.deletetable,
  16124. cmdName:'deletetable'
  16125. },
  16126. '-',
  16127. {
  16128. label:lang.deleterow,
  16129. cmdName:'deleterow'
  16130. },
  16131. {
  16132. label:lang.deletecol,
  16133. cmdName:'deletecol'
  16134. },
  16135. {
  16136. label:lang.insertcol,
  16137. cmdName:'insertcol'
  16138. },
  16139. {
  16140. label:lang.insertcolnext,
  16141. cmdName:'insertcolnext'
  16142. },
  16143. {
  16144. label:lang.insertrow,
  16145. cmdName:'insertrow'
  16146. },
  16147. {
  16148. label:lang.insertrownext,
  16149. cmdName:'insertrownext'
  16150. },
  16151. '-',
  16152. {
  16153. label:lang.insertcaption,
  16154. cmdName:'insertcaption'
  16155. },
  16156. {
  16157. label:lang.deletecaption,
  16158. cmdName:'deletecaption'
  16159. },
  16160. {
  16161. label:lang.inserttitle,
  16162. cmdName:'inserttitle'
  16163. },
  16164. {
  16165. label:lang.deletetitle,
  16166. cmdName:'deletetitle'
  16167. },
  16168. {
  16169. label:lang.inserttitlecol,
  16170. cmdName:'inserttitlecol'
  16171. },
  16172. {
  16173. label:lang.deletetitlecol,
  16174. cmdName:'deletetitlecol'
  16175. },
  16176. '-',
  16177. {
  16178. label:lang.mergecells,
  16179. cmdName:'mergecells'
  16180. },
  16181. {
  16182. label:lang.mergeright,
  16183. cmdName:'mergeright'
  16184. },
  16185. {
  16186. label:lang.mergedown,
  16187. cmdName:'mergedown'
  16188. },
  16189. '-',
  16190. {
  16191. label:lang.splittorows,
  16192. cmdName:'splittorows'
  16193. },
  16194. {
  16195. label:lang.splittocols,
  16196. cmdName:'splittocols'
  16197. },
  16198. {
  16199. label:lang.splittocells,
  16200. cmdName:'splittocells'
  16201. },
  16202. '-',
  16203. {
  16204. label:lang.averageDiseRow,
  16205. cmdName:'averagedistributerow'
  16206. },
  16207. {
  16208. label:lang.averageDisCol,
  16209. cmdName:'averagedistributecol'
  16210. },
  16211. '-',
  16212. {
  16213. label:lang.edittd,
  16214. cmdName:'edittd',
  16215. exec:function () {
  16216. if ( UE.ui['edittd'] ) {
  16217. new UE.ui['edittd']( this );
  16218. }
  16219. this.getDialog('edittd').open();
  16220. }
  16221. },
  16222. {
  16223. label:lang.edittable,
  16224. cmdName:'edittable',
  16225. exec:function () {
  16226. if ( UE.ui['edittable'] ) {
  16227. new UE.ui['edittable']( this );
  16228. }
  16229. this.getDialog('edittable').open();
  16230. }
  16231. },
  16232. {
  16233. label:lang.setbordervisible,
  16234. cmdName:'setbordervisible'
  16235. }
  16236. ]
  16237. },
  16238. {
  16239. group:lang.tablesort,
  16240. icon:'tablesort',
  16241. subMenu:[
  16242. {
  16243. label:lang.enablesort,
  16244. cmdName:'enablesort'
  16245. },
  16246. {
  16247. label:lang.disablesort,
  16248. cmdName:'disablesort'
  16249. },
  16250. '-',
  16251. {
  16252. label:lang.reversecurrent,
  16253. cmdName:'sorttable',
  16254. value:'reversecurrent'
  16255. },
  16256. {
  16257. label:lang.orderbyasc,
  16258. cmdName:'sorttable',
  16259. value:'orderbyasc'
  16260. },
  16261. {
  16262. label:lang.reversebyasc,
  16263. cmdName:'sorttable',
  16264. value:'reversebyasc'
  16265. },
  16266. {
  16267. label:lang.orderbynum,
  16268. cmdName:'sorttable',
  16269. value:'orderbynum'
  16270. },
  16271. {
  16272. label:lang.reversebynum,
  16273. cmdName:'sorttable',
  16274. value:'reversebynum'
  16275. }
  16276. ]
  16277. },
  16278. {
  16279. group:lang.borderbk,
  16280. icon:'borderBack',
  16281. subMenu:[
  16282. {
  16283. label:lang.setcolor,
  16284. cmdName:"interlacetable",
  16285. exec:function(){
  16286. this.execCommand("interlacetable");
  16287. }
  16288. },
  16289. {
  16290. label:lang.unsetcolor,
  16291. cmdName:"uninterlacetable",
  16292. exec:function(){
  16293. this.execCommand("uninterlacetable");
  16294. }
  16295. },
  16296. {
  16297. label:lang.setbackground,
  16298. cmdName:"settablebackground",
  16299. exec:function(){
  16300. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  16301. }
  16302. },
  16303. {
  16304. label:lang.unsetbackground,
  16305. cmdName:"cleartablebackground",
  16306. exec:function(){
  16307. this.execCommand("cleartablebackground");
  16308. }
  16309. },
  16310. {
  16311. label:lang.redandblue,
  16312. cmdName:"settablebackground",
  16313. exec:function(){
  16314. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  16315. }
  16316. },
  16317. {
  16318. label:lang.threecolorgradient,
  16319. cmdName:"settablebackground",
  16320. exec:function(){
  16321. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  16322. }
  16323. }
  16324. ]
  16325. },
  16326. {
  16327. group:lang.aligntd,
  16328. icon:'aligntd',
  16329. subMenu:[
  16330. {
  16331. cmdName:'cellalignment',
  16332. value:{align:'left',vAlign:'top'}
  16333. },
  16334. {
  16335. cmdName:'cellalignment',
  16336. value:{align:'center',vAlign:'top'}
  16337. },
  16338. {
  16339. cmdName:'cellalignment',
  16340. value:{align:'right',vAlign:'top'}
  16341. },
  16342. {
  16343. cmdName:'cellalignment',
  16344. value:{align:'left',vAlign:'middle'}
  16345. },
  16346. {
  16347. cmdName:'cellalignment',
  16348. value:{align:'center',vAlign:'middle'}
  16349. },
  16350. {
  16351. cmdName:'cellalignment',
  16352. value:{align:'right',vAlign:'middle'}
  16353. },
  16354. {
  16355. cmdName:'cellalignment',
  16356. value:{align:'left',vAlign:'bottom'}
  16357. },
  16358. {
  16359. cmdName:'cellalignment',
  16360. value:{align:'center',vAlign:'bottom'}
  16361. },
  16362. {
  16363. cmdName:'cellalignment',
  16364. value:{align:'right',vAlign:'bottom'}
  16365. }
  16366. ]
  16367. },
  16368. {
  16369. group:lang.aligntable,
  16370. icon:'aligntable',
  16371. subMenu:[
  16372. {
  16373. cmdName:'tablealignment',
  16374. className: 'left',
  16375. label:lang.tableleft,
  16376. value:"left"
  16377. },
  16378. {
  16379. cmdName:'tablealignment',
  16380. className: 'center',
  16381. label:lang.tablecenter,
  16382. value:"center"
  16383. },
  16384. {
  16385. cmdName:'tablealignment',
  16386. className: 'right',
  16387. label:lang.tableright,
  16388. value:"right"
  16389. }
  16390. ]
  16391. },
  16392. '-',
  16393. {
  16394. label:lang.insertparagraphbefore,
  16395. cmdName:'insertparagraph',
  16396. value:true
  16397. },
  16398. {
  16399. label:lang.insertparagraphafter,
  16400. cmdName:'insertparagraph'
  16401. },
  16402. {
  16403. label:lang['copy'],
  16404. cmdName:'copy',
  16405. exec:function () {
  16406. alert( lang.copymsg );
  16407. },
  16408. query:function () {
  16409. return 0;
  16410. }
  16411. },
  16412. {
  16413. label:lang['paste'],
  16414. cmdName:'paste',
  16415. exec:function () {
  16416. alert( lang.pastemsg );
  16417. },
  16418. query:function () {
  16419. return 0;
  16420. }
  16421. }
  16422. ];
  16423. if ( !items.length ) {
  16424. return;
  16425. }
  16426. var uiUtils = UE.ui.uiUtils;
  16427. me.addListener( 'contextmenu', function ( type, evt ) {
  16428. var offset = uiUtils.getViewportOffsetByEvent( evt );
  16429. me.fireEvent( 'beforeselectionchange' );
  16430. if ( menu ) {
  16431. menu.destroy();
  16432. }
  16433. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  16434. var last;
  16435. (function ( item ) {
  16436. if ( item == '-' ) {
  16437. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  16438. contextItems.push( '-' );
  16439. }
  16440. } else if ( item.hasOwnProperty( "group" ) ) {
  16441. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  16442. (function ( subItem ) {
  16443. if ( subItem == '-' ) {
  16444. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  16445. subMenu.push( '-' );
  16446. }else{
  16447. subMenu.splice(subMenu.length-1);
  16448. }
  16449. } else {
  16450. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  16451. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  16452. subMenu.push( {
  16453. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  16454. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  16455. onclick:subItem.exec ? function () {
  16456. subItem.exec.call( me );
  16457. } : function () {
  16458. me.execCommand( subItem.cmdName, subItem.value );
  16459. }
  16460. } );
  16461. }
  16462. }
  16463. })( cj );
  16464. }
  16465. if ( subMenu.length ) {
  16466. function getLabel(){
  16467. switch (item.icon){
  16468. case "table":
  16469. return me.getLang( "contextMenu.table" );
  16470. case "justifyjustify":
  16471. return me.getLang( "contextMenu.paragraph" );
  16472. case "aligntd":
  16473. return me.getLang("contextMenu.aligntd");
  16474. case "aligntable":
  16475. return me.getLang("contextMenu.aligntable");
  16476. case "tablesort":
  16477. return lang.tablesort;
  16478. case "borderBack":
  16479. return lang.borderbk;
  16480. default :
  16481. return '';
  16482. }
  16483. }
  16484. contextItems.push( {
  16485. //todo 修正成自动获取方式
  16486. 'label':getLabel(),
  16487. className:'edui-for-' + item.icon,
  16488. 'subMenu':{
  16489. items:subMenu,
  16490. editor:me
  16491. }
  16492. } );
  16493. }
  16494. } else {
  16495. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  16496. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  16497. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  16498. contextItems.push( {
  16499. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  16500. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  16501. onclick:item.exec ? function () {
  16502. item.exec.call( me );
  16503. } : function () {
  16504. me.execCommand( item.cmdName, item.value );
  16505. }
  16506. } );
  16507. }
  16508. }
  16509. })( ti );
  16510. }
  16511. if ( contextItems[contextItems.length - 1] == '-' ) {
  16512. contextItems.pop();
  16513. }
  16514. menu = new UE.ui.Menu( {
  16515. items:contextItems,
  16516. className:"edui-contextmenu",
  16517. editor:me
  16518. } );
  16519. menu.render();
  16520. menu.showAt( offset );
  16521. me.fireEvent("aftershowcontextmenu",menu);
  16522. domUtils.preventDefault( evt );
  16523. if ( browser.ie ) {
  16524. var ieRange;
  16525. try {
  16526. ieRange = me.selection.getNative().createRange();
  16527. } catch ( e ) {
  16528. return;
  16529. }
  16530. if ( ieRange.item ) {
  16531. var range = new dom.Range( me.document );
  16532. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  16533. }
  16534. }
  16535. } );
  16536. };
  16537. /**
  16538. * B、I、sub、super命令支持
  16539. * @file
  16540. * @since 1.2.6.1
  16541. */
  16542. UE.plugins['basestyle'] = function(){
  16543. /**
  16544. * 字体加粗
  16545. * @command bold
  16546. * @param { String } cmd 命令字符串
  16547. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  16548. * @method execCommand
  16549. * @example
  16550. * ```javascript
  16551. * //editor是编辑器实例
  16552. * //对当前选中的文本内容执行加粗操作
  16553. * //第一次执行, 文本内容加粗
  16554. * editor.execCommand( 'bold' );
  16555. *
  16556. * //第二次执行, 文本内容取消加粗
  16557. * editor.execCommand( 'bold' );
  16558. * ```
  16559. */
  16560. /**
  16561. * 字体倾斜
  16562. * @command italic
  16563. * @method execCommand
  16564. * @param { String } cmd 命令字符串
  16565. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  16566. * @example
  16567. * ```javascript
  16568. * //editor是编辑器实例
  16569. * //对当前选中的文本内容执行斜体操作
  16570. * //第一次操作, 文本内容将变成斜体
  16571. * editor.execCommand( 'italic' );
  16572. *
  16573. * //再次对同一文本内容执行, 则文本内容将恢复正常
  16574. * editor.execCommand( 'italic' );
  16575. * ```
  16576. */
  16577. /**
  16578. * 下标文本,与“superscript”命令互斥
  16579. * @command subscript
  16580. * @method execCommand
  16581. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  16582. * @param { String } cmd 命令字符串
  16583. * @example
  16584. * ```javascript
  16585. * //editor是编辑器实例
  16586. * //对当前选中的文本内容执行下标操作
  16587. * //第一次操作, 文本内容将变成下标文本
  16588. * editor.execCommand( 'subscript' );
  16589. *
  16590. * //再次对同一文本内容执行, 则文本内容将恢复正常
  16591. * editor.execCommand( 'subscript' );
  16592. * ```
  16593. */
  16594. /**
  16595. * 上标文本,与“subscript”命令互斥
  16596. * @command superscript
  16597. * @method execCommand
  16598. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  16599. * @param { String } cmd 命令字符串
  16600. * @example
  16601. * ```javascript
  16602. * //editor是编辑器实例
  16603. * //对当前选中的文本内容执行上标操作
  16604. * //第一次操作, 文本内容将变成上标文本
  16605. * editor.execCommand( 'superscript' );
  16606. *
  16607. * //再次对同一文本内容执行, 则文本内容将恢复正常
  16608. * editor.execCommand( 'superscript' );
  16609. * ```
  16610. */
  16611. var basestyles = {
  16612. 'bold':['strong','b'],
  16613. 'italic':['em','i'],
  16614. 'subscript':['sub'],
  16615. 'superscript':['sup']
  16616. },
  16617. getObj = function(editor,tagNames){
  16618. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  16619. },
  16620. me = this;
  16621. //添加快捷键
  16622. me.addshortcutkey({
  16623. "Bold" : "ctrl+66",//^B
  16624. "Italic" : "ctrl+73", //^I
  16625. "Underline" : "ctrl+85"//^U
  16626. });
  16627. me.addInputRule(function(root){
  16628. utils.each(root.getNodesByTagName('b i'),function(node){
  16629. switch (node.tagName){
  16630. case 'b':
  16631. node.tagName = 'strong';
  16632. break;
  16633. case 'i':
  16634. node.tagName = 'em';
  16635. }
  16636. });
  16637. });
  16638. for ( var style in basestyles ) {
  16639. (function( cmd, tagNames ) {
  16640. me.commands[cmd] = {
  16641. execCommand : function( cmdName ) {
  16642. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  16643. if ( range.collapsed ) {
  16644. if ( obj ) {
  16645. var tmpText = me.document.createTextNode('');
  16646. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  16647. range.setStartBefore(tmpText);
  16648. domUtils.remove(tmpText);
  16649. } else {
  16650. var tmpNode = range.document.createElement( tagNames[0] );
  16651. if(cmdName == 'superscript' || cmdName == 'subscript'){
  16652. tmpText = me.document.createTextNode('');
  16653. range.insertNode(tmpText)
  16654. .removeInlineStyle(['sub','sup'])
  16655. .setStartBefore(tmpText)
  16656. .collapse(true);
  16657. }
  16658. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  16659. }
  16660. range.collapse( true );
  16661. } else {
  16662. if(cmdName == 'superscript' || cmdName == 'subscript'){
  16663. if(!obj || obj.tagName.toLowerCase() != cmdName){
  16664. range.removeInlineStyle(['sub','sup']);
  16665. }
  16666. }
  16667. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  16668. }
  16669. range.select();
  16670. },
  16671. queryCommandState : function() {
  16672. return getObj(this,tagNames) ? 1 : 0;
  16673. }
  16674. };
  16675. })( style, basestyles[style] );
  16676. }
  16677. };
  16678. /**
  16679. * @description
  16680. * 1.拖放文件到编辑区域,自动上传并插入到选区
  16681. * 2.插入粘贴板的图片,自动上传并插入到选区
  16682. * @author Jinqn
  16683. * @date 2013-10-14
  16684. */
  16685. UE.plugin.register('autoupload', function (){
  16686. var me = this;
  16687. var sendAndInsertImage = function (file, editor) {
  16688. //模拟数据
  16689. var fd = new FormData();
  16690. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  16691. fd.append('type', 'ajax');
  16692. var xhr = new XMLHttpRequest();
  16693. xhr.open("post", me.options.imageUrl, true);
  16694. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  16695. xhr.addEventListener('load', function (e) {
  16696. try{
  16697. var json = (new Function("return " + e.target.response))(),
  16698. picLink = me.options.imagePath + json.url;
  16699. editor.execCommand('insertimage', {
  16700. src: picLink,
  16701. _src: picLink
  16702. });
  16703. }catch(er){ }
  16704. });
  16705. xhr.send(fd);
  16706. };
  16707. function getPasteImage(e){
  16708. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  16709. }
  16710. function getDropImage(e){
  16711. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  16712. }
  16713. return {
  16714. bindEvents:{
  16715. //插入粘贴板的图片,拖放插入图片
  16716. 'ready':function(e){
  16717. if(window.FormData && window.FileReader) {
  16718. domUtils.on(me.body, 'paste drop', function(e){
  16719. var hasImg = false,
  16720. items;
  16721. //获取粘贴板文件列表或者拖放文件列表
  16722. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  16723. if(items){
  16724. var len = items.length,
  16725. file;
  16726. while (len--){
  16727. file = items[len];
  16728. if(file.getAsFile) file = file.getAsFile();
  16729. if(file && file.size > 0 && /image\/\w+/i.test(file.type) ) {
  16730. sendAndInsertImage(file, me);
  16731. hasImg = true;
  16732. }
  16733. }
  16734. hasImg && e.preventDefault();
  16735. }
  16736. });
  16737. //取消拖放图片时出现的文字光标位置提示
  16738. domUtils.on(me.body, 'dragover', function (e) {
  16739. if(e.dataTransfer.types[0] == 'Files') {
  16740. e.preventDefault();
  16741. }
  16742. });
  16743. }
  16744. }
  16745. }
  16746. }
  16747. });
  16748. var baidu = baidu || {};
  16749. baidu.editor = baidu.editor || {};
  16750. baidu.editor.ui = {};
  16751. (function (){
  16752. var browser = baidu.editor.browser,
  16753. domUtils = baidu.editor.dom.domUtils;
  16754. var magic = '$EDITORUI';
  16755. var root = window[magic] = {};
  16756. var uidMagic = 'ID' + magic;
  16757. var uidCount = 0;
  16758. var uiUtils = baidu.editor.ui.uiUtils = {
  16759. uid: function (obj){
  16760. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  16761. },
  16762. hook: function ( fn, callback ) {
  16763. var dg;
  16764. if (fn && fn._callbacks) {
  16765. dg = fn;
  16766. } else {
  16767. dg = function (){
  16768. var q;
  16769. if (fn) {
  16770. q = fn.apply(this, arguments);
  16771. }
  16772. var callbacks = dg._callbacks;
  16773. var k = callbacks.length;
  16774. while (k --) {
  16775. var r = callbacks[k].apply(this, arguments);
  16776. if (q === undefined) {
  16777. q = r;
  16778. }
  16779. }
  16780. return q;
  16781. };
  16782. dg._callbacks = [];
  16783. }
  16784. dg._callbacks.push(callback);
  16785. return dg;
  16786. },
  16787. createElementByHtml: function (html){
  16788. var el = document.createElement('div');
  16789. el.innerHTML = html;
  16790. el = el.firstChild;
  16791. el.parentNode.removeChild(el);
  16792. return el;
  16793. },
  16794. getViewportElement: function (){
  16795. return (browser.ie && browser.quirks) ?
  16796. document.body : document.documentElement;
  16797. },
  16798. getClientRect: function (element){
  16799. var bcr;
  16800. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  16801. try{
  16802. bcr = element.getBoundingClientRect();
  16803. }catch(e){
  16804. bcr={left:0,top:0,height:0,width:0}
  16805. }
  16806. var rect = {
  16807. left: Math.round(bcr.left),
  16808. top: Math.round(bcr.top),
  16809. height: Math.round(bcr.bottom - bcr.top),
  16810. width: Math.round(bcr.right - bcr.left)
  16811. };
  16812. var doc;
  16813. while ((doc = element.ownerDocument) !== document &&
  16814. (element = domUtils.getWindow(doc).frameElement)) {
  16815. bcr = element.getBoundingClientRect();
  16816. rect.left += bcr.left;
  16817. rect.top += bcr.top;
  16818. }
  16819. rect.bottom = rect.top + rect.height;
  16820. rect.right = rect.left + rect.width;
  16821. return rect;
  16822. },
  16823. getViewportRect: function (){
  16824. var viewportEl = uiUtils.getViewportElement();
  16825. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  16826. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  16827. return {
  16828. left: 0,
  16829. top: 0,
  16830. height: height,
  16831. width: width,
  16832. bottom: height,
  16833. right: width
  16834. };
  16835. },
  16836. setViewportOffset: function (element, offset){
  16837. var rect;
  16838. var fixedLayer = uiUtils.getFixedLayer();
  16839. if (element.parentNode === fixedLayer) {
  16840. element.style.left = offset.left + 'px';
  16841. element.style.top = offset.top + 'px';
  16842. } else {
  16843. domUtils.setViewportOffset(element, offset);
  16844. }
  16845. },
  16846. getEventOffset: function (evt){
  16847. var el = evt.target || evt.srcElement;
  16848. var rect = uiUtils.getClientRect(el);
  16849. var offset = uiUtils.getViewportOffsetByEvent(evt);
  16850. return {
  16851. left: offset.left - rect.left,
  16852. top: offset.top - rect.top
  16853. };
  16854. },
  16855. getViewportOffsetByEvent: function (evt){
  16856. var el = evt.target || evt.srcElement;
  16857. var frameEl = domUtils.getWindow(el).frameElement;
  16858. var offset = {
  16859. left: evt.clientX,
  16860. top: evt.clientY
  16861. };
  16862. if (frameEl && el.ownerDocument !== document) {
  16863. var rect = uiUtils.getClientRect(frameEl);
  16864. offset.left += rect.left;
  16865. offset.top += rect.top;
  16866. }
  16867. return offset;
  16868. },
  16869. setGlobal: function (id, obj){
  16870. root[id] = obj;
  16871. return magic + '["' + id + '"]';
  16872. },
  16873. unsetGlobal: function (id){
  16874. delete root[id];
  16875. },
  16876. copyAttributes: function (tgt, src){
  16877. var attributes = src.attributes;
  16878. var k = attributes.length;
  16879. while (k --) {
  16880. var attrNode = attributes[k];
  16881. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  16882. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  16883. }
  16884. }
  16885. if (src.className) {
  16886. domUtils.addClass(tgt,src.className);
  16887. }
  16888. if (src.style.cssText) {
  16889. tgt.style.cssText += ';' + src.style.cssText;
  16890. }
  16891. },
  16892. removeStyle: function (el, styleName){
  16893. if (el.style.removeProperty) {
  16894. el.style.removeProperty(styleName);
  16895. } else if (el.style.removeAttribute) {
  16896. el.style.removeAttribute(styleName);
  16897. } else throw '';
  16898. },
  16899. contains: function (elA, elB){
  16900. return elA && elB && (elA === elB ? false : (
  16901. elA.contains ? elA.contains(elB) :
  16902. elA.compareDocumentPosition(elB) & 16
  16903. ));
  16904. },
  16905. startDrag: function (evt, callbacks,doc){
  16906. var doc = doc || document;
  16907. var startX = evt.clientX;
  16908. var startY = evt.clientY;
  16909. function handleMouseMove(evt){
  16910. var x = evt.clientX - startX;
  16911. var y = evt.clientY - startY;
  16912. callbacks.ondragmove(x, y,evt);
  16913. if (evt.stopPropagation) {
  16914. evt.stopPropagation();
  16915. } else {
  16916. evt.cancelBubble = true;
  16917. }
  16918. }
  16919. if (doc.addEventListener) {
  16920. function handleMouseUp(evt){
  16921. doc.removeEventListener('mousemove', handleMouseMove, true);
  16922. doc.removeEventListener('mouseup', handleMouseUp, true);
  16923. window.removeEventListener('mouseup', handleMouseUp, true);
  16924. callbacks.ondragstop();
  16925. }
  16926. doc.addEventListener('mousemove', handleMouseMove, true);
  16927. doc.addEventListener('mouseup', handleMouseUp, true);
  16928. window.addEventListener('mouseup', handleMouseUp, true);
  16929. evt.preventDefault();
  16930. } else {
  16931. var elm = evt.srcElement;
  16932. elm.setCapture();
  16933. function releaseCaptrue(){
  16934. elm.releaseCapture();
  16935. elm.detachEvent('onmousemove', handleMouseMove);
  16936. elm.detachEvent('onmouseup', releaseCaptrue);
  16937. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  16938. callbacks.ondragstop();
  16939. }
  16940. elm.attachEvent('onmousemove', handleMouseMove);
  16941. elm.attachEvent('onmouseup', releaseCaptrue);
  16942. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  16943. evt.returnValue = false;
  16944. }
  16945. callbacks.ondragstart();
  16946. },
  16947. getFixedLayer: function (){
  16948. var layer = document.getElementById('edui_fixedlayer');
  16949. if (layer == null) {
  16950. layer = document.createElement('div');
  16951. layer.id = 'edui_fixedlayer';
  16952. document.body.appendChild(layer);
  16953. if (browser.ie && browser.version <= 8) {
  16954. layer.style.position = 'absolute';
  16955. bindFixedLayer();
  16956. setTimeout(updateFixedOffset);
  16957. } else {
  16958. layer.style.position = 'fixed';
  16959. }
  16960. layer.style.left = '0';
  16961. layer.style.top = '0';
  16962. layer.style.width = '0';
  16963. layer.style.height = '0';
  16964. }
  16965. return layer;
  16966. },
  16967. makeUnselectable: function (element){
  16968. if (browser.opera || (browser.ie && browser.version < 9)) {
  16969. element.unselectable = 'on';
  16970. if (element.hasChildNodes()) {
  16971. for (var i=0; i<element.childNodes.length; i++) {
  16972. if (element.childNodes[i].nodeType == 1) {
  16973. uiUtils.makeUnselectable(element.childNodes[i]);
  16974. }
  16975. }
  16976. }
  16977. } else {
  16978. if (element.style.MozUserSelect !== undefined) {
  16979. element.style.MozUserSelect = 'none';
  16980. } else if (element.style.WebkitUserSelect !== undefined) {
  16981. element.style.WebkitUserSelect = 'none';
  16982. } else if (element.style.KhtmlUserSelect !== undefined) {
  16983. element.style.KhtmlUserSelect = 'none';
  16984. }
  16985. }
  16986. }
  16987. };
  16988. function updateFixedOffset(){
  16989. var layer = document.getElementById('edui_fixedlayer');
  16990. uiUtils.setViewportOffset(layer, {
  16991. left: 0,
  16992. top: 0
  16993. });
  16994. // layer.style.display = 'none';
  16995. // layer.style.display = 'block';
  16996. //#trace: 1354
  16997. // setTimeout(updateFixedOffset);
  16998. }
  16999. function bindFixedLayer(adjOffset){
  17000. domUtils.on(window, 'scroll', updateFixedOffset);
  17001. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  17002. }
  17003. })();
  17004. (function () {
  17005. var utils = baidu.editor.utils,
  17006. uiUtils = baidu.editor.ui.uiUtils,
  17007. EventBase = baidu.editor.EventBase,
  17008. UIBase = baidu.editor.ui.UIBase = function () {
  17009. };
  17010. UIBase.prototype = {
  17011. className:'',
  17012. uiName:'',
  17013. initOptions:function (options) {
  17014. var me = this;
  17015. for (var k in options) {
  17016. me[k] = options[k];
  17017. }
  17018. this.id = this.id || 'edui' + uiUtils.uid();
  17019. },
  17020. initUIBase:function () {
  17021. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  17022. },
  17023. render:function (holder) {
  17024. var html = this.renderHtml();
  17025. var el = uiUtils.createElementByHtml(html);
  17026. //by xuheng 给每个node添加class
  17027. var list = domUtils.getElementsByTagName(el, "*");
  17028. var theme = "edui-" + (this.theme || this.editor.options.theme);
  17029. var layer = document.getElementById('edui_fixedlayer');
  17030. for (var i = 0, node; node = list[i++];) {
  17031. domUtils.addClass(node, theme);
  17032. }
  17033. domUtils.addClass(el, theme);
  17034. if(layer){
  17035. layer.className="";
  17036. domUtils.addClass(layer,theme);
  17037. }
  17038. var seatEl = this.getDom();
  17039. if (seatEl != null) {
  17040. seatEl.parentNode.replaceChild(el, seatEl);
  17041. uiUtils.copyAttributes(el, seatEl);
  17042. } else {
  17043. if (typeof holder == 'string') {
  17044. holder = document.getElementById(holder);
  17045. }
  17046. holder = holder || uiUtils.getFixedLayer();
  17047. domUtils.addClass(holder, theme);
  17048. holder.appendChild(el);
  17049. }
  17050. this.postRender();
  17051. },
  17052. getDom:function (name) {
  17053. if (!name) {
  17054. return document.getElementById(this.id);
  17055. } else {
  17056. return document.getElementById(this.id + '_' + name);
  17057. }
  17058. },
  17059. postRender:function () {
  17060. this.fireEvent('postrender');
  17061. },
  17062. getHtmlTpl:function () {
  17063. return '';
  17064. },
  17065. formatHtml:function (tpl) {
  17066. var prefix = 'edui-' + this.uiName;
  17067. return (tpl
  17068. .replace(/##/g, this.id)
  17069. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  17070. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  17071. .replace(/\$\$/g, this._globalKey));
  17072. },
  17073. renderHtml:function () {
  17074. return this.formatHtml(this.getHtmlTpl());
  17075. },
  17076. dispose:function () {
  17077. var box = this.getDom();
  17078. if (box) baidu.editor.dom.domUtils.remove(box);
  17079. uiUtils.unsetGlobal(this.id);
  17080. }
  17081. };
  17082. utils.inherits(UIBase, EventBase);
  17083. })();
  17084. (function (){
  17085. var utils = baidu.editor.utils,
  17086. UIBase = baidu.editor.ui.UIBase,
  17087. Separator = baidu.editor.ui.Separator = function (options){
  17088. this.initOptions(options);
  17089. this.initSeparator();
  17090. };
  17091. Separator.prototype = {
  17092. uiName: 'separator',
  17093. initSeparator: function (){
  17094. this.initUIBase();
  17095. },
  17096. getHtmlTpl: function (){
  17097. return '<div id="##" class="edui-box %%"></div>';
  17098. }
  17099. };
  17100. utils.inherits(Separator, UIBase);
  17101. })();
  17102. ///import core
  17103. ///import uicore
  17104. (function (){
  17105. var utils = baidu.editor.utils,
  17106. domUtils = baidu.editor.dom.domUtils,
  17107. UIBase = baidu.editor.ui.UIBase,
  17108. uiUtils = baidu.editor.ui.uiUtils;
  17109. var Mask = baidu.editor.ui.Mask = function (options){
  17110. this.initOptions(options);
  17111. this.initUIBase();
  17112. };
  17113. Mask.prototype = {
  17114. getHtmlTpl: function (){
  17115. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  17116. },
  17117. postRender: function (){
  17118. var me = this;
  17119. domUtils.on(window, 'resize', function (){
  17120. setTimeout(function (){
  17121. if (!me.isHidden()) {
  17122. me._fill();
  17123. }
  17124. });
  17125. });
  17126. },
  17127. show: function (zIndex){
  17128. this._fill();
  17129. this.getDom().style.display = '';
  17130. this.getDom().style.zIndex = zIndex;
  17131. },
  17132. hide: function (){
  17133. this.getDom().style.display = 'none';
  17134. this.getDom().style.zIndex = '';
  17135. },
  17136. isHidden: function (){
  17137. return this.getDom().style.display == 'none';
  17138. },
  17139. _onMouseDown: function (){
  17140. return false;
  17141. },
  17142. _fill: function (){
  17143. var el = this.getDom();
  17144. var vpRect = uiUtils.getViewportRect();
  17145. el.style.width = vpRect.width + 'px';
  17146. el.style.height = vpRect.height + 'px';
  17147. }
  17148. };
  17149. utils.inherits(Mask, UIBase);
  17150. })();
  17151. ///import core
  17152. ///import uicore
  17153. (function () {
  17154. var utils = baidu.editor.utils,
  17155. uiUtils = baidu.editor.ui.uiUtils,
  17156. domUtils = baidu.editor.dom.domUtils,
  17157. UIBase = baidu.editor.ui.UIBase,
  17158. Popup = baidu.editor.ui.Popup = function (options){
  17159. this.initOptions(options);
  17160. this.initPopup();
  17161. };
  17162. var allPopups = [];
  17163. function closeAllPopup( evt,el ){
  17164. for ( var i = 0; i < allPopups.length; i++ ) {
  17165. var pop = allPopups[i];
  17166. if (!pop.isHidden()) {
  17167. if (pop.queryAutoHide(el) !== false) {
  17168. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  17169. pop.hide();
  17170. }
  17171. }
  17172. }
  17173. if(allPopups.length)
  17174. pop.editor.fireEvent("afterhidepop");
  17175. }
  17176. Popup.postHide = closeAllPopup;
  17177. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  17178. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  17179. Popup.prototype = {
  17180. SHADOW_RADIUS: 5,
  17181. content: null,
  17182. _hidden: false,
  17183. autoRender: true,
  17184. canSideLeft: true,
  17185. canSideUp: true,
  17186. initPopup: function (){
  17187. this.initUIBase();
  17188. allPopups.push( this );
  17189. },
  17190. getHtmlTpl: function (){
  17191. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  17192. ' <div id="##_body" class="edui-popup-body">' +
  17193. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  17194. ' <div class="edui-shadow"></div>' +
  17195. ' <div id="##_content" class="edui-popup-content">' +
  17196. this.getContentHtmlTpl() +
  17197. ' </div>' +
  17198. ' </div>' +
  17199. '</div>';
  17200. },
  17201. getContentHtmlTpl: function (){
  17202. if(this.content){
  17203. if (typeof this.content == 'string') {
  17204. return this.content;
  17205. }
  17206. return this.content.renderHtml();
  17207. }else{
  17208. return ''
  17209. }
  17210. },
  17211. _UIBase_postRender: UIBase.prototype.postRender,
  17212. postRender: function (){
  17213. if (this.content instanceof UIBase) {
  17214. this.content.postRender();
  17215. }
  17216. //捕获鼠标滚轮
  17217. if( this.captureWheel && !this.captured ) {
  17218. this.captured = true;
  17219. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  17220. _height = this.getDom().offsetHeight,
  17221. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  17222. content = this.getDom('content'),
  17223. ifr = this.getDom('body').getElementsByTagName('iframe'),
  17224. me = this;
  17225. ifr.length && ( ifr = ifr[0] );
  17226. while( _top + _height > winHeight ) {
  17227. _height -= 30;
  17228. content.style.height = _height + 'px';
  17229. //同步更改iframe高度
  17230. ifr && ( ifr.style.height = _height + 'px' );
  17231. }
  17232. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  17233. if( window.XMLHttpRequest ) {
  17234. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  17235. if(e.preventDefault) {
  17236. e.preventDefault();
  17237. } else {
  17238. e.returnValue = false;
  17239. }
  17240. if( e.wheelDelta ) {
  17241. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  17242. } else {
  17243. content.scrollTop -= ( e.detail / -3 )*60;
  17244. }
  17245. });
  17246. } else {
  17247. //ie6
  17248. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  17249. e.returnValue = false;
  17250. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  17251. });
  17252. }
  17253. }
  17254. this.fireEvent('postRenderAfter');
  17255. this.hide(true);
  17256. this._UIBase_postRender();
  17257. },
  17258. _doAutoRender: function (){
  17259. if (!this.getDom() && this.autoRender) {
  17260. this.render();
  17261. }
  17262. },
  17263. mesureSize: function (){
  17264. var box = this.getDom('content');
  17265. return uiUtils.getClientRect(box);
  17266. },
  17267. fitSize: function (){
  17268. if( this.captureWheel && this.sized ) {
  17269. return this.__size;
  17270. }
  17271. this.sized = true;
  17272. var popBodyEl = this.getDom('body');
  17273. popBodyEl.style.width = '';
  17274. popBodyEl.style.height = '';
  17275. var size = this.mesureSize();
  17276. if( this.captureWheel ) {
  17277. popBodyEl.style.width = -(-20 -size.width) + 'px';
  17278. var height = parseInt( this.getDom('content').style.height, 10 );
  17279. !window.isNaN( height ) && ( size.height = height );
  17280. } else {
  17281. popBodyEl.style.width = size.width + 'px';
  17282. }
  17283. popBodyEl.style.height = size.height + 'px';
  17284. this.__size = size;
  17285. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  17286. return size;
  17287. },
  17288. showAnchor: function ( element, hoz ){
  17289. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  17290. },
  17291. showAnchorRect: function ( rect, hoz, adj ){
  17292. this._doAutoRender();
  17293. var vpRect = uiUtils.getViewportRect();
  17294. this._show();
  17295. var popSize = this.fitSize();
  17296. var sideLeft, sideUp, left, top;
  17297. if (hoz) {
  17298. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  17299. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  17300. left = (sideLeft ? rect.left - popSize.width : rect.right);
  17301. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  17302. } else {
  17303. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  17304. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  17305. left = (sideLeft ? rect.right - popSize.width : rect.left);
  17306. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  17307. }
  17308. var popEl = this.getDom();
  17309. uiUtils.setViewportOffset(popEl, {
  17310. left: left,
  17311. top: top
  17312. });
  17313. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  17314. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  17315. if(this.editor){
  17316. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  17317. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  17318. }
  17319. },
  17320. showAt: function (offset) {
  17321. var left = offset.left;
  17322. var top = offset.top;
  17323. var rect = {
  17324. left: left,
  17325. top: top,
  17326. right: left,
  17327. bottom: top,
  17328. height: 0,
  17329. width: 0
  17330. };
  17331. this.showAnchorRect(rect, false, true);
  17332. },
  17333. _show: function (){
  17334. if (this._hidden) {
  17335. var box = this.getDom();
  17336. box.style.display = '';
  17337. this._hidden = false;
  17338. // if (box.setActive) {
  17339. // box.setActive();
  17340. // }
  17341. this.fireEvent('show');
  17342. }
  17343. },
  17344. isHidden: function (){
  17345. return this._hidden;
  17346. },
  17347. show: function (){
  17348. this._doAutoRender();
  17349. this._show();
  17350. },
  17351. hide: function (notNofity){
  17352. if (!this._hidden && this.getDom()) {
  17353. this.getDom().style.display = 'none';
  17354. this._hidden = true;
  17355. if (!notNofity) {
  17356. this.fireEvent('hide');
  17357. }
  17358. }
  17359. },
  17360. queryAutoHide: function (el){
  17361. return !el || !uiUtils.contains(this.getDom(), el);
  17362. }
  17363. };
  17364. utils.inherits(Popup, UIBase);
  17365. domUtils.on( document, 'mousedown', function ( evt ) {
  17366. var el = evt.target || evt.srcElement;
  17367. closeAllPopup( evt,el );
  17368. } );
  17369. domUtils.on( window, 'scroll', function (evt,el) {
  17370. closeAllPopup( evt,el );
  17371. } );
  17372. })();
  17373. ///import core
  17374. ///import uicore
  17375. (function (){
  17376. var utils = baidu.editor.utils,
  17377. UIBase = baidu.editor.ui.UIBase,
  17378. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  17379. this.initOptions(options);
  17380. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  17381. this.initUIBase();
  17382. };
  17383. ColorPicker.prototype = {
  17384. getHtmlTpl: function (){
  17385. return genColorPicker(this.noColorText,this.editor);
  17386. },
  17387. _onTableClick: function (evt){
  17388. var tgt = evt.target || evt.srcElement;
  17389. var color = tgt.getAttribute('data-color');
  17390. if (color) {
  17391. this.fireEvent('pickcolor', color);
  17392. }
  17393. },
  17394. _onTableOver: function (evt){
  17395. var tgt = evt.target || evt.srcElement;
  17396. var color = tgt.getAttribute('data-color');
  17397. if (color) {
  17398. this.getDom('preview').style.backgroundColor = color;
  17399. }
  17400. },
  17401. _onTableOut: function (){
  17402. this.getDom('preview').style.backgroundColor = '';
  17403. },
  17404. _onPickNoColor: function (){
  17405. this.fireEvent('picknocolor');
  17406. }
  17407. };
  17408. utils.inherits(ColorPicker, UIBase);
  17409. var COLORS = (
  17410. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  17411. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  17412. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  17413. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  17414. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  17415. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  17416. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  17417. function genColorPicker(noColorText,editor){
  17418. var html = '<div id="##" class="edui-colorpicker %%">' +
  17419. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  17420. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  17421. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  17422. '</div>' +
  17423. '<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">' +
  17424. '<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>'+
  17425. '<tr class="edui-colorpicker-tablefirstrow" >';
  17426. for (var i=0; i<COLORS.length; i++) {
  17427. if (i && i%10 === 0) {
  17428. 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"':'')+'>';
  17429. }
  17430. 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"' +
  17431. ' data-color="#'+ COLORS[i] +'"'+
  17432. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  17433. (i<10 || i>=60?'border-width:1px;':
  17434. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  17435. 'border-width:0 1px 0 1px;')+
  17436. '"' +
  17437. '></a></td>':'';
  17438. }
  17439. html += '</tr></table></div>';
  17440. return html;
  17441. }
  17442. })();
  17443. ///import core
  17444. ///import uicore
  17445. (function (){
  17446. var utils = baidu.editor.utils,
  17447. uiUtils = baidu.editor.ui.uiUtils,
  17448. UIBase = baidu.editor.ui.UIBase;
  17449. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  17450. this.initOptions(options);
  17451. this.initTablePicker();
  17452. };
  17453. TablePicker.prototype = {
  17454. defaultNumRows: 10,
  17455. defaultNumCols: 10,
  17456. maxNumRows: 20,
  17457. maxNumCols: 20,
  17458. numRows: 10,
  17459. numCols: 10,
  17460. lengthOfCellSide: 22,
  17461. initTablePicker: function (){
  17462. this.initUIBase();
  17463. },
  17464. getHtmlTpl: function (){
  17465. var me = this;
  17466. return '<div id="##" class="edui-tablepicker %%">' +
  17467. '<div class="edui-tablepicker-body">' +
  17468. '<div class="edui-infoarea">' +
  17469. '<span id="##_label" class="edui-label"></span>' +
  17470. '</div>' +
  17471. '<div class="edui-pickarea"' +
  17472. ' onmousemove="$$._onMouseMove(event, this);"' +
  17473. ' onmouseover="$$._onMouseOver(event, this);"' +
  17474. ' onmouseout="$$._onMouseOut(event, this);"' +
  17475. ' onclick="$$._onClick(event, this);"' +
  17476. '>' +
  17477. '<div id="##_overlay" class="edui-overlay"></div>' +
  17478. '</div>' +
  17479. '</div>' +
  17480. '</div>';
  17481. },
  17482. _UIBase_render: UIBase.prototype.render,
  17483. render: function (holder){
  17484. this._UIBase_render(holder);
  17485. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  17486. },
  17487. _track: function (numCols, numRows){
  17488. var style = this.getDom('overlay').style;
  17489. var sideLen = this.lengthOfCellSide;
  17490. style.width = numCols * sideLen + 'px';
  17491. style.height = numRows * sideLen + 'px';
  17492. var label = this.getDom('label');
  17493. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  17494. this.numCols = numCols;
  17495. this.numRows = numRows;
  17496. },
  17497. _onMouseOver: function (evt, el){
  17498. var rel = evt.relatedTarget || evt.fromElement;
  17499. if (!uiUtils.contains(el, rel) && el !== rel) {
  17500. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  17501. this.getDom('overlay').style.visibility = '';
  17502. }
  17503. },
  17504. _onMouseOut: function (evt, el){
  17505. var rel = evt.relatedTarget || evt.toElement;
  17506. if (!uiUtils.contains(el, rel) && el !== rel) {
  17507. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  17508. this.getDom('overlay').style.visibility = 'hidden';
  17509. }
  17510. },
  17511. _onMouseMove: function (evt, el){
  17512. var style = this.getDom('overlay').style;
  17513. var offset = uiUtils.getEventOffset(evt);
  17514. var sideLen = this.lengthOfCellSide;
  17515. var numCols = Math.ceil(offset.left / sideLen);
  17516. var numRows = Math.ceil(offset.top / sideLen);
  17517. this._track(numCols, numRows);
  17518. },
  17519. _onClick: function (){
  17520. this.fireEvent('picktable', this.numCols, this.numRows);
  17521. }
  17522. };
  17523. utils.inherits(TablePicker, UIBase);
  17524. })();
  17525. (function (){
  17526. var browser = baidu.editor.browser,
  17527. domUtils = baidu.editor.dom.domUtils,
  17528. uiUtils = baidu.editor.ui.uiUtils;
  17529. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  17530. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  17531. ( browser.ie ? (
  17532. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  17533. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  17534. : (
  17535. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  17536. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  17537. baidu.editor.ui.Stateful = {
  17538. alwalysHoverable: false,
  17539. target:null,//目标元素和this指向dom不一样
  17540. Stateful_init: function (){
  17541. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  17542. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  17543. },
  17544. Stateful_getHtmlTpl: function (){
  17545. var tpl = this._Stateful_dGetHtmlTpl();
  17546. // 使用function避免$转义
  17547. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  17548. },
  17549. Stateful_onMouseEnter: function (evt, el){
  17550. this.target=el;
  17551. if (!this.isDisabled() || this.alwalysHoverable) {
  17552. this.addState('hover');
  17553. this.fireEvent('over');
  17554. }
  17555. },
  17556. Stateful_onMouseLeave: function (evt, el){
  17557. if (!this.isDisabled() || this.alwalysHoverable) {
  17558. this.removeState('hover');
  17559. this.removeState('active');
  17560. this.fireEvent('out');
  17561. }
  17562. },
  17563. Stateful_onMouseOver: function (evt, el){
  17564. var rel = evt.relatedTarget;
  17565. if (!uiUtils.contains(el, rel) && el !== rel) {
  17566. this.Stateful_onMouseEnter(evt, el);
  17567. }
  17568. },
  17569. Stateful_onMouseOut: function (evt, el){
  17570. var rel = evt.relatedTarget;
  17571. if (!uiUtils.contains(el, rel) && el !== rel) {
  17572. this.Stateful_onMouseLeave(evt, el);
  17573. }
  17574. },
  17575. Stateful_onMouseDown: function (evt, el){
  17576. if (!this.isDisabled()) {
  17577. this.addState('active');
  17578. }
  17579. },
  17580. Stateful_onMouseUp: function (evt, el){
  17581. if (!this.isDisabled()) {
  17582. this.removeState('active');
  17583. }
  17584. },
  17585. Stateful_postRender: function (){
  17586. if (this.disabled && !this.hasState('disabled')) {
  17587. this.addState('disabled');
  17588. }
  17589. },
  17590. hasState: function (state){
  17591. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  17592. },
  17593. addState: function (state){
  17594. if (!this.hasState(state)) {
  17595. this.getStateDom().className += ' edui-state-' + state;
  17596. }
  17597. },
  17598. removeState: function (state){
  17599. if (this.hasState(state)) {
  17600. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  17601. }
  17602. },
  17603. getStateDom: function (){
  17604. return this.getDom('state');
  17605. },
  17606. isChecked: function (){
  17607. return this.hasState('checked');
  17608. },
  17609. setChecked: function (checked){
  17610. if (!this.isDisabled() && checked) {
  17611. this.addState('checked');
  17612. } else {
  17613. this.removeState('checked');
  17614. }
  17615. },
  17616. isDisabled: function (){
  17617. return this.hasState('disabled');
  17618. },
  17619. setDisabled: function (disabled){
  17620. if (disabled) {
  17621. this.removeState('hover');
  17622. this.removeState('checked');
  17623. this.removeState('active');
  17624. this.addState('disabled');
  17625. } else {
  17626. this.removeState('disabled');
  17627. }
  17628. }
  17629. };
  17630. })();
  17631. ///import core
  17632. ///import uicore
  17633. ///import ui/stateful.js
  17634. (function (){
  17635. var utils = baidu.editor.utils,
  17636. UIBase = baidu.editor.ui.UIBase,
  17637. Stateful = baidu.editor.ui.Stateful,
  17638. Button = baidu.editor.ui.Button = function (options){
  17639. this.initOptions(options);
  17640. this.initButton();
  17641. };
  17642. Button.prototype = {
  17643. uiName: 'button',
  17644. label: '',
  17645. title: '',
  17646. showIcon: true,
  17647. showText: true,
  17648. initButton: function (){
  17649. this.initUIBase();
  17650. this.Stateful_init();
  17651. },
  17652. getHtmlTpl: function (){
  17653. return '<div id="##" class="edui-box %%">' +
  17654. '<div id="##_state" stateful>' +
  17655. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  17656. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  17657. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  17658. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  17659. '</div>' +
  17660. '</div>' +
  17661. '</div></div>';
  17662. },
  17663. postRender: function (){
  17664. this.Stateful_postRender();
  17665. this.setDisabled(this.disabled)
  17666. },
  17667. _onClick: function (){
  17668. if (!this.isDisabled()) {
  17669. this.fireEvent('click');
  17670. }
  17671. }
  17672. };
  17673. utils.inherits(Button, UIBase);
  17674. utils.extend(Button.prototype, Stateful);
  17675. })();
  17676. ///import core
  17677. ///import uicore
  17678. ///import ui/stateful.js
  17679. (function (){
  17680. var utils = baidu.editor.utils,
  17681. uiUtils = baidu.editor.ui.uiUtils,
  17682. domUtils = baidu.editor.dom.domUtils,
  17683. UIBase = baidu.editor.ui.UIBase,
  17684. Stateful = baidu.editor.ui.Stateful,
  17685. SplitButton = baidu.editor.ui.SplitButton = function (options){
  17686. this.initOptions(options);
  17687. this.initSplitButton();
  17688. };
  17689. SplitButton.prototype = {
  17690. popup: null,
  17691. uiName: 'splitbutton',
  17692. title: '',
  17693. initSplitButton: function (){
  17694. this.initUIBase();
  17695. this.Stateful_init();
  17696. var me = this;
  17697. if (this.popup != null) {
  17698. var popup = this.popup;
  17699. this.popup = null;
  17700. this.setPopup(popup);
  17701. }
  17702. },
  17703. _UIBase_postRender: UIBase.prototype.postRender,
  17704. postRender: function (){
  17705. this.Stateful_postRender();
  17706. this._UIBase_postRender();
  17707. },
  17708. setPopup: function (popup){
  17709. if (this.popup === popup) return;
  17710. if (this.popup != null) {
  17711. this.popup.dispose();
  17712. }
  17713. popup.addListener('show', utils.bind(this._onPopupShow, this));
  17714. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  17715. popup.addListener('postrender', utils.bind(function (){
  17716. popup.getDom('body').appendChild(
  17717. uiUtils.createElementByHtml('<div id="' +
  17718. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  17719. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  17720. );
  17721. popup.getDom().className += ' ' + this.className;
  17722. }, this));
  17723. this.popup = popup;
  17724. },
  17725. _onPopupShow: function (){
  17726. this.addState('opened');
  17727. },
  17728. _onPopupHide: function (){
  17729. this.removeState('opened');
  17730. },
  17731. getHtmlTpl: function (){
  17732. return '<div id="##" class="edui-box %%">' +
  17733. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  17734. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  17735. '<div class="edui-box edui-icon"></div>' +
  17736. '</div>' +
  17737. '<div class="edui-box edui-splitborder"></div>' +
  17738. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  17739. '</div></div></div>';
  17740. },
  17741. showPopup: function (){
  17742. // 当popup往上弹出的时候,做特殊处理
  17743. var rect = uiUtils.getClientRect(this.getDom());
  17744. rect.top -= this.popup.SHADOW_RADIUS;
  17745. rect.height += this.popup.SHADOW_RADIUS;
  17746. this.popup.showAnchorRect(rect);
  17747. },
  17748. _onArrowClick: function (event, el){
  17749. if (!this.isDisabled()) {
  17750. this.showPopup();
  17751. }
  17752. },
  17753. _onButtonClick: function (){
  17754. if (!this.isDisabled()) {
  17755. this.fireEvent('buttonclick');
  17756. }
  17757. }
  17758. };
  17759. utils.inherits(SplitButton, UIBase);
  17760. utils.extend(SplitButton.prototype, Stateful, true);
  17761. })();
  17762. ///import core
  17763. ///import uicore
  17764. ///import ui/colorpicker.js
  17765. ///import ui/popup.js
  17766. ///import ui/splitbutton.js
  17767. (function (){
  17768. var utils = baidu.editor.utils,
  17769. uiUtils = baidu.editor.ui.uiUtils,
  17770. ColorPicker = baidu.editor.ui.ColorPicker,
  17771. Popup = baidu.editor.ui.Popup,
  17772. SplitButton = baidu.editor.ui.SplitButton,
  17773. ColorButton = baidu.editor.ui.ColorButton = function (options){
  17774. this.initOptions(options);
  17775. this.initColorButton();
  17776. };
  17777. ColorButton.prototype = {
  17778. initColorButton: function (){
  17779. var me = this;
  17780. this.popup = new Popup({
  17781. content: new ColorPicker({
  17782. noColorText: me.editor.getLang("clearColor"),
  17783. editor:me.editor,
  17784. onpickcolor: function (t, color){
  17785. me._onPickColor(color);
  17786. },
  17787. onpicknocolor: function (t, color){
  17788. me._onPickNoColor(color);
  17789. }
  17790. }),
  17791. editor:me.editor
  17792. });
  17793. this.initSplitButton();
  17794. },
  17795. _SplitButton_postRender: SplitButton.prototype.postRender,
  17796. postRender: function (){
  17797. this._SplitButton_postRender();
  17798. this.getDom('button_body').appendChild(
  17799. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  17800. );
  17801. this.getDom().className += ' edui-colorbutton';
  17802. },
  17803. setColor: function (color){
  17804. this.getDom('colorlump').style.backgroundColor = color;
  17805. this.color = color;
  17806. },
  17807. _onPickColor: function (color){
  17808. if (this.fireEvent('pickcolor', color) !== false) {
  17809. this.setColor(color);
  17810. this.popup.hide();
  17811. }
  17812. },
  17813. _onPickNoColor: function (color){
  17814. if (this.fireEvent('picknocolor') !== false) {
  17815. this.popup.hide();
  17816. }
  17817. }
  17818. };
  17819. utils.inherits(ColorButton, SplitButton);
  17820. })();
  17821. ///import core
  17822. ///import uicore
  17823. ///import ui/popup.js
  17824. ///import ui/tablepicker.js
  17825. ///import ui/splitbutton.js
  17826. (function (){
  17827. var utils = baidu.editor.utils,
  17828. Popup = baidu.editor.ui.Popup,
  17829. TablePicker = baidu.editor.ui.TablePicker,
  17830. SplitButton = baidu.editor.ui.SplitButton,
  17831. TableButton = baidu.editor.ui.TableButton = function (options){
  17832. this.initOptions(options);
  17833. this.initTableButton();
  17834. };
  17835. TableButton.prototype = {
  17836. initTableButton: function (){
  17837. var me = this;
  17838. this.popup = new Popup({
  17839. content: new TablePicker({
  17840. editor:me.editor,
  17841. onpicktable: function (t, numCols, numRows){
  17842. me._onPickTable(numCols, numRows);
  17843. }
  17844. }),
  17845. 'editor':me.editor
  17846. });
  17847. this.initSplitButton();
  17848. },
  17849. _onPickTable: function (numCols, numRows){
  17850. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  17851. this.popup.hide();
  17852. }
  17853. }
  17854. };
  17855. utils.inherits(TableButton, SplitButton);
  17856. })();
  17857. ///import core
  17858. ///import uicore
  17859. (function () {
  17860. var utils = baidu.editor.utils,
  17861. UIBase = baidu.editor.ui.UIBase;
  17862. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  17863. this.initOptions(options);
  17864. this.initAutoTypeSetPicker();
  17865. };
  17866. AutoTypeSetPicker.prototype = {
  17867. initAutoTypeSetPicker:function () {
  17868. this.initUIBase();
  17869. },
  17870. getHtmlTpl:function () {
  17871. var me = this.editor,
  17872. opt = me.options.autotypeset,
  17873. lang = me.getLang("autoTypeSet");
  17874. var textAlignInputName = 'textAlignValue' + me.uid,
  17875. imageBlockInputName = 'imageBlockLineValue' + me.uid;
  17876. return '<div id="##" class="edui-autotypesetpicker %%">' +
  17877. '<div class="edui-autotypesetpicker-body">' +
  17878. '<table >' +
  17879. '<tr><td nowrap colspan="2"><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>' +
  17880. '<tr><td nowrap colspan="2"><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>' +
  17881. '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' +
  17882. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  17883. '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' +
  17884. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  17885. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  17886. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  17887. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  17888. '<tr><td nowrap colspan="2"><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>' +
  17889. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  17890. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  17891. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  17892. '</table>' +
  17893. '</div>' +
  17894. '</div>';
  17895. },
  17896. _UIBase_render:UIBase.prototype.render
  17897. };
  17898. utils.inherits(AutoTypeSetPicker, UIBase);
  17899. })();
  17900. ///import core
  17901. ///import uicore
  17902. ///import ui/popup.js
  17903. ///import ui/autotypesetpicker.js
  17904. ///import ui/splitbutton.js
  17905. (function (){
  17906. var utils = baidu.editor.utils,
  17907. Popup = baidu.editor.ui.Popup,
  17908. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  17909. SplitButton = baidu.editor.ui.SplitButton,
  17910. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  17911. this.initOptions(options);
  17912. this.initAutoTypeSetButton();
  17913. };
  17914. function getPara(me){
  17915. var opt = me.editor.options.autotypeset,
  17916. cont = me.getDom(),
  17917. editorId = me.editor.uid,
  17918. inputType = null,
  17919. attrName = null,
  17920. ipts = domUtils.getElementsByTagName(cont,"input");
  17921. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  17922. inputType = ipt.getAttribute("type");
  17923. if(inputType=="checkbox"){
  17924. attrName = ipt.getAttribute("name");
  17925. opt[attrName] && delete opt[attrName];
  17926. if(ipt.checked){
  17927. var attrValue = document.getElementById( attrName+"Value" + editorId );
  17928. if(attrValue){
  17929. if(/input/ig.test(attrValue.tagName)){
  17930. opt[attrName] = attrValue.value;
  17931. }else{
  17932. var iptChilds = attrValue.getElementsByTagName("input");
  17933. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  17934. if(iptchild.checked){
  17935. opt[attrName] = iptchild.value;
  17936. break;
  17937. }
  17938. }
  17939. }
  17940. }else{
  17941. opt[attrName] = true;
  17942. }
  17943. }
  17944. }
  17945. }
  17946. var selects = domUtils.getElementsByTagName(cont,"select");
  17947. for(var i=0,si;si=selects[i++];){
  17948. var attr = si.getAttribute('name');
  17949. opt[attr] = opt[attr] ? si.value : '';
  17950. }
  17951. me.editor.options.autotypeset = opt;
  17952. }
  17953. AutoTypeSetButton.prototype = {
  17954. initAutoTypeSetButton: function (){
  17955. var me = this;
  17956. this.popup = new Popup({
  17957. //传入配置参数
  17958. content: new AutoTypeSetPicker({editor:me.editor}),
  17959. 'editor':me.editor,
  17960. hide : function(){
  17961. if (!this._hidden && this.getDom()) {
  17962. getPara(this);
  17963. this.getDom().style.display = 'none';
  17964. this._hidden = true;
  17965. this.fireEvent('hide');
  17966. }
  17967. }
  17968. });
  17969. var flag = 0;
  17970. this.popup.addListener('postRenderAfter',function(){
  17971. var popupUI = this;
  17972. if(flag)return;
  17973. var cont = this.getDom(),
  17974. btn = cont.getElementsByTagName('button')[0];
  17975. btn.onclick = function(){
  17976. getPara(popupUI);
  17977. me.editor.execCommand('autotypeset');
  17978. popupUI.hide()
  17979. };
  17980. flag = 1;
  17981. });
  17982. this.initSplitButton();
  17983. }
  17984. };
  17985. utils.inherits(AutoTypeSetButton, SplitButton);
  17986. })();
  17987. ///import core
  17988. ///import uicore
  17989. (function () {
  17990. var utils = baidu.editor.utils,
  17991. Popup = baidu.editor.ui.Popup,
  17992. Stateful = baidu.editor.ui.Stateful,
  17993. UIBase = baidu.editor.ui.UIBase;
  17994. /**
  17995. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  17996. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  17997. * @update 2013/4/2 hancong03@baidu.com
  17998. */
  17999. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  18000. this.initOptions(options);
  18001. this.initSelected();
  18002. this.initCellAlignPicker();
  18003. };
  18004. CellAlignPicker.prototype = {
  18005. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  18006. initSelected: function(){
  18007. var status = {
  18008. valign: {
  18009. top: 0,
  18010. middle: 1,
  18011. bottom: 2
  18012. },
  18013. align: {
  18014. left: 0,
  18015. center: 1,
  18016. right: 2
  18017. },
  18018. count: 3
  18019. },
  18020. result = -1;
  18021. if( this.selected ) {
  18022. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  18023. }
  18024. },
  18025. initCellAlignPicker:function () {
  18026. this.initUIBase();
  18027. this.Stateful_init();
  18028. },
  18029. getHtmlTpl:function () {
  18030. var alignType = [ 'left', 'center', 'right' ],
  18031. COUNT = 9,
  18032. tempClassName = null,
  18033. tempIndex = -1,
  18034. tmpl = [];
  18035. for( var i= 0; i<COUNT; i++ ) {
  18036. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  18037. tempIndex = i % 3;
  18038. tempIndex === 0 && tmpl.push('<tr>');
  18039. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  18040. tempIndex === 2 && tmpl.push('</tr>');
  18041. }
  18042. return '<div id="##" class="edui-cellalignpicker %%">' +
  18043. '<div class="edui-cellalignpicker-body">' +
  18044. '<table onclick="$$._onClick(event);">' +
  18045. tmpl.join('') +
  18046. '</table>' +
  18047. '</div>' +
  18048. '</div>';
  18049. },
  18050. getStateDom: function (){
  18051. return this.target;
  18052. },
  18053. _onClick: function (evt){
  18054. var target= evt.target || evt.srcElement;
  18055. if(/icon/.test(target.className)){
  18056. this.items[target.parentNode.getAttribute("index")].onclick();
  18057. Popup.postHide(evt);
  18058. }
  18059. },
  18060. _UIBase_render:UIBase.prototype.render
  18061. };
  18062. utils.inherits(CellAlignPicker, UIBase);
  18063. utils.extend(CellAlignPicker.prototype, Stateful,true);
  18064. })();
  18065. ///import core
  18066. ///import uicore
  18067. (function () {
  18068. var utils = baidu.editor.utils,
  18069. Stateful = baidu.editor.ui.Stateful,
  18070. uiUtils = baidu.editor.ui.uiUtils,
  18071. UIBase = baidu.editor.ui.UIBase;
  18072. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  18073. this.initOptions(options);
  18074. this.initPastePicker();
  18075. };
  18076. PastePicker.prototype = {
  18077. initPastePicker:function () {
  18078. this.initUIBase();
  18079. this.Stateful_init();
  18080. },
  18081. getHtmlTpl:function () {
  18082. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  18083. '<div class="edui-pastecontainer">' +
  18084. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  18085. '<div class="edui-button">' +
  18086. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  18087. '<div class="edui-richtxticon"></div></div>' +
  18088. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  18089. '<div class="edui-tagicon"></div></div>' +
  18090. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  18091. '<div class="edui-plaintxticon"></div></div>' +
  18092. '</div>' +
  18093. '</div>' +
  18094. '</div>'
  18095. },
  18096. getStateDom:function () {
  18097. return this.target;
  18098. },
  18099. format:function (param) {
  18100. this.editor.ui._isTransfer = true;
  18101. this.editor.fireEvent('pasteTransfer', param);
  18102. },
  18103. _onClick:function (cur) {
  18104. var node = domUtils.getNextDomNode(cur),
  18105. screenHt = uiUtils.getViewportRect().height,
  18106. subPop = uiUtils.getClientRect(node);
  18107. if ((subPop.top + subPop.height) > screenHt)
  18108. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  18109. else
  18110. node.style.top = "";
  18111. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  18112. node.style.visibility = "visible";
  18113. domUtils.addClass(cur, "edui-state-opened");
  18114. } else {
  18115. node.style.visibility = "hidden";
  18116. domUtils.removeClasses(cur, "edui-state-opened")
  18117. }
  18118. },
  18119. _UIBase_render:UIBase.prototype.render
  18120. };
  18121. utils.inherits(PastePicker, UIBase);
  18122. utils.extend(PastePicker.prototype, Stateful, true);
  18123. })();
  18124. (function (){
  18125. var utils = baidu.editor.utils,
  18126. uiUtils = baidu.editor.ui.uiUtils,
  18127. UIBase = baidu.editor.ui.UIBase,
  18128. Toolbar = baidu.editor.ui.Toolbar = function (options){
  18129. this.initOptions(options);
  18130. this.initToolbar();
  18131. };
  18132. Toolbar.prototype = {
  18133. items: null,
  18134. initToolbar: function (){
  18135. this.items = this.items || [];
  18136. this.initUIBase();
  18137. },
  18138. add: function (item){
  18139. this.items.push(item);
  18140. },
  18141. getHtmlTpl: function (){
  18142. var buff = [];
  18143. for (var i=0; i<this.items.length; i++) {
  18144. buff[i] = this.items[i].renderHtml();
  18145. }
  18146. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  18147. buff.join('') +
  18148. '</div>'
  18149. },
  18150. postRender: function (){
  18151. var box = this.getDom();
  18152. for (var i=0; i<this.items.length; i++) {
  18153. this.items[i].postRender();
  18154. }
  18155. uiUtils.makeUnselectable(box);
  18156. },
  18157. _onMouseDown: function (){
  18158. return false;
  18159. }
  18160. };
  18161. utils.inherits(Toolbar, UIBase);
  18162. })();
  18163. ///import core
  18164. ///import uicore
  18165. ///import ui\popup.js
  18166. ///import ui\stateful.js
  18167. (function () {
  18168. var utils = baidu.editor.utils,
  18169. domUtils = baidu.editor.dom.domUtils,
  18170. uiUtils = baidu.editor.ui.uiUtils,
  18171. UIBase = baidu.editor.ui.UIBase,
  18172. Popup = baidu.editor.ui.Popup,
  18173. Stateful = baidu.editor.ui.Stateful,
  18174. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  18175. Menu = baidu.editor.ui.Menu = function (options) {
  18176. this.initOptions(options);
  18177. this.initMenu();
  18178. };
  18179. var menuSeparator = {
  18180. renderHtml:function () {
  18181. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  18182. },
  18183. postRender:function () {
  18184. },
  18185. queryAutoHide:function () {
  18186. return true;
  18187. }
  18188. };
  18189. Menu.prototype = {
  18190. items:null,
  18191. uiName:'menu',
  18192. initMenu:function () {
  18193. this.items = this.items || [];
  18194. this.initPopup();
  18195. this.initItems();
  18196. },
  18197. initItems:function () {
  18198. for (var i = 0; i < this.items.length; i++) {
  18199. var item = this.items[i];
  18200. if (item == '-') {
  18201. this.items[i] = this.getSeparator();
  18202. } else if (!(item instanceof MenuItem)) {
  18203. item.editor = this.editor;
  18204. item.theme = this.editor.options.theme;
  18205. this.items[i] = this.createItem(item);
  18206. }
  18207. }
  18208. },
  18209. getSeparator:function () {
  18210. return menuSeparator;
  18211. },
  18212. createItem:function (item) {
  18213. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  18214. item.menu = this;
  18215. return new MenuItem(item);
  18216. },
  18217. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  18218. getContentHtmlTpl:function () {
  18219. if (this.items.length == 0) {
  18220. return this._Popup_getContentHtmlTpl();
  18221. }
  18222. var buff = [];
  18223. for (var i = 0; i < this.items.length; i++) {
  18224. var item = this.items[i];
  18225. buff[i] = item.renderHtml();
  18226. }
  18227. return ('<div class="%%-body">' + buff.join('') + '</div>');
  18228. },
  18229. _Popup_postRender:Popup.prototype.postRender,
  18230. postRender:function () {
  18231. var me = this;
  18232. for (var i = 0; i < this.items.length; i++) {
  18233. var item = this.items[i];
  18234. item.ownerMenu = this;
  18235. item.postRender();
  18236. }
  18237. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  18238. evt = evt || event;
  18239. var rel = evt.relatedTarget || evt.fromElement;
  18240. var el = me.getDom();
  18241. if (!uiUtils.contains(el, rel) && el !== rel) {
  18242. me.fireEvent('over');
  18243. }
  18244. });
  18245. this._Popup_postRender();
  18246. },
  18247. queryAutoHide:function (el) {
  18248. if (el) {
  18249. if (uiUtils.contains(this.getDom(), el)) {
  18250. return false;
  18251. }
  18252. for (var i = 0; i < this.items.length; i++) {
  18253. var item = this.items[i];
  18254. if (item.queryAutoHide(el) === false) {
  18255. return false;
  18256. }
  18257. }
  18258. }
  18259. },
  18260. clearItems:function () {
  18261. for (var i = 0; i < this.items.length; i++) {
  18262. var item = this.items[i];
  18263. clearTimeout(item._showingTimer);
  18264. clearTimeout(item._closingTimer);
  18265. if (item.subMenu) {
  18266. item.subMenu.destroy();
  18267. }
  18268. }
  18269. this.items = [];
  18270. },
  18271. destroy:function () {
  18272. if (this.getDom()) {
  18273. domUtils.remove(this.getDom());
  18274. }
  18275. this.clearItems();
  18276. },
  18277. dispose:function () {
  18278. this.destroy();
  18279. }
  18280. };
  18281. utils.inherits(Menu, Popup);
  18282. /**
  18283. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  18284. * @type {Function}
  18285. */
  18286. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  18287. this.initOptions(options);
  18288. this.initUIBase();
  18289. this.Stateful_init();
  18290. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  18291. if (options.className && options.className.indexOf("aligntd") != -1) {
  18292. var me = this;
  18293. //获取单元格对齐初始状态
  18294. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  18295. this.subMenu = new Popup({
  18296. content:new CellAlignPicker(this.subMenu),
  18297. parentMenu:me,
  18298. editor:me.editor,
  18299. destroy:function () {
  18300. if (this.getDom()) {
  18301. domUtils.remove(this.getDom());
  18302. }
  18303. }
  18304. });
  18305. this.subMenu.addListener("postRenderAfter", function () {
  18306. domUtils.on(this.getDom(), "mouseover", function () {
  18307. me.addState('opened');
  18308. });
  18309. });
  18310. } else {
  18311. this.subMenu = new Menu(this.subMenu);
  18312. }
  18313. }
  18314. };
  18315. MenuItem.prototype = {
  18316. label:'',
  18317. subMenu:null,
  18318. ownerMenu:null,
  18319. uiName:'menuitem',
  18320. alwalysHoverable:true,
  18321. getHtmlTpl:function () {
  18322. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  18323. '<div class="%%-body">' +
  18324. this.renderLabelHtml() +
  18325. '</div>' +
  18326. '</div>';
  18327. },
  18328. postRender:function () {
  18329. var me = this;
  18330. this.addListener('over', function () {
  18331. me.ownerMenu.fireEvent('submenuover', me);
  18332. if (me.subMenu) {
  18333. me.delayShowSubMenu();
  18334. }
  18335. });
  18336. if (this.subMenu) {
  18337. this.getDom().className += ' edui-hassubmenu';
  18338. this.subMenu.render();
  18339. this.addListener('out', function () {
  18340. me.delayHideSubMenu();
  18341. });
  18342. this.subMenu.addListener('over', function () {
  18343. clearTimeout(me._closingTimer);
  18344. me._closingTimer = null;
  18345. me.addState('opened');
  18346. });
  18347. this.ownerMenu.addListener('hide', function () {
  18348. me.hideSubMenu();
  18349. });
  18350. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  18351. if (subMenu !== me) {
  18352. me.delayHideSubMenu();
  18353. }
  18354. });
  18355. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  18356. this.subMenu.queryAutoHide = function (el) {
  18357. if (el && uiUtils.contains(me.getDom(), el)) {
  18358. return false;
  18359. }
  18360. return this._bakQueryAutoHide(el);
  18361. };
  18362. }
  18363. this.getDom().style.tabIndex = '-1';
  18364. uiUtils.makeUnselectable(this.getDom());
  18365. this.Stateful_postRender();
  18366. },
  18367. delayShowSubMenu:function () {
  18368. var me = this;
  18369. if (!me.isDisabled()) {
  18370. me.addState('opened');
  18371. clearTimeout(me._showingTimer);
  18372. clearTimeout(me._closingTimer);
  18373. me._closingTimer = null;
  18374. me._showingTimer = setTimeout(function () {
  18375. me.showSubMenu();
  18376. }, 250);
  18377. }
  18378. },
  18379. delayHideSubMenu:function () {
  18380. var me = this;
  18381. if (!me.isDisabled()) {
  18382. me.removeState('opened');
  18383. clearTimeout(me._showingTimer);
  18384. if (!me._closingTimer) {
  18385. me._closingTimer = setTimeout(function () {
  18386. if (!me.hasState('opened')) {
  18387. me.hideSubMenu();
  18388. }
  18389. me._closingTimer = null;
  18390. }, 400);
  18391. }
  18392. }
  18393. },
  18394. renderLabelHtml:function () {
  18395. return '<div class="edui-arrow"></div>' +
  18396. '<div class="edui-box edui-icon"></div>' +
  18397. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  18398. },
  18399. getStateDom:function () {
  18400. return this.getDom();
  18401. },
  18402. queryAutoHide:function (el) {
  18403. if (this.subMenu && this.hasState('opened')) {
  18404. return this.subMenu.queryAutoHide(el);
  18405. }
  18406. },
  18407. _onClick:function (event, this_) {
  18408. if (this.hasState('disabled')) return;
  18409. if (this.fireEvent('click', event, this_) !== false) {
  18410. if (this.subMenu) {
  18411. this.showSubMenu();
  18412. } else {
  18413. Popup.postHide(event);
  18414. }
  18415. }
  18416. },
  18417. showSubMenu:function () {
  18418. var rect = uiUtils.getClientRect(this.getDom());
  18419. rect.right -= 5;
  18420. rect.left += 2;
  18421. rect.width -= 7;
  18422. rect.top -= 4;
  18423. rect.bottom += 4;
  18424. rect.height += 8;
  18425. this.subMenu.showAnchorRect(rect, true, true);
  18426. },
  18427. hideSubMenu:function () {
  18428. this.subMenu.hide();
  18429. }
  18430. };
  18431. utils.inherits(MenuItem, UIBase);
  18432. utils.extend(MenuItem.prototype, Stateful, true);
  18433. })();
  18434. ///import core
  18435. ///import uicore
  18436. ///import ui/menu.js
  18437. ///import ui/splitbutton.js
  18438. (function (){
  18439. // todo: menu和item提成通用list
  18440. var utils = baidu.editor.utils,
  18441. uiUtils = baidu.editor.ui.uiUtils,
  18442. Menu = baidu.editor.ui.Menu,
  18443. SplitButton = baidu.editor.ui.SplitButton,
  18444. Combox = baidu.editor.ui.Combox = function (options){
  18445. this.initOptions(options);
  18446. this.initCombox();
  18447. };
  18448. Combox.prototype = {
  18449. uiName: 'combox',
  18450. initCombox: function (){
  18451. var me = this;
  18452. this.items = this.items || [];
  18453. for (var i=0; i<this.items.length; i++) {
  18454. var item = this.items[i];
  18455. item.uiName = 'listitem';
  18456. item.index = i;
  18457. item.onclick = function (){
  18458. me.selectByIndex(this.index);
  18459. };
  18460. }
  18461. this.popup = new Menu({
  18462. items: this.items,
  18463. uiName: 'list',
  18464. editor:this.editor,
  18465. captureWheel: true,
  18466. combox: this
  18467. });
  18468. this.initSplitButton();
  18469. },
  18470. _SplitButton_postRender: SplitButton.prototype.postRender,
  18471. postRender: function (){
  18472. this._SplitButton_postRender();
  18473. this.setLabel(this.label || '');
  18474. this.setValue(this.initValue || '');
  18475. },
  18476. showPopup: function (){
  18477. var rect = uiUtils.getClientRect(this.getDom());
  18478. rect.top += 1;
  18479. rect.bottom -= 1;
  18480. rect.height -= 2;
  18481. this.popup.showAnchorRect(rect);
  18482. },
  18483. getValue: function (){
  18484. return this.value;
  18485. },
  18486. setValue: function (value){
  18487. var index = this.indexByValue(value);
  18488. if (index != -1) {
  18489. this.selectedIndex = index;
  18490. this.setLabel(this.items[index].label);
  18491. this.value = this.items[index].value;
  18492. } else {
  18493. this.selectedIndex = -1;
  18494. this.setLabel(this.getLabelForUnknowValue(value));
  18495. this.value = value;
  18496. }
  18497. },
  18498. setLabel: function (label){
  18499. this.getDom('button_body').innerHTML = label;
  18500. this.label = label;
  18501. },
  18502. getLabelForUnknowValue: function (value){
  18503. return value;
  18504. },
  18505. indexByValue: function (value){
  18506. for (var i=0; i<this.items.length; i++) {
  18507. if (value == this.items[i].value) {
  18508. return i;
  18509. }
  18510. }
  18511. return -1;
  18512. },
  18513. getItem: function (index){
  18514. return this.items[index];
  18515. },
  18516. selectByIndex: function (index){
  18517. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  18518. this.selectedIndex = index;
  18519. this.value = this.items[index].value;
  18520. this.setLabel(this.items[index].label);
  18521. }
  18522. }
  18523. };
  18524. utils.inherits(Combox, SplitButton);
  18525. })();
  18526. ///import core
  18527. ///import uicore
  18528. ///import ui/mask.js
  18529. ///import ui/button.js
  18530. (function (){
  18531. var utils = baidu.editor.utils,
  18532. domUtils = baidu.editor.dom.domUtils,
  18533. uiUtils = baidu.editor.ui.uiUtils,
  18534. Mask = baidu.editor.ui.Mask,
  18535. UIBase = baidu.editor.ui.UIBase,
  18536. Button = baidu.editor.ui.Button,
  18537. Dialog = baidu.editor.ui.Dialog = function (options){
  18538. this.initOptions(utils.extend({
  18539. autoReset: true,
  18540. draggable: true,
  18541. onok: function (){},
  18542. oncancel: function (){},
  18543. onclose: function (t, ok){
  18544. return ok ? this.onok() : this.oncancel();
  18545. },
  18546. //是否控制dialog中的scroll事件, 默认为不阻止
  18547. holdScroll: false
  18548. },options));
  18549. this.initDialog();
  18550. };
  18551. var modalMask;
  18552. var dragMask;
  18553. Dialog.prototype = {
  18554. draggable: false,
  18555. uiName: 'dialog',
  18556. initDialog: function (){
  18557. var me = this,
  18558. theme=this.editor.options.theme;
  18559. this.initUIBase();
  18560. this.modalMask = (modalMask || (modalMask = new Mask({
  18561. className: 'edui-dialog-modalmask',
  18562. theme:theme
  18563. })));
  18564. this.dragMask = (dragMask || (dragMask = new Mask({
  18565. className: 'edui-dialog-dragmask',
  18566. theme:theme
  18567. })));
  18568. this.closeButton = new Button({
  18569. className: 'edui-dialog-closebutton',
  18570. title: me.closeDialog,
  18571. theme:theme,
  18572. onclick: function (){
  18573. me.close(false);
  18574. }
  18575. });
  18576. this.fullscreen && this.initResizeEvent();
  18577. if (this.buttons) {
  18578. for (var i=0; i<this.buttons.length; i++) {
  18579. if (!(this.buttons[i] instanceof Button)) {
  18580. this.buttons[i] = new Button(this.buttons[i]);
  18581. }
  18582. }
  18583. }
  18584. },
  18585. initResizeEvent: function () {
  18586. var me = this;
  18587. domUtils.on( window, "resize", function () {
  18588. if ( me._hidden || me._hidden === undefined ) {
  18589. return;
  18590. }
  18591. if ( me.__resizeTimer ) {
  18592. window.clearTimeout( me.__resizeTimer );
  18593. }
  18594. me.__resizeTimer = window.setTimeout( function () {
  18595. me.__resizeTimer = null;
  18596. var dialogWrapNode = me.getDom(),
  18597. contentNode = me.getDom('content'),
  18598. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  18599. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  18600. vpRect = uiUtils.getViewportRect();
  18601. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  18602. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  18603. dialogWrapNode.style.width = vpRect.width + "px";
  18604. dialogWrapNode.style.height = vpRect.height + "px";
  18605. me.fireEvent( "resize" );
  18606. }, 100 );
  18607. } );
  18608. },
  18609. fitSize: function (){
  18610. var popBodyEl = this.getDom('body');
  18611. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  18612. // uiUtils.removeStyle(popBodyEl, 'width');
  18613. // uiUtils.removeStyle(popBodyEl, 'height');
  18614. // }
  18615. var size = this.mesureSize();
  18616. popBodyEl.style.width = size.width + 'px';
  18617. popBodyEl.style.height = size.height + 'px';
  18618. return size;
  18619. },
  18620. safeSetOffset: function (offset){
  18621. var me = this;
  18622. var el = me.getDom();
  18623. var vpRect = uiUtils.getViewportRect();
  18624. var rect = uiUtils.getClientRect(el);
  18625. var left = offset.left;
  18626. if (left + rect.width > vpRect.right) {
  18627. left = vpRect.right - rect.width;
  18628. }
  18629. var top = offset.top;
  18630. if (top + rect.height > vpRect.bottom) {
  18631. top = vpRect.bottom - rect.height;
  18632. }
  18633. el.style.left = Math.max(left, 0) + 'px';
  18634. el.style.top = Math.max(top, 0) + 'px';
  18635. },
  18636. showAtCenter: function (){
  18637. var vpRect = uiUtils.getViewportRect();
  18638. if ( !this.fullscreen ) {
  18639. this.getDom().style.display = '';
  18640. var popSize = this.fitSize();
  18641. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  18642. var left = vpRect.width / 2 - popSize.width / 2;
  18643. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  18644. var popEl = this.getDom();
  18645. this.safeSetOffset({
  18646. left: Math.max(left | 0, 0),
  18647. top: Math.max(top | 0, 0)
  18648. });
  18649. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  18650. popEl.className += ' edui-state-centered';
  18651. }
  18652. } else {
  18653. var dialogWrapNode = this.getDom(),
  18654. contentNode = this.getDom('content');
  18655. dialogWrapNode.style.display = "block";
  18656. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  18657. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  18658. dialogWrapNode.style.left = "-100000px";
  18659. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  18660. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  18661. dialogWrapNode.style.width = vpRect.width + "px";
  18662. dialogWrapNode.style.height = vpRect.height + "px";
  18663. dialogWrapNode.style.left = 0;
  18664. //保存环境的overflow值
  18665. this._originalContext = {
  18666. html: {
  18667. overflowX: document.documentElement.style.overflowX,
  18668. overflowY: document.documentElement.style.overflowY
  18669. },
  18670. body: {
  18671. overflowX: document.body.style.overflowX,
  18672. overflowY: document.body.style.overflowY
  18673. }
  18674. };
  18675. document.documentElement.style.overflowX = 'hidden';
  18676. document.documentElement.style.overflowY = 'hidden';
  18677. document.body.style.overflowX = 'hidden';
  18678. document.body.style.overflowY = 'hidden';
  18679. }
  18680. this._show();
  18681. },
  18682. getContentHtml: function (){
  18683. var contentHtml = '';
  18684. if (typeof this.content == 'string') {
  18685. contentHtml = this.content;
  18686. } else if (this.iframeUrl) {
  18687. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  18688. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  18689. }
  18690. return contentHtml;
  18691. },
  18692. getHtmlTpl: function (){
  18693. var footHtml = '';
  18694. if (this.buttons) {
  18695. var buff = [];
  18696. for (var i=0; i<this.buttons.length; i++) {
  18697. buff[i] = this.buttons[i].renderHtml();
  18698. }
  18699. footHtml = '<div class="%%-foot">' +
  18700. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  18701. '</div>';
  18702. }
  18703. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  18704. '<div class="%%-shadow"></div>' +
  18705. '<div id="##_titlebar" class="%%-titlebar">' +
  18706. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  18707. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  18708. '</div>' +
  18709. this.closeButton.renderHtml() +
  18710. '</div>' +
  18711. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  18712. footHtml +
  18713. '</div></div></div>';
  18714. },
  18715. postRender: function (){
  18716. // todo: 保持居中/记住上次关闭位置选项
  18717. if (!this.modalMask.getDom()) {
  18718. this.modalMask.render();
  18719. this.modalMask.hide();
  18720. }
  18721. if (!this.dragMask.getDom()) {
  18722. this.dragMask.render();
  18723. this.dragMask.hide();
  18724. }
  18725. var me = this;
  18726. this.addListener('show', function (){
  18727. me.modalMask.show(this.getDom().style.zIndex - 2);
  18728. });
  18729. this.addListener('hide', function (){
  18730. me.modalMask.hide();
  18731. });
  18732. if (this.buttons) {
  18733. for (var i=0; i<this.buttons.length; i++) {
  18734. this.buttons[i].postRender();
  18735. }
  18736. }
  18737. domUtils.on(window, 'resize', function (){
  18738. setTimeout(function (){
  18739. if (!me.isHidden()) {
  18740. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  18741. }
  18742. });
  18743. });
  18744. //hold住scroll事件,防止dialog的滚动影响页面
  18745. if( this.holdScroll ) {
  18746. if( !me.iframeUrl ) {
  18747. domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18748. domUtils.preventDefault(e);
  18749. } );
  18750. } else {
  18751. me.addListener('dialogafterreset', function(){
  18752. window.setTimeout(function(){
  18753. var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  18754. if( browser.ie ) {
  18755. var timer = window.setInterval(function(){
  18756. if( iframeWindow.document && iframeWindow.document.body ) {
  18757. window.clearInterval( timer );
  18758. timer = null;
  18759. domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18760. domUtils.preventDefault(e);
  18761. } );
  18762. }
  18763. }, 100);
  18764. } else {
  18765. domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18766. domUtils.preventDefault(e);
  18767. } );
  18768. }
  18769. }, 1);
  18770. });
  18771. }
  18772. }
  18773. this._hide();
  18774. },
  18775. mesureSize: function (){
  18776. var body = this.getDom('body');
  18777. var width = uiUtils.getClientRect(this.getDom('content')).width;
  18778. var dialogBodyStyle = body.style;
  18779. dialogBodyStyle.width = width;
  18780. return uiUtils.getClientRect(body);
  18781. },
  18782. _onTitlebarMouseDown: function (evt, el){
  18783. if (this.draggable) {
  18784. var rect;
  18785. var vpRect = uiUtils.getViewportRect();
  18786. var me = this;
  18787. uiUtils.startDrag(evt, {
  18788. ondragstart: function (){
  18789. rect = uiUtils.getClientRect(me.getDom());
  18790. me.getDom('contmask').style.visibility = 'visible';
  18791. me.dragMask.show(me.getDom().style.zIndex - 1);
  18792. },
  18793. ondragmove: function (x, y){
  18794. var left = rect.left + x;
  18795. var top = rect.top + y;
  18796. me.safeSetOffset({
  18797. left: left,
  18798. top: top
  18799. });
  18800. },
  18801. ondragstop: function (){
  18802. me.getDom('contmask').style.visibility = 'hidden';
  18803. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  18804. me.dragMask.hide();
  18805. }
  18806. });
  18807. }
  18808. },
  18809. reset: function (){
  18810. this.getDom('content').innerHTML = this.getContentHtml();
  18811. this.fireEvent('dialogafterreset');
  18812. },
  18813. _show: function (){
  18814. if (this._hidden) {
  18815. this.getDom().style.display = '';
  18816. //要高过编辑器的zindxe
  18817. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  18818. this._hidden = false;
  18819. this.fireEvent('show');
  18820. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  18821. }
  18822. },
  18823. isHidden: function (){
  18824. return this._hidden;
  18825. },
  18826. _hide: function (){
  18827. if (!this._hidden) {
  18828. var wrapNode = this.getDom();
  18829. wrapNode.style.display = 'none';
  18830. wrapNode.style.zIndex = '';
  18831. wrapNode.style.width = '';
  18832. wrapNode.style.height = '';
  18833. this._hidden = true;
  18834. this.fireEvent('hide');
  18835. }
  18836. },
  18837. open: function (){
  18838. if (this.autoReset) {
  18839. //有可能还没有渲染
  18840. try{
  18841. this.reset();
  18842. }catch(e){
  18843. this.render();
  18844. this.open()
  18845. }
  18846. }
  18847. this.showAtCenter();
  18848. if (this.iframeUrl) {
  18849. try {
  18850. this.getDom('iframe').focus();
  18851. } catch(ex){}
  18852. }
  18853. },
  18854. _onCloseButtonClick: function (evt, el){
  18855. this.close(false);
  18856. },
  18857. close: function (ok){
  18858. if (this.fireEvent('close', ok) !== false) {
  18859. //还原环境
  18860. if ( this.fullscreen ) {
  18861. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  18862. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  18863. document.body.style.overflowX = this._originalContext.body.overflowX;
  18864. document.body.style.overflowY = this._originalContext.body.overflowY;
  18865. delete this._originalContext;
  18866. }
  18867. this._hide();
  18868. }
  18869. }
  18870. };
  18871. utils.inherits(Dialog, UIBase);
  18872. })();
  18873. ///import core
  18874. ///import uicore
  18875. ///import ui/menu.js
  18876. ///import ui/splitbutton.js
  18877. (function (){
  18878. var utils = baidu.editor.utils,
  18879. Menu = baidu.editor.ui.Menu,
  18880. SplitButton = baidu.editor.ui.SplitButton,
  18881. MenuButton = baidu.editor.ui.MenuButton = function (options){
  18882. this.initOptions(options);
  18883. this.initMenuButton();
  18884. };
  18885. MenuButton.prototype = {
  18886. initMenuButton: function (){
  18887. var me = this;
  18888. this.uiName = "menubutton";
  18889. this.popup = new Menu({
  18890. items: me.items,
  18891. className: me.className,
  18892. editor:me.editor
  18893. });
  18894. this.popup.addListener('show', function (){
  18895. var list = this;
  18896. for (var i=0; i<list.items.length; i++) {
  18897. list.items[i].removeState('checked');
  18898. if (list.items[i].value == me._value) {
  18899. list.items[i].addState('checked');
  18900. this.value = me._value;
  18901. }
  18902. }
  18903. });
  18904. this.initSplitButton();
  18905. },
  18906. setValue : function(value){
  18907. this._value = value;
  18908. }
  18909. };
  18910. utils.inherits(MenuButton, SplitButton);
  18911. })();
  18912. //ui跟编辑器的适配層
  18913. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  18914. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  18915. (function () {
  18916. var utils = baidu.editor.utils;
  18917. var editorui = baidu.editor.ui;
  18918. var _Dialog = editorui.Dialog;
  18919. editorui.buttons = {};
  18920. editorui.Dialog = function (options) {
  18921. var dialog = new _Dialog(options);
  18922. dialog.addListener('hide', function () {
  18923. if (dialog.editor) {
  18924. var editor = dialog.editor;
  18925. try {
  18926. if (browser.gecko) {
  18927. var y = editor.window.scrollY,
  18928. x = editor.window.scrollX;
  18929. editor.body.focus();
  18930. editor.window.scrollTo(x, y);
  18931. } else {
  18932. editor.focus();
  18933. }
  18934. } catch (ex) {
  18935. }
  18936. }
  18937. });
  18938. return dialog;
  18939. };
  18940. var iframeUrlMap = {
  18941. 'anchor':'~/dialogs/anchor/anchor.html',
  18942. 'insertimage':'~/dialogs/image/image.html',
  18943. 'link':'~/dialogs/link/link.html',
  18944. 'spechars':'~/dialogs/spechars/spechars.html',
  18945. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  18946. 'map':'~/dialogs/map/map.html',
  18947. 'gmap':'~/dialogs/gmap/gmap.html',
  18948. 'insertvideo':'~/dialogs/video/video.html',
  18949. 'help':'~/dialogs/help/help.html',
  18950. 'preview':'~/dialogs/preview/preview.html',
  18951. 'emotion':'~/dialogs/emotion/emotion.html',
  18952. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  18953. 'attachment':'~/dialogs/attachment/attachment.html',
  18954. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  18955. 'edittip':'~/dialogs/table/edittip.html',
  18956. 'edittable':'~/dialogs/table/edittable.html',
  18957. 'edittd':'~/dialogs/table/edittd.html',
  18958. 'webapp':'~/dialogs/webapp/webapp.html',
  18959. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  18960. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  18961. 'music':'~/dialogs/music/music.html',
  18962. 'template':'~/dialogs/template/template.html',
  18963. 'background':'~/dialogs/background/background.html',
  18964. 'charts': '~/dialogs/charts/charts.html'
  18965. };
  18966. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  18967. var btnCmds = ['undo', 'redo', 'formatmatch',
  18968. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  18969. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  18970. 'blockquote', 'pasteplain', 'pagebreak',
  18971. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  18972. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  18973. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  18974. for (var i = 0, ci; ci = btnCmds[i++];) {
  18975. ci = ci.toLowerCase();
  18976. editorui[ci] = function (cmd) {
  18977. return function (editor) {
  18978. var ui = new editorui.Button({
  18979. className:'edui-for-' + cmd,
  18980. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  18981. onclick:function () {
  18982. editor.execCommand(cmd);
  18983. },
  18984. theme:editor.options.theme,
  18985. showText:false
  18986. });
  18987. editorui.buttons[cmd] = ui;
  18988. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18989. var state = editor.queryCommandState(cmd);
  18990. if (state == -1) {
  18991. ui.setDisabled(true);
  18992. ui.setChecked(false);
  18993. } else {
  18994. if (!uiReady) {
  18995. ui.setDisabled(false);
  18996. ui.setChecked(state);
  18997. }
  18998. }
  18999. });
  19000. return ui;
  19001. };
  19002. }(ci);
  19003. }
  19004. //清除文档
  19005. editorui.cleardoc = function (editor) {
  19006. var ui = new editorui.Button({
  19007. className:'edui-for-cleardoc',
  19008. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  19009. theme:editor.options.theme,
  19010. onclick:function () {
  19011. if (confirm(editor.getLang("confirmClear"))) {
  19012. editor.execCommand('cleardoc');
  19013. }
  19014. }
  19015. });
  19016. editorui.buttons["cleardoc"] = ui;
  19017. editor.addListener('selectionchange', function () {
  19018. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  19019. });
  19020. return ui;
  19021. };
  19022. //排版,图片排版,文字方向
  19023. var typeset = {
  19024. 'justify':['left', 'right', 'center', 'justify'],
  19025. 'imagefloat':['none', 'left', 'center', 'right'],
  19026. 'directionality':['ltr', 'rtl']
  19027. };
  19028. for (var p in typeset) {
  19029. (function (cmd, val) {
  19030. for (var i = 0, ci; ci = val[i++];) {
  19031. (function (cmd2) {
  19032. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  19033. var ui = new editorui.Button({
  19034. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  19035. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  19036. theme:editor.options.theme,
  19037. onclick:function () {
  19038. editor.execCommand(cmd, cmd2);
  19039. }
  19040. });
  19041. editorui.buttons[cmd] = ui;
  19042. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19043. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  19044. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  19045. });
  19046. return ui;
  19047. };
  19048. })(ci)
  19049. }
  19050. })(p, typeset[p])
  19051. }
  19052. //字体颜色和背景颜色
  19053. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  19054. editorui[ci] = function (cmd) {
  19055. return function (editor) {
  19056. var ui = new editorui.ColorButton({
  19057. className:'edui-for-' + cmd,
  19058. color:'default',
  19059. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  19060. editor:editor,
  19061. onpickcolor:function (t, color) {
  19062. editor.execCommand(cmd, color);
  19063. },
  19064. onpicknocolor:function () {
  19065. editor.execCommand(cmd, 'default');
  19066. this.setColor('transparent');
  19067. this.color = 'default';
  19068. },
  19069. onbuttonclick:function () {
  19070. editor.execCommand(cmd, this.color);
  19071. }
  19072. });
  19073. editorui.buttons[cmd] = ui;
  19074. editor.addListener('selectionchange', function () {
  19075. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  19076. });
  19077. return ui;
  19078. };
  19079. }(ci);
  19080. }
  19081. var dialogBtns = {
  19082. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  19083. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  19084. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  19085. };
  19086. for (var p in dialogBtns) {
  19087. (function (type, vals) {
  19088. for (var i = 0, ci; ci = vals[i++];) {
  19089. //todo opera下存在问题
  19090. if (browser.opera && ci === "searchreplace") {
  19091. continue;
  19092. }
  19093. (function (cmd) {
  19094. editorui[cmd] = function (editor, iframeUrl, title) {
  19095. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  19096. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  19097. var dialog;
  19098. //没有iframeUrl不创建dialog
  19099. if (iframeUrl) {
  19100. dialog = new editorui.Dialog(utils.extend({
  19101. iframeUrl:editor.ui.mapUrl(iframeUrl),
  19102. editor:editor,
  19103. className:'edui-for-' + cmd,
  19104. title:title,
  19105. holdScroll: cmd === 'insertimage',
  19106. fullscreen: /charts|preview/.test(cmd),
  19107. closeDialog:editor.getLang("closeDialog")
  19108. }, type == 'ok' ? {
  19109. buttons:[
  19110. {
  19111. className:'edui-okbutton',
  19112. label:editor.getLang("ok"),
  19113. editor:editor,
  19114. onclick:function () {
  19115. dialog.close(true);
  19116. }
  19117. },
  19118. {
  19119. className:'edui-cancelbutton',
  19120. label:editor.getLang("cancel"),
  19121. editor:editor,
  19122. onclick:function () {
  19123. dialog.close(false);
  19124. }
  19125. }
  19126. ]
  19127. } : {}));
  19128. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  19129. }
  19130. var ui = new editorui.Button({
  19131. className:'edui-for-' + cmd,
  19132. title:title,
  19133. onclick:function () {
  19134. if (dialog) {
  19135. switch (cmd) {
  19136. case "wordimage":
  19137. var images = editor.execCommand("wordimage");
  19138. if (images && images.length) {
  19139. dialog.render();
  19140. dialog.open();
  19141. }
  19142. break;
  19143. case "scrawl":
  19144. if (editor.queryCommandState("scrawl") != -1) {
  19145. dialog.render();
  19146. dialog.open();
  19147. }
  19148. break;
  19149. default:
  19150. dialog.render();
  19151. dialog.open();
  19152. }
  19153. }
  19154. },
  19155. theme:editor.options.theme,
  19156. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  19157. });
  19158. editorui.buttons[cmd] = ui;
  19159. editor.addListener('selectionchange', function () {
  19160. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  19161. var unNeedCheckState = {'edittable':1};
  19162. if (cmd in unNeedCheckState)return;
  19163. var state = editor.queryCommandState(cmd);
  19164. if (ui.getDom()) {
  19165. ui.setDisabled(state == -1);
  19166. ui.setChecked(state);
  19167. }
  19168. });
  19169. return ui;
  19170. };
  19171. })(ci.toLowerCase())
  19172. }
  19173. })(p, dialogBtns[p])
  19174. }
  19175. editorui.snapscreen = function (editor, iframeUrl, title) {
  19176. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  19177. var ui = new editorui.Button({
  19178. className:'edui-for-snapscreen',
  19179. title:title,
  19180. onclick:function () {
  19181. editor.execCommand("snapscreen");
  19182. },
  19183. theme:editor.options.theme
  19184. });
  19185. editorui.buttons['snapscreen'] = ui;
  19186. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  19187. if (iframeUrl) {
  19188. var dialog = new editorui.Dialog({
  19189. iframeUrl:editor.ui.mapUrl(iframeUrl),
  19190. editor:editor,
  19191. className:'edui-for-snapscreen',
  19192. title:title,
  19193. buttons:[
  19194. {
  19195. className:'edui-okbutton',
  19196. label:editor.getLang("ok"),
  19197. editor:editor,
  19198. onclick:function () {
  19199. dialog.close(true);
  19200. }
  19201. },
  19202. {
  19203. className:'edui-cancelbutton',
  19204. label:editor.getLang("cancel"),
  19205. editor:editor,
  19206. onclick:function () {
  19207. dialog.close(false);
  19208. }
  19209. }
  19210. ]
  19211. });
  19212. dialog.render();
  19213. editor.ui._dialogs["snapscreenDialog"] = dialog;
  19214. }
  19215. editor.addListener('selectionchange', function () {
  19216. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  19217. });
  19218. return ui;
  19219. };
  19220. editorui.insertcode = function (editor, list, title) {
  19221. list = editor.options['insertcode'] || [];
  19222. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  19223. // if (!list.length) return;
  19224. var items = [];
  19225. utils.each(list,function(key,val){
  19226. items.push({
  19227. label:key,
  19228. value:val,
  19229. theme:editor.options.theme,
  19230. renderLabelHtml:function () {
  19231. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  19232. }
  19233. });
  19234. });
  19235. var ui = new editorui.Combox({
  19236. editor:editor,
  19237. items:items,
  19238. onselect:function (t, index) {
  19239. editor.execCommand('insertcode', this.items[index].value);
  19240. },
  19241. onbuttonclick:function () {
  19242. this.showPopup();
  19243. },
  19244. title:title,
  19245. initValue:title,
  19246. className:'edui-for-insertcode',
  19247. indexByValue:function (value) {
  19248. if (value) {
  19249. for (var i = 0, ci; ci = this.items[i]; i++) {
  19250. if (ci.value.indexOf(value) != -1)
  19251. return i;
  19252. }
  19253. }
  19254. return -1;
  19255. }
  19256. });
  19257. editorui.buttons['insertcode'] = ui;
  19258. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19259. if (!uiReady) {
  19260. var state = editor.queryCommandState('insertcode');
  19261. if (state == -1) {
  19262. ui.setDisabled(true);
  19263. } else {
  19264. ui.setDisabled(false);
  19265. var value = editor.queryCommandValue('insertcode');
  19266. if(!value){
  19267. ui.setValue(title);
  19268. return;
  19269. }
  19270. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  19271. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  19272. ui.setValue(value);
  19273. }
  19274. }
  19275. });
  19276. return ui;
  19277. };
  19278. editorui.fontfamily = function (editor, list, title) {
  19279. list = editor.options['fontfamily'] || [];
  19280. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  19281. if (!list.length) return;
  19282. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  19283. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  19284. (function (key, val) {
  19285. items.push({
  19286. label:key,
  19287. value:val,
  19288. theme:editor.options.theme,
  19289. renderLabelHtml:function () {
  19290. return '<div class="edui-label %%-label" style="font-family:' +
  19291. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  19292. }
  19293. });
  19294. })(ci.label || langLabel, ci.val)
  19295. }
  19296. var ui = new editorui.Combox({
  19297. editor:editor,
  19298. items:items,
  19299. onselect:function (t, index) {
  19300. editor.execCommand('FontFamily', this.items[index].value);
  19301. },
  19302. onbuttonclick:function () {
  19303. this.showPopup();
  19304. },
  19305. title:title,
  19306. initValue:title,
  19307. className:'edui-for-fontfamily',
  19308. indexByValue:function (value) {
  19309. if (value) {
  19310. for (var i = 0, ci; ci = this.items[i]; i++) {
  19311. if (ci.value.indexOf(value) != -1)
  19312. return i;
  19313. }
  19314. }
  19315. return -1;
  19316. }
  19317. });
  19318. editorui.buttons['fontfamily'] = ui;
  19319. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19320. if (!uiReady) {
  19321. var state = editor.queryCommandState('FontFamily');
  19322. if (state == -1) {
  19323. ui.setDisabled(true);
  19324. } else {
  19325. ui.setDisabled(false);
  19326. var value = editor.queryCommandValue('FontFamily');
  19327. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  19328. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  19329. ui.setValue(value);
  19330. }
  19331. }
  19332. });
  19333. return ui;
  19334. };
  19335. editorui.fontsize = function (editor, list, title) {
  19336. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  19337. list = list || editor.options['fontsize'] || [];
  19338. if (!list.length) return;
  19339. var items = [];
  19340. for (var i = 0; i < list.length; i++) {
  19341. var size = list[i] + 'px';
  19342. items.push({
  19343. label:size,
  19344. value:size,
  19345. theme:editor.options.theme,
  19346. renderLabelHtml:function () {
  19347. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  19348. this.value + '">' + (this.label || '') + '</div>';
  19349. }
  19350. });
  19351. }
  19352. var ui = new editorui.Combox({
  19353. editor:editor,
  19354. items:items,
  19355. title:title,
  19356. initValue:title,
  19357. onselect:function (t, index) {
  19358. editor.execCommand('FontSize', this.items[index].value);
  19359. },
  19360. onbuttonclick:function () {
  19361. this.showPopup();
  19362. },
  19363. className:'edui-for-fontsize'
  19364. });
  19365. editorui.buttons['fontsize'] = ui;
  19366. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19367. if (!uiReady) {
  19368. var state = editor.queryCommandState('FontSize');
  19369. if (state == -1) {
  19370. ui.setDisabled(true);
  19371. } else {
  19372. ui.setDisabled(false);
  19373. ui.setValue(editor.queryCommandValue('FontSize'));
  19374. }
  19375. }
  19376. });
  19377. return ui;
  19378. };
  19379. editorui.paragraph = function (editor, list, title) {
  19380. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  19381. list = editor.options['paragraph'] || [];
  19382. if (utils.isEmptyObject(list)) return;
  19383. var items = [];
  19384. for (var i in list) {
  19385. items.push({
  19386. value:i,
  19387. label:list[i] || editor.getLang("paragraph")[i],
  19388. theme:editor.options.theme,
  19389. renderLabelHtml:function () {
  19390. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  19391. }
  19392. })
  19393. }
  19394. var ui = new editorui.Combox({
  19395. editor:editor,
  19396. items:items,
  19397. title:title,
  19398. initValue:title,
  19399. className:'edui-for-paragraph',
  19400. onselect:function (t, index) {
  19401. editor.execCommand('Paragraph', this.items[index].value);
  19402. },
  19403. onbuttonclick:function () {
  19404. this.showPopup();
  19405. }
  19406. });
  19407. editorui.buttons['paragraph'] = ui;
  19408. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19409. if (!uiReady) {
  19410. var state = editor.queryCommandState('Paragraph');
  19411. if (state == -1) {
  19412. ui.setDisabled(true);
  19413. } else {
  19414. ui.setDisabled(false);
  19415. var value = editor.queryCommandValue('Paragraph');
  19416. var index = ui.indexByValue(value);
  19417. if (index != -1) {
  19418. ui.setValue(value);
  19419. } else {
  19420. ui.setValue(ui.initValue);
  19421. }
  19422. }
  19423. }
  19424. });
  19425. return ui;
  19426. };
  19427. //自定义标题
  19428. editorui.customstyle = function (editor) {
  19429. var list = editor.options['customstyle'] || [],
  19430. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  19431. if (!list.length)return;
  19432. var langCs = editor.getLang('customstyle');
  19433. for (var i = 0, items = [], t; t = list[i++];) {
  19434. (function (t) {
  19435. var ck = {};
  19436. ck.label = t.label ? t.label : langCs[t.name];
  19437. ck.style = t.style;
  19438. ck.className = t.className;
  19439. ck.tag = t.tag;
  19440. items.push({
  19441. label:ck.label,
  19442. value:ck,
  19443. theme:editor.options.theme,
  19444. renderLabelHtml:function () {
  19445. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  19446. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  19447. + '</div>';
  19448. }
  19449. });
  19450. })(t);
  19451. }
  19452. var ui = new editorui.Combox({
  19453. editor:editor,
  19454. items:items,
  19455. title:title,
  19456. initValue:title,
  19457. className:'edui-for-customstyle',
  19458. onselect:function (t, index) {
  19459. editor.execCommand('customstyle', this.items[index].value);
  19460. },
  19461. onbuttonclick:function () {
  19462. this.showPopup();
  19463. },
  19464. indexByValue:function (value) {
  19465. for (var i = 0, ti; ti = this.items[i++];) {
  19466. if (ti.label == value) {
  19467. return i - 1
  19468. }
  19469. }
  19470. return -1;
  19471. }
  19472. });
  19473. editorui.buttons['customstyle'] = ui;
  19474. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19475. if (!uiReady) {
  19476. var state = editor.queryCommandState('customstyle');
  19477. if (state == -1) {
  19478. ui.setDisabled(true);
  19479. } else {
  19480. ui.setDisabled(false);
  19481. var value = editor.queryCommandValue('customstyle');
  19482. var index = ui.indexByValue(value);
  19483. if (index != -1) {
  19484. ui.setValue(value);
  19485. } else {
  19486. ui.setValue(ui.initValue);
  19487. }
  19488. }
  19489. }
  19490. });
  19491. return ui;
  19492. };
  19493. editorui.inserttable = function (editor, iframeUrl, title) {
  19494. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  19495. var ui = new editorui.TableButton({
  19496. editor:editor,
  19497. title:title,
  19498. className:'edui-for-inserttable',
  19499. onpicktable:function (t, numCols, numRows) {
  19500. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  19501. },
  19502. onbuttonclick:function () {
  19503. this.showPopup();
  19504. }
  19505. });
  19506. editorui.buttons['inserttable'] = ui;
  19507. editor.addListener('selectionchange', function () {
  19508. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  19509. });
  19510. return ui;
  19511. };
  19512. editorui.lineheight = function (editor) {
  19513. var val = editor.options.lineheight || [];
  19514. if (!val.length)return;
  19515. for (var i = 0, ci, items = []; ci = val[i++];) {
  19516. items.push({
  19517. //todo:写死了
  19518. label:ci,
  19519. value:ci,
  19520. theme:editor.options.theme,
  19521. onclick:function () {
  19522. editor.execCommand("lineheight", this.value);
  19523. }
  19524. })
  19525. }
  19526. var ui = new editorui.MenuButton({
  19527. editor:editor,
  19528. className:'edui-for-lineheight',
  19529. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  19530. items:items,
  19531. onbuttonclick:function () {
  19532. var value = editor.queryCommandValue('LineHeight') || this.value;
  19533. editor.execCommand("LineHeight", value);
  19534. }
  19535. });
  19536. editorui.buttons['lineheight'] = ui;
  19537. editor.addListener('selectionchange', function () {
  19538. var state = editor.queryCommandState('LineHeight');
  19539. if (state == -1) {
  19540. ui.setDisabled(true);
  19541. } else {
  19542. ui.setDisabled(false);
  19543. var value = editor.queryCommandValue('LineHeight');
  19544. value && ui.setValue((value + '').replace(/cm/, ''));
  19545. ui.setChecked(state)
  19546. }
  19547. });
  19548. return ui;
  19549. };
  19550. var rowspacings = ['top', 'bottom'];
  19551. for (var r = 0, ri; ri = rowspacings[r++];) {
  19552. (function (cmd) {
  19553. editorui['rowspacing' + cmd] = function (editor) {
  19554. var val = editor.options['rowspacing' + cmd] || [];
  19555. if (!val.length) return null;
  19556. for (var i = 0, ci, items = []; ci = val[i++];) {
  19557. items.push({
  19558. label:ci,
  19559. value:ci,
  19560. theme:editor.options.theme,
  19561. onclick:function () {
  19562. editor.execCommand("rowspacing", this.value, cmd);
  19563. }
  19564. })
  19565. }
  19566. var ui = new editorui.MenuButton({
  19567. editor:editor,
  19568. className:'edui-for-rowspacing' + cmd,
  19569. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  19570. items:items,
  19571. onbuttonclick:function () {
  19572. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  19573. editor.execCommand("rowspacing", value, cmd);
  19574. }
  19575. });
  19576. editorui.buttons[cmd] = ui;
  19577. editor.addListener('selectionchange', function () {
  19578. var state = editor.queryCommandState('rowspacing', cmd);
  19579. if (state == -1) {
  19580. ui.setDisabled(true);
  19581. } else {
  19582. ui.setDisabled(false);
  19583. var value = editor.queryCommandValue('rowspacing', cmd);
  19584. value && ui.setValue((value + '').replace(/%/, ''));
  19585. ui.setChecked(state)
  19586. }
  19587. });
  19588. return ui;
  19589. }
  19590. })(ri)
  19591. }
  19592. //有序,无序列表
  19593. var lists = ['insertorderedlist', 'insertunorderedlist'];
  19594. for (var l = 0, cl; cl = lists[l++];) {
  19595. (function (cmd) {
  19596. editorui[cmd] = function (editor) {
  19597. var vals = editor.options[cmd],
  19598. _onMenuClick = function () {
  19599. editor.execCommand(cmd, this.value);
  19600. }, items = [];
  19601. for (var i in vals) {
  19602. items.push({
  19603. label:vals[i] || editor.getLang()[cmd][i] || "",
  19604. value:i,
  19605. theme:editor.options.theme,
  19606. onclick:_onMenuClick
  19607. })
  19608. }
  19609. var ui = new editorui.MenuButton({
  19610. editor:editor,
  19611. className:'edui-for-' + cmd,
  19612. title:editor.getLang("labelMap." + cmd) || '',
  19613. 'items':items,
  19614. onbuttonclick:function () {
  19615. var value = editor.queryCommandValue(cmd) || this.value;
  19616. editor.execCommand(cmd, value);
  19617. }
  19618. });
  19619. editorui.buttons[cmd] = ui;
  19620. editor.addListener('selectionchange', function () {
  19621. var state = editor.queryCommandState(cmd);
  19622. if (state == -1) {
  19623. ui.setDisabled(true);
  19624. } else {
  19625. ui.setDisabled(false);
  19626. var value = editor.queryCommandValue(cmd);
  19627. ui.setValue(value);
  19628. ui.setChecked(state)
  19629. }
  19630. });
  19631. return ui;
  19632. };
  19633. })(cl)
  19634. }
  19635. editorui.fullscreen = function (editor, title) {
  19636. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  19637. var ui = new editorui.Button({
  19638. className:'edui-for-fullscreen',
  19639. title:title,
  19640. theme:editor.options.theme,
  19641. onclick:function () {
  19642. if (editor.ui) {
  19643. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  19644. }
  19645. this.setChecked(editor.ui.isFullScreen());
  19646. }
  19647. });
  19648. editorui.buttons['fullscreen'] = ui;
  19649. editor.addListener('selectionchange', function () {
  19650. var state = editor.queryCommandState('fullscreen');
  19651. ui.setDisabled(state == -1);
  19652. ui.setChecked(editor.ui.isFullScreen());
  19653. });
  19654. return ui;
  19655. };
  19656. // 表情
  19657. editorui["emotion"] = function (editor, iframeUrl) {
  19658. var cmd = "emotion";
  19659. var ui = new editorui.MultiMenuPop({
  19660. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  19661. editor:editor,
  19662. className:'edui-for-' + cmd,
  19663. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  19664. });
  19665. editorui.buttons[cmd] = ui;
  19666. editor.addListener('selectionchange', function () {
  19667. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  19668. });
  19669. return ui;
  19670. };
  19671. editorui.autotypeset = function (editor) {
  19672. var ui = new editorui.AutoTypeSetButton({
  19673. editor:editor,
  19674. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  19675. className:'edui-for-autotypeset',
  19676. onbuttonclick:function () {
  19677. editor.execCommand('autotypeset')
  19678. }
  19679. });
  19680. editorui.buttons['autotypeset'] = ui;
  19681. editor.addListener('selectionchange', function () {
  19682. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  19683. });
  19684. return ui;
  19685. };
  19686. })();
  19687. ///import core
  19688. ///commands 全屏
  19689. ///commandsName FullScreen
  19690. ///commandsTitle 全屏
  19691. (function () {
  19692. var utils = baidu.editor.utils,
  19693. uiUtils = baidu.editor.ui.uiUtils,
  19694. UIBase = baidu.editor.ui.UIBase,
  19695. domUtils = baidu.editor.dom.domUtils;
  19696. var nodeStack = [];
  19697. function EditorUI(options) {
  19698. this.initOptions(options);
  19699. this.initEditorUI();
  19700. }
  19701. EditorUI.prototype = {
  19702. uiName:'editor',
  19703. initEditorUI:function () {
  19704. this.editor.ui = this;
  19705. this._dialogs = {};
  19706. this.initUIBase();
  19707. this._initToolbars();
  19708. var editor = this.editor,
  19709. me = this;
  19710. editor.addListener('ready', function () {
  19711. //提供getDialog方法
  19712. editor.getDialog = function (name) {
  19713. return editor.ui._dialogs[name + "Dialog"];
  19714. };
  19715. domUtils.on(editor.window, 'scroll', function (evt) {
  19716. baidu.editor.ui.Popup.postHide(evt);
  19717. });
  19718. //提供编辑器实时宽高(全屏时宽高不变化)
  19719. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  19720. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  19721. //display bottom-bar label based on config
  19722. if (editor.options.elementPathEnabled) {
  19723. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  19724. }
  19725. if (editor.options.wordCount) {
  19726. function countFn() {
  19727. setCount(editor,me);
  19728. domUtils.un(editor.document, "click", arguments.callee);
  19729. }
  19730. domUtils.on(editor.document, "click", countFn);
  19731. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  19732. }
  19733. editor.ui._scale();
  19734. if (editor.options.scaleEnabled) {
  19735. if (editor.autoHeightEnabled) {
  19736. editor.disableAutoHeight();
  19737. }
  19738. me.enableScale();
  19739. } else {
  19740. me.disableScale();
  19741. }
  19742. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  19743. editor.ui.getDom('elementpath').style.display = "none";
  19744. editor.ui.getDom('wordcount').style.display = "none";
  19745. editor.ui.getDom('scale').style.display = "none";
  19746. }
  19747. if (!editor.selection.isFocus())return;
  19748. editor.fireEvent('selectionchange', false, true);
  19749. });
  19750. editor.addListener('mousedown', function (t, evt) {
  19751. var el = evt.target || evt.srcElement;
  19752. baidu.editor.ui.Popup.postHide(evt, el);
  19753. baidu.editor.ui.ShortCutMenu.postHide(evt);
  19754. });
  19755. editor.addListener("delcells", function () {
  19756. if (UE.ui['edittip']) {
  19757. new UE.ui['edittip'](editor);
  19758. }
  19759. editor.getDialog('edittip').open();
  19760. });
  19761. var pastePop, isPaste = false, timer;
  19762. editor.addListener("afterpaste", function () {
  19763. if(editor.queryCommandState('pasteplain'))
  19764. return;
  19765. if(baidu.editor.ui.PastePicker){
  19766. pastePop = new baidu.editor.ui.Popup({
  19767. content:new baidu.editor.ui.PastePicker({editor:editor}),
  19768. editor:editor,
  19769. className:'edui-wordpastepop'
  19770. });
  19771. pastePop.render();
  19772. }
  19773. isPaste = true;
  19774. });
  19775. editor.addListener("afterinserthtml", function () {
  19776. clearTimeout(timer);
  19777. timer = setTimeout(function () {
  19778. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  19779. if(pastePop.isHidden()){
  19780. var span = domUtils.createElement(editor.document, 'span', {
  19781. 'style':"line-height:0px;",
  19782. 'innerHTML':'\ufeff'
  19783. }),
  19784. range = editor.selection.getRange();
  19785. range.insertNode(span);
  19786. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  19787. pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  19788. domUtils.remove(span);
  19789. }else{
  19790. pastePop.show();
  19791. }
  19792. delete editor.ui._isTransfer;
  19793. isPaste = false;
  19794. }
  19795. }, 200)
  19796. });
  19797. editor.addListener('contextmenu', function (t, evt) {
  19798. baidu.editor.ui.Popup.postHide(evt);
  19799. });
  19800. editor.addListener('keydown', function (t, evt) {
  19801. if (pastePop) pastePop.dispose(evt);
  19802. var keyCode = evt.keyCode || evt.which;
  19803. if(evt.altKey&&keyCode==90){
  19804. UE.ui.buttons['fullscreen'].onclick();
  19805. }
  19806. });
  19807. editor.addListener('wordcount', function (type) {
  19808. setCount(this,me);
  19809. });
  19810. function setCount(editor,ui) {
  19811. editor.setOpt({
  19812. wordCount:true,
  19813. maximumWords:10000,
  19814. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  19815. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  19816. });
  19817. var opt = editor.options,
  19818. max = opt.maximumWords,
  19819. msg = opt.wordCountMsg ,
  19820. errMsg = opt.wordOverFlowMsg,
  19821. countDom = ui.getDom('wordcount');
  19822. if (!opt.wordCount) {
  19823. return;
  19824. }
  19825. var count = editor.getContentLength(true);
  19826. if (count > max) {
  19827. countDom.innerHTML = errMsg;
  19828. editor.fireEvent("wordcountoverflow");
  19829. } else {
  19830. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  19831. }
  19832. }
  19833. editor.addListener('selectionchange', function () {
  19834. if (editor.options.elementPathEnabled) {
  19835. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  19836. }
  19837. if (editor.options.scaleEnabled) {
  19838. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  19839. }
  19840. });
  19841. var popup = new baidu.editor.ui.Popup({
  19842. editor:editor,
  19843. content:'',
  19844. className:'edui-bubble',
  19845. _onEditButtonClick:function () {
  19846. this.hide();
  19847. editor.ui._dialogs.linkDialog.open();
  19848. },
  19849. _onImgEditButtonClick:function (name) {
  19850. this.hide();
  19851. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  19852. },
  19853. _onImgSetFloat:function (value) {
  19854. this.hide();
  19855. editor.execCommand("imagefloat", value);
  19856. },
  19857. _setIframeAlign:function (value) {
  19858. var frame = popup.anchorEl;
  19859. var newFrame = frame.cloneNode(true);
  19860. switch (value) {
  19861. case -2:
  19862. newFrame.setAttribute("align", "");
  19863. break;
  19864. case -1:
  19865. newFrame.setAttribute("align", "left");
  19866. break;
  19867. case 1:
  19868. newFrame.setAttribute("align", "right");
  19869. break;
  19870. }
  19871. frame.parentNode.insertBefore(newFrame, frame);
  19872. domUtils.remove(frame);
  19873. popup.anchorEl = newFrame;
  19874. popup.showAnchor(popup.anchorEl);
  19875. },
  19876. _updateIframe:function () {
  19877. var frame = editor._iframe = popup.anchorEl;
  19878. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  19879. editor.selection.getRange().selectNode(frame).select();
  19880. editor.ui._dialogs.mapDialog.open();
  19881. popup.hide();
  19882. } else {
  19883. editor.ui._dialogs.insertframeDialog.open();
  19884. popup.hide();
  19885. }
  19886. },
  19887. _onRemoveButtonClick:function (cmdName) {
  19888. editor.execCommand(cmdName);
  19889. this.hide();
  19890. },
  19891. queryAutoHide:function (el) {
  19892. if (el && el.ownerDocument == editor.document) {
  19893. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  19894. return el !== popup.anchorEl;
  19895. }
  19896. }
  19897. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  19898. }
  19899. });
  19900. popup.render();
  19901. if (editor.options.imagePopup) {
  19902. editor.addListener('mouseover', function (t, evt) {
  19903. evt = evt || window.event;
  19904. var el = evt.target || evt.srcElement;
  19905. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  19906. var html = popup.formatHtml(
  19907. '<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;' +
  19908. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  19909. if (html) {
  19910. popup.getDom('content').innerHTML = html;
  19911. popup.anchorEl = el;
  19912. popup.showAnchor(popup.anchorEl);
  19913. } else {
  19914. popup.hide();
  19915. }
  19916. }
  19917. });
  19918. editor.addListener('selectionchange', function (t, causeByUi) {
  19919. if (!causeByUi) return;
  19920. var html = '', str = "",
  19921. img = editor.selection.getRange().getClosedNode(),
  19922. dialogs = editor.ui._dialogs;
  19923. if (img && img.tagName == 'IMG') {
  19924. var dialogName = 'insertimageDialog';
  19925. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  19926. dialogName = "insertvideoDialog"
  19927. }
  19928. if (img.className.indexOf("edui-faked-webapp") != -1) {
  19929. dialogName = "webappDialog"
  19930. }
  19931. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  19932. dialogName = "mapDialog"
  19933. }
  19934. if (img.className.indexOf("edui-faked-music") != -1) {
  19935. dialogName = "musicDialog"
  19936. }
  19937. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  19938. dialogName = "gmapDialog"
  19939. }
  19940. if (img.getAttribute("anchorname")) {
  19941. dialogName = "anchorDialog";
  19942. html = popup.formatHtml(
  19943. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  19944. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  19945. }
  19946. if (img.getAttribute("word_img")) {
  19947. //todo 放到dialog去做查询
  19948. editor.word_img = [img.getAttribute("word_img")];
  19949. dialogName = "wordimageDialog"
  19950. }
  19951. if (!dialogs[dialogName]) {
  19952. return;
  19953. }
  19954. str = '<nobr>' + editor.getLang("property") + ': '+
  19955. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  19956. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  19957. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  19958. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  19959. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  19960. !html && (html = popup.formatHtml(str))
  19961. }
  19962. if (editor.ui._dialogs.linkDialog) {
  19963. var link = editor.queryCommandValue('link');
  19964. var url;
  19965. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  19966. var txt = url;
  19967. if (url.length > 30) {
  19968. txt = url.substring(0, 20) + "...";
  19969. }
  19970. if (html) {
  19971. html += '<div style="height:5px;"></div>'
  19972. }
  19973. html += popup.formatHtml(
  19974. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  19975. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  19976. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  19977. popup.showAnchor(link);
  19978. }
  19979. }
  19980. if (html) {
  19981. popup.getDom('content').innerHTML = html;
  19982. popup.anchorEl = img || link;
  19983. popup.showAnchor(popup.anchorEl);
  19984. } else {
  19985. popup.hide();
  19986. }
  19987. });
  19988. }
  19989. },
  19990. _initToolbars:function () {
  19991. var editor = this.editor;
  19992. var toolbars = this.toolbars || [];
  19993. var toolbarUis = [];
  19994. for (var i = 0; i < toolbars.length; i++) {
  19995. var toolbar = toolbars[i];
  19996. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  19997. for (var j = 0; j < toolbar.length; j++) {
  19998. var toolbarItem = toolbar[j];
  19999. var toolbarItemUi = null;
  20000. if (typeof toolbarItem == 'string') {
  20001. toolbarItem = toolbarItem.toLowerCase();
  20002. if (toolbarItem == '|') {
  20003. toolbarItem = 'Separator';
  20004. }
  20005. if(toolbarItem == '||'){
  20006. toolbarItem = 'Breakline';
  20007. }
  20008. if (baidu.editor.ui[toolbarItem]) {
  20009. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  20010. }
  20011. //fullscreen这里单独处理一下,放到首行去
  20012. if (toolbarItem == 'fullscreen') {
  20013. if (toolbarUis && toolbarUis[0]) {
  20014. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  20015. } else {
  20016. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  20017. }
  20018. continue;
  20019. }
  20020. } else {
  20021. toolbarItemUi = toolbarItem;
  20022. }
  20023. if (toolbarItemUi && toolbarItemUi.id) {
  20024. toolbarUi.add(toolbarItemUi);
  20025. }
  20026. }
  20027. toolbarUis[i] = toolbarUi;
  20028. }
  20029. this.toolbars = toolbarUis;
  20030. },
  20031. getHtmlTpl:function () {
  20032. return '<div id="##" class="%%">' +
  20033. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  20034. (this.toolbars.length ?
  20035. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  20036. this.renderToolbarBoxHtml() +
  20037. '</div></div>' : '') +
  20038. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  20039. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  20040. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  20041. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  20042. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  20043. '</div>' +
  20044. '</div>' +
  20045. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  20046. //modify wdcount by matao
  20047. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  20048. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  20049. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  20050. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  20051. '</tr></table></div>' +
  20052. '<div id="##_scalelayer"></div>' +
  20053. '</div>';
  20054. },
  20055. showWordImageDialog:function () {
  20056. this._dialogs['wordimageDialog'].open();
  20057. },
  20058. renderToolbarBoxHtml:function () {
  20059. var buff = [];
  20060. for (var i = 0; i < this.toolbars.length; i++) {
  20061. buff.push(this.toolbars[i].renderHtml());
  20062. }
  20063. return buff.join('');
  20064. },
  20065. setFullScreen:function (fullscreen) {
  20066. var editor = this.editor,
  20067. container = editor.container.parentNode.parentNode;
  20068. if (this._fullscreen != fullscreen) {
  20069. this._fullscreen = fullscreen;
  20070. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  20071. if (baidu.editor.browser.gecko) {
  20072. var bk = editor.selection.getRange().createBookmark();
  20073. }
  20074. if (fullscreen) {
  20075. while (container.tagName != "BODY") {
  20076. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  20077. nodeStack.push(position);
  20078. container.style.position = "static";
  20079. container = container.parentNode;
  20080. }
  20081. this._bakHtmlOverflow = document.documentElement.style.overflow;
  20082. this._bakBodyOverflow = document.body.style.overflow;
  20083. this._bakAutoHeight = this.editor.autoHeightEnabled;
  20084. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  20085. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  20086. if (this._bakAutoHeight) {
  20087. //当全屏时不能执行自动长高
  20088. editor.autoHeightEnabled = false;
  20089. this.editor.disableAutoHeight();
  20090. }
  20091. document.documentElement.style.overflow = 'hidden';
  20092. //修复,滚动条不收起的问题
  20093. window.scrollTo(0,window.scrollY);
  20094. this._bakCssText = this.getDom().style.cssText;
  20095. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  20096. editor.iframe.parentNode.style.width = '';
  20097. this._updateFullScreen();
  20098. } else {
  20099. while (container.tagName != "BODY") {
  20100. container.style.position = nodeStack.shift();
  20101. container = container.parentNode;
  20102. }
  20103. this.getDom().style.cssText = this._bakCssText;
  20104. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  20105. if (this._bakAutoHeight) {
  20106. editor.autoHeightEnabled = true;
  20107. this.editor.enableAutoHeight();
  20108. }
  20109. document.documentElement.style.overflow = this._bakHtmlOverflow;
  20110. document.body.style.overflow = this._bakBodyOverflow;
  20111. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  20112. window.scrollTo(0, this._bakScrollTop);
  20113. }
  20114. if (browser.gecko && editor.body.contentEditable === 'true') {
  20115. var input = document.createElement('input');
  20116. document.body.appendChild(input);
  20117. editor.body.contentEditable = false;
  20118. setTimeout(function () {
  20119. input.focus();
  20120. setTimeout(function () {
  20121. editor.body.contentEditable = true;
  20122. editor.fireEvent('fullscreenchanged', fullscreen);
  20123. editor.selection.getRange().moveToBookmark(bk).select(true);
  20124. baidu.editor.dom.domUtils.remove(input);
  20125. fullscreen && window.scroll(0, 0);
  20126. }, 0)
  20127. }, 0)
  20128. }
  20129. if(editor.body.contentEditable === 'true'){
  20130. this.editor.fireEvent('fullscreenchanged', fullscreen);
  20131. this.triggerLayout();
  20132. }
  20133. }
  20134. },
  20135. _updateFullScreen:function () {
  20136. if (this._fullscreen) {
  20137. var vpRect = uiUtils.getViewportRect();
  20138. 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);
  20139. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  20140. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  20141. //不手动调一下,会导致全屏失效
  20142. if(browser.gecko){
  20143. try{
  20144. window.onresize();
  20145. }catch(e){
  20146. }
  20147. }
  20148. }
  20149. },
  20150. _updateElementPath:function () {
  20151. var bottom = this.getDom('elementpath'), list;
  20152. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  20153. var buff = [];
  20154. for (var i = 0, ci; ci = list[i]; i++) {
  20155. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  20156. }
  20157. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  20158. } else {
  20159. bottom.style.display = 'none'
  20160. }
  20161. },
  20162. disableElementPath:function () {
  20163. var bottom = this.getDom('elementpath');
  20164. bottom.innerHTML = '';
  20165. bottom.style.display = 'none';
  20166. this.elementPathEnabled = false;
  20167. },
  20168. enableElementPath:function () {
  20169. var bottom = this.getDom('elementpath');
  20170. bottom.style.display = '';
  20171. this.elementPathEnabled = true;
  20172. this._updateElementPath();
  20173. },
  20174. _scale:function () {
  20175. var doc = document,
  20176. editor = this.editor,
  20177. editorHolder = editor.container,
  20178. editorDocument = editor.document,
  20179. toolbarBox = this.getDom("toolbarbox"),
  20180. bottombar = this.getDom("bottombar"),
  20181. scale = this.getDom("scale"),
  20182. scalelayer = this.getDom("scalelayer");
  20183. var isMouseMove = false,
  20184. position = null,
  20185. minEditorHeight = 0,
  20186. minEditorWidth = editor.options.minFrameWidth,
  20187. pageX = 0,
  20188. pageY = 0,
  20189. scaleWidth = 0,
  20190. scaleHeight = 0;
  20191. function down() {
  20192. position = domUtils.getXY(editorHolder);
  20193. if (!minEditorHeight) {
  20194. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  20195. }
  20196. 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:"
  20197. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  20198. domUtils.on(doc, "mousemove", move);
  20199. domUtils.on(editorDocument, "mouseup", up);
  20200. domUtils.on(doc, "mouseup", up);
  20201. }
  20202. var me = this;
  20203. //by xuheng 全屏时关掉缩放
  20204. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  20205. if (fullScreen) {
  20206. me.disableScale();
  20207. } else {
  20208. if (me.editor.options.scaleEnabled) {
  20209. me.enableScale();
  20210. var tmpNode = me.editor.document.createElement('span');
  20211. me.editor.body.appendChild(tmpNode);
  20212. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  20213. domUtils.remove(tmpNode)
  20214. }
  20215. }
  20216. });
  20217. function move(event) {
  20218. clearSelection();
  20219. var e = event || window.event;
  20220. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  20221. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  20222. scaleWidth = pageX - position.x;
  20223. scaleHeight = pageY - position.y;
  20224. if (scaleWidth >= minEditorWidth) {
  20225. isMouseMove = true;
  20226. scalelayer.style.width = scaleWidth + 'px';
  20227. }
  20228. if (scaleHeight >= minEditorHeight) {
  20229. isMouseMove = true;
  20230. scalelayer.style.height = scaleHeight + "px";
  20231. }
  20232. }
  20233. function up() {
  20234. if (isMouseMove) {
  20235. isMouseMove = false;
  20236. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  20237. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  20238. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  20239. }
  20240. if (scalelayer) {
  20241. scalelayer.style.display = "none";
  20242. }
  20243. clearSelection();
  20244. domUtils.un(doc, "mousemove", move);
  20245. domUtils.un(editorDocument, "mouseup", up);
  20246. domUtils.un(doc, "mouseup", up);
  20247. }
  20248. function clearSelection() {
  20249. if (browser.ie)
  20250. doc.selection.clear();
  20251. else
  20252. window.getSelection().removeAllRanges();
  20253. }
  20254. this.enableScale = function () {
  20255. //trace:2868
  20256. if (editor.queryCommandState("source") == 1) return;
  20257. scale.style.display = "";
  20258. this.scaleEnabled = true;
  20259. domUtils.on(scale, "mousedown", down);
  20260. };
  20261. this.disableScale = function () {
  20262. scale.style.display = "none";
  20263. this.scaleEnabled = false;
  20264. domUtils.un(scale, "mousedown", down);
  20265. };
  20266. },
  20267. isFullScreen:function () {
  20268. return this._fullscreen;
  20269. },
  20270. postRender:function () {
  20271. UIBase.prototype.postRender.call(this);
  20272. for (var i = 0; i < this.toolbars.length; i++) {
  20273. this.toolbars[i].postRender();
  20274. }
  20275. var me = this;
  20276. var timerId,
  20277. domUtils = baidu.editor.dom.domUtils,
  20278. updateFullScreenTime = function () {
  20279. clearTimeout(timerId);
  20280. timerId = setTimeout(function () {
  20281. me._updateFullScreen();
  20282. });
  20283. };
  20284. domUtils.on(window, 'resize', updateFullScreenTime);
  20285. me.addListener('destroy', function () {
  20286. domUtils.un(window, 'resize', updateFullScreenTime);
  20287. clearTimeout(timerId);
  20288. })
  20289. },
  20290. showToolbarMsg:function (msg, flag) {
  20291. this.getDom('toolbarmsg_label').innerHTML = msg;
  20292. this.getDom('toolbarmsg').style.display = '';
  20293. //
  20294. if (!flag) {
  20295. var w = this.getDom('upload_dialog');
  20296. w.style.display = 'none';
  20297. }
  20298. },
  20299. hideToolbarMsg:function () {
  20300. this.getDom('toolbarmsg').style.display = 'none';
  20301. },
  20302. mapUrl:function (url) {
  20303. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  20304. },
  20305. triggerLayout:function () {
  20306. var dom = this.getDom();
  20307. if (dom.style.zoom == '1') {
  20308. dom.style.zoom = '100%';
  20309. } else {
  20310. dom.style.zoom = '1';
  20311. }
  20312. }
  20313. };
  20314. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  20315. var instances = {};
  20316. UE.ui.Editor = function (options) {
  20317. var editor = new UE.Editor(options);
  20318. editor.options.editor = editor;
  20319. utils.loadFile(document, {
  20320. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  20321. tag:"link",
  20322. type:"text/css",
  20323. rel:"stylesheet"
  20324. });
  20325. var oldRender = editor.render;
  20326. editor.render = function (holder) {
  20327. if (holder.constructor === String) {
  20328. editor.key = holder;
  20329. instances[holder] = editor;
  20330. }
  20331. utils.domReady(function () {
  20332. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  20333. function renderUI() {
  20334. editor.setOpt({
  20335. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  20336. });
  20337. new EditorUI(editor.options);
  20338. if (holder) {
  20339. if (holder.constructor === String) {
  20340. holder = document.getElementById(holder);
  20341. }
  20342. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  20343. if (holder && /script|textarea/ig.test(holder.tagName)) {
  20344. var newDiv = document.createElement('div');
  20345. holder.parentNode.insertBefore(newDiv, holder);
  20346. var cont = holder.value || holder.innerHTML;
  20347. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  20348. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  20349. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  20350. .replace(/>[\n\r\t]+</g, '><');
  20351. holder.className && (newDiv.className = holder.className);
  20352. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  20353. if (/textarea/i.test(holder.tagName)) {
  20354. editor.textarea = holder;
  20355. editor.textarea.style.display = 'none';
  20356. } else {
  20357. holder.parentNode.removeChild(holder);
  20358. holder.id && (newDiv.id = holder.id);
  20359. }
  20360. holder = newDiv;
  20361. holder.innerHTML = '';
  20362. }
  20363. }
  20364. domUtils.addClass(holder, "edui-" + editor.options.theme);
  20365. editor.ui.render(holder);
  20366. var opt = editor.options;
  20367. //给实例添加一个编辑器的容器引用
  20368. editor.container = editor.ui.getDom();
  20369. var parents = domUtils.findParents(holder,true);
  20370. var displays = [];
  20371. for(var i = 0 ,ci;ci=parents[i];i++){
  20372. displays[i] = ci.style.display;
  20373. ci.style.display = 'block'
  20374. }
  20375. if (opt.initialFrameWidth) {
  20376. opt.minFrameWidth = opt.initialFrameWidth;
  20377. } else {
  20378. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  20379. }
  20380. if (opt.initialFrameHeight) {
  20381. opt.minFrameHeight = opt.initialFrameHeight;
  20382. } else {
  20383. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  20384. }
  20385. for(var i = 0 ,ci;ci=parents[i];i++){
  20386. ci.style.display = displays[i]
  20387. }
  20388. //编辑器最外容器设置了高度,会导致,编辑器不占位
  20389. //todo 先去掉,没有找到原因
  20390. if(holder.style.height){
  20391. holder.style.height = ''
  20392. }
  20393. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  20394. editor.container.style.zIndex = opt.zIndex;
  20395. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  20396. editor.fireEvent("afteruiready");
  20397. }
  20398. })
  20399. };
  20400. return editor;
  20401. };
  20402. /**
  20403. * @file
  20404. * @name UE
  20405. * @short UE
  20406. * @desc UEditor的顶部命名空间
  20407. */
  20408. /**
  20409. * @name getEditor
  20410. * @since 1.2.4+
  20411. * @grammar UE.getEditor(id,[opt]) => Editor实例
  20412. * @desc 提供一个全局的方法得到编辑器实例
  20413. *
  20414. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  20415. * * ''opt'' 编辑器的可选参数
  20416. * @example
  20417. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  20418. * this.setContent('hello')
  20419. * }});
  20420. * UE.getEditor('containerId'); //返回刚创建的实例
  20421. *
  20422. */
  20423. UE.getEditor = function (id, opt) {
  20424. var editor = instances[id];
  20425. if (!editor) {
  20426. editor = instances[id] = new UE.ui.Editor(opt);
  20427. editor.render(id);
  20428. }
  20429. return editor;
  20430. };
  20431. UE.delEditor = function (id) {
  20432. var editor;
  20433. if (editor = instances[id]) {
  20434. editor.key && editor.destroy();
  20435. delete instances[id]
  20436. }
  20437. }
  20438. })();
  20439. ///import core
  20440. ///import uicore
  20441. ///commands 表情
  20442. (function(){
  20443. var utils = baidu.editor.utils,
  20444. Popup = baidu.editor.ui.Popup,
  20445. SplitButton = baidu.editor.ui.SplitButton,
  20446. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  20447. this.initOptions(options);
  20448. this.initMultiMenu();
  20449. };
  20450. MultiMenuPop.prototype = {
  20451. initMultiMenu: function (){
  20452. var me = this;
  20453. this.popup = new Popup({
  20454. content: '',
  20455. editor : me.editor,
  20456. iframe_rendered: false,
  20457. onshow: function (){
  20458. if (!this.iframe_rendered) {
  20459. this.iframe_rendered = true;
  20460. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  20461. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  20462. }
  20463. }
  20464. // canSideUp:false,
  20465. // canSideLeft:false
  20466. });
  20467. this.onbuttonclick = function(){
  20468. this.showPopup();
  20469. };
  20470. this.initSplitButton();
  20471. }
  20472. };
  20473. utils.inherits(MultiMenuPop, SplitButton);
  20474. })();
  20475. (function () {
  20476. var UI = baidu.editor.ui,
  20477. UIBase = UI.UIBase,
  20478. uiUtils = UI.uiUtils,
  20479. utils = baidu.editor.utils,
  20480. domUtils = baidu.editor.dom.domUtils;
  20481. var allMenus = [],//存储所有快捷菜单
  20482. timeID,
  20483. isSubMenuShow = false;//是否有子pop显示
  20484. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  20485. this.initOptions (options);
  20486. this.initShortCutMenu ();
  20487. };
  20488. ShortCutMenu.postHide = hideAllMenu;
  20489. ShortCutMenu.prototype = {
  20490. isHidden : true ,
  20491. SPACE : 5 ,
  20492. initShortCutMenu : function () {
  20493. this.items = this.items || [];
  20494. this.initUIBase ();
  20495. this.initItems ();
  20496. this.initEvent ();
  20497. allMenus.push (this);
  20498. } ,
  20499. initEvent : function () {
  20500. var me = this,
  20501. doc = me.editor.document;
  20502. domUtils.on (doc , "mousemove" , function (e) {
  20503. if (me.isHidden === false) {
  20504. //有pop显示就不隐藏快捷菜单
  20505. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  20506. var flag = true,
  20507. el = me.getDom (),
  20508. wt = el.offsetWidth,
  20509. ht = el.offsetHeight,
  20510. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  20511. distanceY = ht / 2,//距离中心Y标准
  20512. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  20513. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  20514. clearTimeout (timeID);
  20515. timeID = setTimeout (function () {
  20516. if (y > 0 && y < distanceY) {
  20517. me.setOpacity (el , "1");
  20518. } else if (y > distanceY && y < distanceY + 70) {
  20519. me.setOpacity (el , "0.5");
  20520. flag = false;
  20521. } else if (y > distanceY + 70 && y < distanceY + 140) {
  20522. me.hide ();
  20523. }
  20524. if (flag && x > 0 && x < distanceX) {
  20525. me.setOpacity (el , "1")
  20526. } else if (x > distanceX && x < distanceX + 70) {
  20527. me.setOpacity (el , "0.5")
  20528. } else if (x > distanceX + 70 && x < distanceX + 140) {
  20529. me.hide ();
  20530. }
  20531. });
  20532. }
  20533. });
  20534. //ie\ff下 mouseout不准
  20535. if (browser.chrome) {
  20536. domUtils.on (doc , "mouseout" , function (e) {
  20537. var relatedTgt = e.relatedTarget || e.toElement;
  20538. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  20539. me.hide ();
  20540. }
  20541. });
  20542. }
  20543. me.editor.addListener ("afterhidepop" , function () {
  20544. if (!me.isHidden) {
  20545. isSubMenuShow = true;
  20546. }
  20547. });
  20548. } ,
  20549. initItems : function () {
  20550. if (utils.isArray (this.items)) {
  20551. for (var i = 0, len = this.items.length ; i < len ; i++) {
  20552. var item = this.items[i].toLowerCase ();
  20553. if (UI[item]) {
  20554. this.items[i] = new UI[item] (this.editor);
  20555. this.items[i].className += " edui-shortcutsubmenu ";
  20556. }
  20557. }
  20558. }
  20559. } ,
  20560. setOpacity : function (el , value) {
  20561. if (browser.ie && browser.version < 9) {
  20562. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  20563. } else {
  20564. el.style.opacity = value;
  20565. }
  20566. } ,
  20567. getSubMenuMark : function () {
  20568. isSubMenuShow = false;
  20569. var layerEle = uiUtils.getFixedLayer ();
  20570. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  20571. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  20572. });
  20573. for (var i = 0, node ; node = list[i++] ;) {
  20574. if (node.style.display != "none") {
  20575. isSubMenuShow = true;
  20576. }
  20577. }
  20578. return isSubMenuShow;
  20579. } ,
  20580. show : function (e , hasContextmenu) {
  20581. var me = this,
  20582. offset = {},
  20583. el = this.getDom (),
  20584. fixedlayer = uiUtils.getFixedLayer ();
  20585. function setPos (offset) {
  20586. if (offset.left < 0) {
  20587. offset.left = 0;
  20588. }
  20589. if (offset.top < 0) {
  20590. offset.top = 0;
  20591. }
  20592. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  20593. }
  20594. function setPosByCxtMenu (menu) {
  20595. if (!menu.tagName) {
  20596. menu = menu.getDom ();
  20597. }
  20598. offset.left = parseInt (menu.style.left);
  20599. offset.top = parseInt (menu.style.top);
  20600. offset.top -= el.offsetHeight + 15;
  20601. setPos (offset);
  20602. }
  20603. me.eventType = e.type;
  20604. el.style.cssText = "display:block;left:-9999px";
  20605. if (e.type == "contextmenu" && hasContextmenu) {
  20606. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  20607. if (menu) {
  20608. setPosByCxtMenu (menu)
  20609. } else {
  20610. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  20611. setPosByCxtMenu (menu);
  20612. });
  20613. }
  20614. } else {
  20615. offset = uiUtils.getViewportOffsetByEvent (e);
  20616. offset.top -= el.offsetHeight + me.SPACE;
  20617. offset.left += me.SPACE + 20;
  20618. setPos (offset);
  20619. me.setOpacity (el , 0.2);
  20620. }
  20621. me.isHidden = false;
  20622. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  20623. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  20624. if (me.editor) {
  20625. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  20626. fixedlayer.style.zIndex = el.style.zIndex - 1;
  20627. }
  20628. } ,
  20629. hide : function () {
  20630. if (this.getDom ()) {
  20631. this.getDom ().style.display = "none";
  20632. }
  20633. this.isHidden = true;
  20634. } ,
  20635. postRender : function () {
  20636. if (utils.isArray (this.items)) {
  20637. for (var i = 0, item ; item = this.items[i++] ;) {
  20638. item.postRender ();
  20639. }
  20640. }
  20641. } ,
  20642. getHtmlTpl : function () {
  20643. var buff;
  20644. if (utils.isArray (this.items)) {
  20645. buff = [];
  20646. for (var i = 0 ; i < this.items.length ; i++) {
  20647. buff[i] = this.items[i].renderHtml ();
  20648. }
  20649. buff = buff.join ("");
  20650. } else {
  20651. buff = this.items;
  20652. }
  20653. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  20654. buff +
  20655. '</div>';
  20656. }
  20657. };
  20658. utils.inherits (ShortCutMenu , UIBase);
  20659. function hideAllMenu (e) {
  20660. var tgt = e.target || e.srcElement,
  20661. cur = domUtils.findParent (tgt , function (node) {
  20662. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  20663. } , true);
  20664. if (!cur) {
  20665. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  20666. menu.hide ()
  20667. }
  20668. }
  20669. }
  20670. domUtils.on (document , 'mousedown' , function (e) {
  20671. hideAllMenu (e);
  20672. });
  20673. domUtils.on (window , 'scroll' , function (e) {
  20674. hideAllMenu (e);
  20675. });
  20676. }) ();
  20677. (function (){
  20678. var utils = baidu.editor.utils,
  20679. UIBase = baidu.editor.ui.UIBase,
  20680. Breakline = baidu.editor.ui.Breakline = function (options){
  20681. this.initOptions(options);
  20682. this.initSeparator();
  20683. };
  20684. Breakline.prototype = {
  20685. uiName: 'Breakline',
  20686. initSeparator: function (){
  20687. this.initUIBase();
  20688. },
  20689. getHtmlTpl: function (){
  20690. return '<br/>';
  20691. }
  20692. };
  20693. utils.inherits(Breakline, UIBase);
  20694. })();
  20695. })();