ueditor.all.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Fri May 16 2014 14:14:42 GMT+0800 (中国标准时间)
  5. */
  6. (function(){
  7. // editor.js
  8. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  9. var baidu = window.baidu || {};
  10. window.baidu = baidu;
  11. window.UE = baidu.editor = window.UE || {};
  12. UE.plugins = {};
  13. UE.commands = {};
  14. UE.instants = {};
  15. UE.I18N = {};
  16. UE._customizeUI = {};
  17. UE.version = "1.4.2";
  18. var dom = UE.dom = {};
  19. // core/browser.js
  20. /**
  21. * 浏览器判断模块
  22. * @file
  23. * @module UE.browser
  24. * @since 1.2.6.1
  25. */
  26. /**
  27. * 提供浏览器检测的模块
  28. * @unfile
  29. * @module UE.browser
  30. */
  31. var browser = UE.browser = function(){
  32. var agent = navigator.userAgent.toLowerCase(),
  33. opera = window.opera,
  34. browser = {
  35. /**
  36. * @property {boolean} ie 检测当前浏览器是否为IE
  37. * @example
  38. * ```javascript
  39. * if ( UE.browser.ie ) {
  40. * console.log( '当前浏览器是IE' );
  41. * }
  42. * ```
  43. */
  44. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  45. /**
  46. * @property {boolean} opera 检测当前浏览器是否为Opera
  47. * @example
  48. * ```javascript
  49. * if ( UE.browser.opera ) {
  50. * console.log( '当前浏览器是Opera' );
  51. * }
  52. * ```
  53. */
  54. opera : ( !!opera && opera.version ),
  55. /**
  56. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  57. * @example
  58. * ```javascript
  59. * if ( UE.browser.webkit ) {
  60. * console.log( '当前浏览器是webkit内核浏览器' );
  61. * }
  62. * ```
  63. */
  64. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  65. /**
  66. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  67. * @example
  68. * ```javascript
  69. * if ( UE.browser.mac ) {
  70. * console.log( '当前浏览器运行在mac平台下' );
  71. * }
  72. * ```
  73. */
  74. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  75. /**
  76. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  77. * @example
  78. * ```javascript
  79. * if ( UE.browser.quirks ) {
  80. * console.log( '当前浏览器运行处于“怪异模式”' );
  81. * }
  82. * ```
  83. */
  84. quirks : ( document.compatMode == 'BackCompat' )
  85. };
  86. /**
  87. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  88. * @example
  89. * ```javascript
  90. * if ( UE.browser.gecko ) {
  91. * console.log( '当前浏览器内核是gecko内核' );
  92. * }
  93. * ```
  94. */
  95. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  96. var version = 0;
  97. // Internet Explorer 6.0+
  98. if ( browser.ie ){
  99. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  100. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  101. if(v1 && v2 && v1[1] && v2[1]){
  102. version = Math.max(v1[1]*1,v2[1]*1);
  103. }else if(v1 && v1[1]){
  104. version = v1[1]*1;
  105. }else if(v2 && v2[1]){
  106. version = v2[1]*1;
  107. }else{
  108. version = 0;
  109. }
  110. browser.ie11Compat = document.documentMode == 11;
  111. /**
  112. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  113. * @warning 如果浏览器不是IE, 则该值为undefined
  114. * @example
  115. * ```javascript
  116. * if ( UE.browser.ie9Compat ) {
  117. * console.log( '当前浏览器运行在IE9兼容模式下' );
  118. * }
  119. * ```
  120. */
  121. browser.ie9Compat = document.documentMode == 9;
  122. /**
  123. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  124. * @warning 如果浏览器不是IE, 则该值为undefined
  125. * @example
  126. * ```javascript
  127. * if ( UE.browser.ie8 ) {
  128. * console.log( '当前浏览器是IE8浏览器' );
  129. * }
  130. * ```
  131. */
  132. browser.ie8 = !!document.documentMode;
  133. /**
  134. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  135. * @warning 如果浏览器不是IE, 则该值为undefined
  136. * @example
  137. * ```javascript
  138. * if ( UE.browser.ie8Compat ) {
  139. * console.log( '当前浏览器运行在IE8兼容模式下' );
  140. * }
  141. * ```
  142. */
  143. browser.ie8Compat = document.documentMode == 8;
  144. /**
  145. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  146. * @warning 如果浏览器不是IE, 则该值为undefined
  147. * @example
  148. * ```javascript
  149. * if ( UE.browser.ie7Compat ) {
  150. * console.log( '当前浏览器运行在IE7兼容模式下' );
  151. * }
  152. * ```
  153. */
  154. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  155. || document.documentMode == 7 );
  156. /**
  157. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  158. * @warning 如果浏览器不是IE, 则该值为undefined
  159. * @example
  160. * ```javascript
  161. * if ( UE.browser.ie6Compat ) {
  162. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  163. * }
  164. * ```
  165. */
  166. browser.ie6Compat = ( version < 7 || browser.quirks );
  167. browser.ie9above = version > 8;
  168. browser.ie9below = version < 9;
  169. browser.ie11above = version > 10;
  170. browser.ie11below = version < 11;
  171. }
  172. // Gecko.
  173. if ( browser.gecko ){
  174. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  175. if ( geckoRelease )
  176. {
  177. geckoRelease = geckoRelease[1].split( '.' );
  178. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  179. }
  180. }
  181. /**
  182. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  183. * @warning 如果浏览器不是chrome, 则该值为undefined
  184. * @example
  185. * ```javascript
  186. * if ( UE.browser.chrome ) {
  187. * console.log( '当前浏览器是Chrome' );
  188. * }
  189. * ```
  190. */
  191. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  192. browser.chrome = + RegExp['\x241'];
  193. }
  194. /**
  195. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  196. * @warning 如果浏览器不是safari, 则该值为undefined
  197. * @example
  198. * ```javascript
  199. * if ( UE.browser.safari ) {
  200. * console.log( '当前浏览器是Safari' );
  201. * }
  202. * ```
  203. */
  204. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  205. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  206. }
  207. // Opera 9.50+
  208. if ( browser.opera )
  209. version = parseFloat( opera.version() );
  210. // WebKit 522+ (Safari 3+)
  211. if ( browser.webkit )
  212. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  213. /**
  214. * @property { Number } version 检测当前浏览器版本号
  215. * @remind
  216. * <ul>
  217. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  218. * <li>gecko系列会返回10900,158900等</li>
  219. * <li>webkit系列会返回其build号 (如 522等)</li>
  220. * </ul>
  221. * @example
  222. * ```javascript
  223. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  224. * ```
  225. */
  226. browser.version = version;
  227. /**
  228. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  229. * @example
  230. * ```javascript
  231. * if ( UE.browser.isCompatible ) {
  232. * console.log( '浏览器与UEditor能够良好兼容' );
  233. * }
  234. * ```
  235. */
  236. browser.isCompatible =
  237. !browser.mobile && (
  238. ( browser.ie && version >= 6 ) ||
  239. ( browser.gecko && version >= 10801 ) ||
  240. ( browser.opera && version >= 9.5 ) ||
  241. ( browser.air && version >= 1 ) ||
  242. ( browser.webkit && version >= 522 ) ||
  243. false );
  244. return browser;
  245. }();
  246. //快捷方式
  247. var ie = browser.ie,
  248. webkit = browser.webkit,
  249. gecko = browser.gecko,
  250. opera = browser.opera;
  251. // core/utils.js
  252. /**
  253. * 工具函数包
  254. * @file
  255. * @module UE.utils
  256. * @since 1.2.6.1
  257. */
  258. /**
  259. * UEditor封装使用的静态工具函数
  260. * @module UE.utils
  261. * @unfile
  262. */
  263. var utils = UE.utils = {
  264. /**
  265. * 用给定的迭代器遍历对象
  266. * @method each
  267. * @param { Object } obj 需要遍历的对象
  268. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  269. * @example
  270. * ```javascript
  271. * var demoObj = {
  272. * key1: 1,
  273. * key2: 2
  274. * };
  275. *
  276. * //output: key1: 1, key2: 2
  277. * UE.utils.each( demoObj, funciton ( value, key ) {
  278. *
  279. * console.log( key + ":" + value );
  280. *
  281. * } );
  282. * ```
  283. */
  284. /**
  285. * 用给定的迭代器遍历数组或类数组对象
  286. * @method each
  287. * @param { Array } array 需要遍历的数组或者类数组
  288. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  289. * @example
  290. * ```javascript
  291. * var divs = document.getElmentByTagNames( "div" );
  292. *
  293. * //output: 0: DIV, 1: DIV ...
  294. * UE.utils.each( divs, funciton ( value, key ) {
  295. *
  296. * console.log( key + ":" + value.tagName );
  297. *
  298. * } );
  299. * ```
  300. */
  301. each : function(obj, iterator, context) {
  302. if (obj == null) return;
  303. if (obj.length === +obj.length) {
  304. for (var i = 0, l = obj.length; i < l; i++) {
  305. if(iterator.call(context, obj[i], i, obj) === false)
  306. return false;
  307. }
  308. } else {
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. if(iterator.call(context, obj[key], key, obj) === false)
  312. return false;
  313. }
  314. }
  315. }
  316. },
  317. /**
  318. * 以给定对象作为原型创建一个新对象
  319. * @method makeInstance
  320. * @param { Object } protoObject 该对象将作为新创建对象的原型
  321. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  322. * @example
  323. * ```javascript
  324. *
  325. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  326. *
  327. * var newObject = UE.utils.makeInstance( protoObject );
  328. * //output: Hello UEditor!
  329. * newObject.sayHello();
  330. * ```
  331. */
  332. makeInstance:function (obj) {
  333. var noop = new Function();
  334. noop.prototype = obj;
  335. obj = new noop;
  336. noop.prototype = null;
  337. return obj;
  338. },
  339. /**
  340. * 将source对象中的属性扩展到target对象上
  341. * @method extend
  342. * @remind 该方法将强制把source对象上的属性复制到target对象上
  343. * @see UE.utils.extend(Object,Object,Boolean)
  344. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  345. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  346. * @return { Object } 返回target对象
  347. * @example
  348. * ```javascript
  349. *
  350. * var target = { name: 'target', sex: 1 },
  351. * source = { name: 'source', age: 17 };
  352. *
  353. * UE.utils.extend( target, source );
  354. *
  355. * //output: { name: 'source', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. /**
  361. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  362. * 源对象属性名相同的属性值。
  363. * @method extend
  364. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  365. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  366. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  367. * @return { Object } 返回target对象
  368. * @example
  369. * ```javascript
  370. *
  371. * var target = { name: 'target', sex: 1 },
  372. * source = { name: 'source', age: 17 };
  373. *
  374. * UE.utils.extend( target, source, true );
  375. *
  376. * //output: { name: 'target', sex: 1, age: 17 }
  377. * console.log( target );
  378. *
  379. * ```
  380. */
  381. extend:function (t, s, b) {
  382. if (s) {
  383. for (var k in s) {
  384. if (!b || !t.hasOwnProperty(k)) {
  385. t[k] = s[k];
  386. }
  387. }
  388. }
  389. return t;
  390. },
  391. /**
  392. * 将给定的多个对象的属性复制到目标对象target上
  393. * @method extend2
  394. * @remind 该方法将强制把源对象上的属性复制到target对象上
  395. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  396. * 将会覆盖掉之前的值。
  397. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  398. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  399. * @return { Object } 返回target对象
  400. * @example
  401. * ```javascript
  402. *
  403. * var target = {},
  404. * source1 = { name: 'source', age: 17 },
  405. * source2 = { title: 'dev' };
  406. *
  407. * UE.utils.extend2( target, source1, source2 );
  408. *
  409. * //output: { name: 'source', age: 17, title: 'dev' }
  410. * console.log( target );
  411. *
  412. * ```
  413. */
  414. extend2:function (t) {
  415. var a = arguments;
  416. for (var i = 1; i < a.length; i++) {
  417. var x = a[i];
  418. for (var k in x) {
  419. if (!t.hasOwnProperty(k)) {
  420. t[k] = x[k];
  421. }
  422. }
  423. }
  424. return t;
  425. },
  426. /**
  427. * 模拟继承机制, 使得subClass继承自superClass
  428. * @method inherits
  429. * @param { Object } subClass 子类对象
  430. * @param { Object } superClass 超类对象
  431. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  432. * @return { Object } 继承superClass后的子类对象
  433. * @example
  434. * ```javascript
  435. * function SuperClass(){
  436. * this.name = "小李";
  437. * }
  438. *
  439. * SuperClass.prototype = {
  440. * hello:function(str){
  441. * console.log(this.name + str);
  442. * }
  443. * }
  444. *
  445. * function SubClass(){
  446. * this.name = "小张";
  447. * }
  448. *
  449. * UE.utils.inherits(SubClass,SuperClass);
  450. *
  451. * var sub = new SubClass();
  452. * //output: '小张早上好!
  453. * sub.hello("早上好!");
  454. * ```
  455. */
  456. inherits:function (subClass, superClass) {
  457. var oldP = subClass.prototype,
  458. newP = utils.makeInstance(superClass.prototype);
  459. utils.extend(newP, oldP, true);
  460. subClass.prototype = newP;
  461. return (newP.constructor = subClass);
  462. },
  463. /**
  464. * 用指定的context对象作为函数fn的上下文
  465. * @method bind
  466. * @param { Function } fn 需要绑定上下文的函数对象
  467. * @param { Object } content 函数fn新的上下文对象
  468. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  469. * @example
  470. * ```javascript
  471. *
  472. * var name = 'window',
  473. * newTest = null;
  474. *
  475. * function test () {
  476. * console.log( this.name );
  477. * }
  478. *
  479. * newTest = UE.utils.bind( test, { name: 'object' } );
  480. *
  481. * //output: object
  482. * newTest();
  483. *
  484. * //output: window
  485. * test();
  486. *
  487. * ```
  488. */
  489. bind:function (fn, context) {
  490. return function () {
  491. return fn.apply(context, arguments);
  492. };
  493. },
  494. /**
  495. * 创建延迟指定时间后执行的函数fn
  496. * @method defer
  497. * @param { Function } fn 需要延迟执行的函数对象
  498. * @param { int } delay 延迟的时间, 单位是毫秒
  499. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  500. * 而不能保证刚好到达延迟时间时执行。
  501. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  502. * @example
  503. * ```javascript
  504. * var start = 0;
  505. *
  506. * function test(){
  507. * console.log( new Date() - start );
  508. * }
  509. *
  510. * var testDefer = UE.utils.defer( test, 1000 );
  511. * //
  512. * start = new Date();
  513. * //output: (大约在1000毫秒之后输出) 1000
  514. * testDefer();
  515. * ```
  516. */
  517. /**
  518. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  519. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  520. * @method defer
  521. * @param { Function } fn 需要延迟执行的函数对象
  522. * @param { int } delay 延迟的时间, 单位是毫秒
  523. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  524. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  525. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  526. * 而不能保证刚好到达延迟时间时执行。
  527. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  528. * @example
  529. * ```javascript
  530. *
  531. * function test(){
  532. * console.log(1);
  533. * }
  534. *
  535. * var testDefer = UE.utils.defer( test, 1000, true );
  536. *
  537. * //output: (两次调用仅有一次输出) 1
  538. * testDefer();
  539. * testDefer();
  540. * ```
  541. */
  542. defer:function (fn, delay, exclusion) {
  543. var timerID;
  544. return function () {
  545. if (exclusion) {
  546. clearTimeout(timerID);
  547. }
  548. timerID = setTimeout(fn, delay);
  549. };
  550. },
  551. /**
  552. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  558. * @example
  559. * ```javascript
  560. * var item = 1,
  561. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  562. *
  563. * //output: 4
  564. * console.log( UE.utils.indexOf( arr, item ) );
  565. * ```
  566. */
  567. /**
  568. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  569. * @method indexOf
  570. * @remind 该方法的匹配过程使用的是恒等“===”
  571. * @param { Array } array 需要查找的数组对象
  572. * @param { * } item 需要在目标数组中查找的值
  573. * @param { int } start 搜索的起始位置
  574. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  575. * @example
  576. * ```javascript
  577. * var item = 1,
  578. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  579. *
  580. * //output: 9
  581. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  582. * ```
  583. */
  584. indexOf:function (array, item, start) {
  585. var index = -1;
  586. start = this.isNumber(start) ? start : 0;
  587. this.each(array, function (v, i) {
  588. if (i >= start && v === item) {
  589. index = i;
  590. return false;
  591. }
  592. });
  593. return index;
  594. },
  595. /**
  596. * 移除数组array中所有的元素item
  597. * @method removeItem
  598. * @param { Array } array 要移除元素的目标数组
  599. * @param { * } item 将要被移除的元素
  600. * @remind 该方法的匹配过程使用的是恒等“===”
  601. * @example
  602. * ```javascript
  603. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  604. *
  605. * UE.utils.removeItem( arr, 4 );
  606. * //output: [ 5, 7, 1, 3, 6 ]
  607. * console.log( arr );
  608. *
  609. * ```
  610. */
  611. removeItem:function (array, item) {
  612. for (var i = 0, l = array.length; i < l; i++) {
  613. if (array[i] === item) {
  614. array.splice(i, 1);
  615. i--;
  616. }
  617. }
  618. },
  619. /**
  620. * 删除字符串str的首尾空格
  621. * @method trim
  622. * @param { String } str 需要删除首尾空格的字符串
  623. * @return { String } 删除了首尾的空格后的字符串
  624. * @example
  625. * ```javascript
  626. *
  627. * var str = " UEdtior ";
  628. *
  629. * //output: 9
  630. * console.log( str.length );
  631. *
  632. * //output: 7
  633. * console.log( UE.utils.trim( " UEdtior " ).length );
  634. *
  635. * //output: 9
  636. * console.log( str.length );
  637. *
  638. * ```
  639. */
  640. trim:function (str) {
  641. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  642. },
  643. /**
  644. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  645. * @method listToMap
  646. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  647. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  648. * @return { Object } 转化之后的hash对象
  649. * @example
  650. * ```javascript
  651. *
  652. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  653. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  654. *
  655. * ```
  656. */
  657. /**
  658. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  659. * @method listToMap
  660. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  661. * @param { Array } arr 字符串数组
  662. * @return { Object } 转化之后的hash对象
  663. * @example
  664. * ```javascript
  665. *
  666. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  667. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  668. *
  669. * ```
  670. */
  671. listToMap:function (list) {
  672. if (!list)return {};
  673. list = utils.isArray(list) ? list : list.split(',');
  674. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  675. obj[ci.toUpperCase()] = obj[ci] = 1;
  676. }
  677. return obj;
  678. },
  679. /**
  680. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  681. * @method unhtml
  682. * @param { String } str 需要转义的字符串
  683. * @return { String } 转义后的字符串
  684. * @example
  685. * ```javascript
  686. * var html = '<body>&</body>';
  687. *
  688. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  689. * console.log( UE.utils.unhtml( html ) );
  690. *
  691. * ```
  692. */
  693. unhtml:function (str, reg) {
  694. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  695. if (b) {
  696. return a;
  697. } else {
  698. return {
  699. '<':'&lt;',
  700. '&':'&amp;',
  701. '"':'&quot;',
  702. '>':'&gt;',
  703. "'":'&#39;'
  704. }[a]
  705. }
  706. }) : '';
  707. },
  708. /**
  709. * 将str中的转义字符还原成html字符
  710. * @see UE.utils.unhtml(String);
  711. * @method html
  712. * @param { String } str 需要逆转义的字符串
  713. * @return { String } 逆转义后的字符串
  714. * @example
  715. * ```javascript
  716. *
  717. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  718. *
  719. * //output: <body>&</body>
  720. * console.log( UE.utils.html( str ) );
  721. *
  722. * ```
  723. */
  724. html:function (str) {
  725. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  726. return {
  727. '&lt;':'<',
  728. '&amp;':'&',
  729. '&quot;':'"',
  730. '&gt;':'>',
  731. '&#39;':"'",
  732. '&nbsp;':' '
  733. }[m]
  734. }) : '';
  735. },
  736. /**
  737. * 将css样式转换为驼峰的形式
  738. * @method cssStyleToDomStyle
  739. * @param { String } cssName 需要转换的css样式名
  740. * @return { String } 转换成驼峰形式后的css样式名
  741. * @example
  742. * ```javascript
  743. *
  744. * var str = 'border-top';
  745. *
  746. * //output: borderTop
  747. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  748. *
  749. * ```
  750. */
  751. cssStyleToDomStyle:function () {
  752. var test = document.createElement('div').style,
  753. cache = {
  754. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  755. };
  756. return function (cssName) {
  757. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  758. return match.charAt(1).toUpperCase();
  759. }));
  760. };
  761. }(),
  762. /**
  763. * 动态加载文件到doc中
  764. * @method loadFile
  765. * @param { DomDocument } document 需要加载资源文件的文档对象
  766. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  767. * @example
  768. * ```javascript
  769. *
  770. * UE.utils.loadFile( document, {
  771. * src:"test.js",
  772. * tag:"script",
  773. * type:"text/javascript",
  774. * defer:"defer"
  775. * } );
  776. *
  777. * ```
  778. */
  779. /**
  780. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  781. * @method loadFile
  782. * @param { DomDocument } document 需要加载资源文件的文档对象
  783. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  784. * @param { Function } fn 资源文件加载成功之后执行的回调
  785. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  786. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  787. * @example
  788. * ```javascript
  789. *
  790. * UE.utils.loadFile( document, {
  791. * src:"test.js",
  792. * tag:"script",
  793. * type:"text/javascript",
  794. * defer:"defer"
  795. * }, function () {
  796. * console.log('加载成功');
  797. * } );
  798. *
  799. * ```
  800. */
  801. loadFile:function () {
  802. var tmpList = [];
  803. function getItem(doc, obj) {
  804. try {
  805. for (var i = 0, ci; ci = tmpList[i++];) {
  806. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  807. return ci;
  808. }
  809. }
  810. } catch (e) {
  811. return null;
  812. }
  813. }
  814. return function (doc, obj, fn) {
  815. var item = getItem(doc, obj);
  816. if (item) {
  817. if (item.ready) {
  818. fn && fn();
  819. } else {
  820. item.funs.push(fn)
  821. }
  822. return;
  823. }
  824. tmpList.push({
  825. doc:doc,
  826. url:obj.src || obj.href,
  827. funs:[fn]
  828. });
  829. if (!doc.body) {
  830. var html = [];
  831. for (var p in obj) {
  832. if (p == 'tag')continue;
  833. html.push(p + '="' + obj[p] + '"')
  834. }
  835. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  836. return;
  837. }
  838. if (obj.id && doc.getElementById(obj.id)) {
  839. return;
  840. }
  841. var element = doc.createElement(obj.tag);
  842. delete obj.tag;
  843. for (var p in obj) {
  844. element.setAttribute(p, obj[p]);
  845. }
  846. element.onload = element.onreadystatechange = function () {
  847. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  848. item = getItem(doc, obj);
  849. if (item.funs.length > 0) {
  850. item.ready = 1;
  851. for (var fi; fi = item.funs.pop();) {
  852. fi();
  853. }
  854. }
  855. element.onload = element.onreadystatechange = null;
  856. }
  857. };
  858. element.onerror = function () {
  859. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  860. };
  861. doc.getElementsByTagName("head")[0].appendChild(element);
  862. }
  863. }(),
  864. /**
  865. * 判断obj对象是否为空
  866. * @method isEmptyObject
  867. * @param { * } obj 需要判断的对象
  868. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  869. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  870. * @return { Boolean } 对象是否为空
  871. * @example
  872. * ```javascript
  873. *
  874. * //output: true
  875. * console.log( UE.utils.isEmptyObject( {} ) );
  876. *
  877. * //output: true
  878. * console.log( UE.utils.isEmptyObject( [] ) );
  879. *
  880. * //output: true
  881. * console.log( UE.utils.isEmptyObject( "" ) );
  882. *
  883. * //output: false
  884. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  885. *
  886. * //output: false
  887. * console.log( UE.utils.isEmptyObject( [1] ) );
  888. *
  889. * //output: false
  890. * console.log( UE.utils.isEmptyObject( "1" ) );
  891. *
  892. * ```
  893. */
  894. isEmptyObject:function (obj) {
  895. if (obj == null) return true;
  896. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  897. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  898. return true;
  899. },
  900. /**
  901. * 把rgb格式的颜色值转换成16进制格式
  902. * @method fixColor
  903. * @param { String } rgb格式的颜色值
  904. * @param { String }
  905. * @example
  906. * rgb(255,255,255) => "#ffffff"
  907. */
  908. fixColor:function (name, value) {
  909. if (/color/i.test(name) && /rgba?/.test(value)) {
  910. var array = value.split(",");
  911. if (array.length > 3)
  912. return "";
  913. value = "#";
  914. for (var i = 0, color; color = array[i++];) {
  915. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  916. value += color.length == 1 ? "0" + color : color;
  917. }
  918. value = value.toUpperCase();
  919. }
  920. return value;
  921. },
  922. /**
  923. * 只针对border,padding,margin做了处理,因为性能问题
  924. * @public
  925. * @function
  926. * @param {String} val style字符串
  927. */
  928. optCss:function (val) {
  929. var padding, margin, border;
  930. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  931. if (val.split(' ').length == 1) {
  932. switch (key) {
  933. case 'padding':
  934. !padding && (padding = {});
  935. padding[name] = val;
  936. return '';
  937. case 'margin':
  938. !margin && (margin = {});
  939. margin[name] = val;
  940. return '';
  941. case 'border':
  942. return val == 'initial' ? '' : str;
  943. }
  944. }
  945. return str;
  946. });
  947. function opt(obj, name) {
  948. if (!obj) {
  949. return '';
  950. }
  951. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  952. if (!t || !l || !b || !r) {
  953. for (var p in obj) {
  954. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  955. }
  956. } else {
  957. val += ';' + name + ':' +
  958. (t == b && b == l && l == r ? t :
  959. t == b && l == r ? (t + ' ' + l) :
  960. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  961. }
  962. return val;
  963. }
  964. val += opt(padding, 'padding') + opt(margin, 'margin');
  965. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  966. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  967. return b ? b + ";;" : ';'
  968. });
  969. },
  970. /**
  971. * 克隆对象
  972. * @method clone
  973. * @param { Object } source 源对象
  974. * @return { Object } source的一个副本
  975. */
  976. /**
  977. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  978. * @method clone
  979. * @param { Object } source 源对象
  980. * @param { Object } target 目标对象
  981. * @return { Object } 附加了source对象所有属性的target对象
  982. */
  983. clone:function (source, target) {
  984. var tmp;
  985. target = target || {};
  986. for (var i in source) {
  987. if (source.hasOwnProperty(i)) {
  988. tmp = source[i];
  989. if (typeof tmp == 'object') {
  990. target[i] = utils.isArray(tmp) ? [] : {};
  991. utils.clone(source[i], target[i])
  992. } else {
  993. target[i] = tmp;
  994. }
  995. }
  996. }
  997. return target;
  998. },
  999. /**
  1000. * 把cm/pt为单位的值转换为px为单位的值
  1001. * @method transUnitToPx
  1002. * @param { String } 待转换的带单位的字符串
  1003. * @return { String } 转换为px为计量单位的值的字符串
  1004. * @example
  1005. * ```javascript
  1006. *
  1007. * //output: 500px
  1008. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1009. *
  1010. * //output: 27px
  1011. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1012. *
  1013. * ```
  1014. */
  1015. transUnitToPx:function (val) {
  1016. if (!/(pt|cm)/.test(val)) {
  1017. return val
  1018. }
  1019. var unit;
  1020. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1021. val = v;
  1022. unit = u;
  1023. });
  1024. switch (unit) {
  1025. case 'cm':
  1026. val = parseFloat(val) * 25;
  1027. break;
  1028. case 'pt':
  1029. val = Math.round(parseFloat(val) * 96 / 72);
  1030. }
  1031. return val + (val ? 'px' : '');
  1032. },
  1033. /**
  1034. * 在dom树ready之后执行给定的回调函数
  1035. * @method domReady
  1036. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1037. * @param { Function } fn dom树ready之后的回调函数
  1038. * @example
  1039. * ```javascript
  1040. *
  1041. * UE.utils.domReady( function () {
  1042. *
  1043. * console.log('123');
  1044. *
  1045. * } );
  1046. *
  1047. * ```
  1048. */
  1049. domReady:function () {
  1050. var fnArr = [];
  1051. function doReady(doc) {
  1052. //确保onready只执行一次
  1053. doc.isReady = true;
  1054. for (var ci; ci = fnArr.pop(); ci()) {
  1055. }
  1056. }
  1057. return function (onready, win) {
  1058. win = win || window;
  1059. var doc = win.document;
  1060. onready && fnArr.push(onready);
  1061. if (doc.readyState === "complete") {
  1062. doReady(doc);
  1063. } else {
  1064. doc.isReady && doReady(doc);
  1065. if (browser.ie && browser.version != 11) {
  1066. (function () {
  1067. if (doc.isReady) return;
  1068. try {
  1069. doc.documentElement.doScroll("left");
  1070. } catch (error) {
  1071. setTimeout(arguments.callee, 0);
  1072. return;
  1073. }
  1074. doReady(doc);
  1075. })();
  1076. win.attachEvent('onload', function () {
  1077. doReady(doc)
  1078. });
  1079. } else {
  1080. doc.addEventListener("DOMContentLoaded", function () {
  1081. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1082. doReady(doc);
  1083. }, false);
  1084. win.addEventListener('load', function () {
  1085. doReady(doc)
  1086. }, false);
  1087. }
  1088. }
  1089. }
  1090. }(),
  1091. /**
  1092. * 动态添加css样式
  1093. * @method cssRule
  1094. * @param { String } 节点名称
  1095. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1096. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1097. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1098. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1099. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1100. */
  1101. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1102. var indexList, index;
  1103. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1104. //获取样式
  1105. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1106. indexList = doc.indexList || (doc.indexList = {});
  1107. index = indexList[key];
  1108. if(index !== undefined){
  1109. return doc.styleSheets[index].cssText
  1110. }
  1111. return undefined;
  1112. }
  1113. doc = doc || document;
  1114. indexList = doc.indexList || (doc.indexList = {});
  1115. index = indexList[key];
  1116. //清除样式
  1117. if(style === ''){
  1118. if(index!== undefined){
  1119. doc.styleSheets[index].cssText = '';
  1120. delete indexList[key];
  1121. return true
  1122. }
  1123. return false;
  1124. }
  1125. //添加样式
  1126. if(index!== undefined){
  1127. sheetStyle = doc.styleSheets[index];
  1128. }else{
  1129. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1130. indexList[key] = index;
  1131. }
  1132. sheetStyle.cssText = style;
  1133. }: function (key, style, doc) {
  1134. var head, node;
  1135. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1136. //获取样式
  1137. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1138. node = doc.getElementById(key);
  1139. return node ? node.innerHTML : undefined;
  1140. }
  1141. doc = doc || document;
  1142. node = doc.getElementById(key);
  1143. //清除样式
  1144. if(style === ''){
  1145. if(node){
  1146. node.parentNode.removeChild(node);
  1147. return true
  1148. }
  1149. return false;
  1150. }
  1151. //添加样式
  1152. if(node){
  1153. node.innerHTML = style;
  1154. }else{
  1155. node = doc.createElement('style');
  1156. node.id = key;
  1157. node.innerHTML = style;
  1158. doc.getElementsByTagName('head')[0].appendChild(node);
  1159. }
  1160. },
  1161. sort:function(array,compareFn){
  1162. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1163. for(var i= 0,len = array.length; i<len; i++){
  1164. for(var j = i,length = array.length; j<length; j++){
  1165. if(compareFn(array[i], array[j]) > 0){
  1166. var t = array[i];
  1167. array[i] = array[j];
  1168. array[j] = t;
  1169. }
  1170. }
  1171. }
  1172. return array;
  1173. },
  1174. serializeParam:function (json) {
  1175. var strArr = [];
  1176. for (var i in json) {
  1177. //忽略默认的几个参数
  1178. if(i=="method" || i=="timeout" || i=="async") continue;
  1179. //传递过来的对象和函数不在提交之列
  1180. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1181. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1182. } else if (utils.isArray(json[i])) {
  1183. //支持传数组内容
  1184. for(var j = 0; j < json[i].length; j++) {
  1185. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1186. }
  1187. }
  1188. }
  1189. return strArr.join("&");
  1190. },
  1191. formatUrl:function (url) {
  1192. var u = url.replace(/&&/g, '&');
  1193. u = u.replace(/\?&/g, '?');
  1194. u = u.replace(/&$/g, '');
  1195. u = u.replace(/&#/g, '#');
  1196. u = u.replace(/&+/g, '&');
  1197. return u;
  1198. },
  1199. isCrossDomainUrl:function (url) {
  1200. var a = document.createElement('a');
  1201. a.href = url;
  1202. if (browser.ie) {
  1203. a.href = a.href;
  1204. }
  1205. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1206. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1207. },
  1208. clearEmptyAttrs : function(obj){
  1209. for(var p in obj){
  1210. if(obj[p] === ''){
  1211. delete obj[p]
  1212. }
  1213. }
  1214. return obj;
  1215. },
  1216. str2json : function(s){
  1217. if (!utils.isString(s)) return null;
  1218. if (window.JSON) {
  1219. return JSON.parse(s);
  1220. } else {
  1221. return (new Function("return " + utils.trim(s || '')))();
  1222. }
  1223. },
  1224. json2str : (function(){
  1225. if (window.JSON) {
  1226. return JSON.stringify;
  1227. } else {
  1228. var escapeMap = {
  1229. "\b": '\\b',
  1230. "\t": '\\t',
  1231. "\n": '\\n',
  1232. "\f": '\\f',
  1233. "\r": '\\r',
  1234. '"' : '\\"',
  1235. "\\": '\\\\'
  1236. };
  1237. function encodeString(source) {
  1238. if (/["\\\x00-\x1f]/.test(source)) {
  1239. source = source.replace(
  1240. /["\\\x00-\x1f]/g,
  1241. function (match) {
  1242. var c = escapeMap[match];
  1243. if (c) {
  1244. return c;
  1245. }
  1246. c = match.charCodeAt();
  1247. return "\\u00"
  1248. + Math.floor(c / 16).toString(16)
  1249. + (c % 16).toString(16);
  1250. });
  1251. }
  1252. return '"' + source + '"';
  1253. }
  1254. function encodeArray(source) {
  1255. var result = ["["],
  1256. l = source.length,
  1257. preComma, i, item;
  1258. for (i = 0; i < l; i++) {
  1259. item = source[i];
  1260. switch (typeof item) {
  1261. case "undefined":
  1262. case "function":
  1263. case "unknown":
  1264. break;
  1265. default:
  1266. if(preComma) {
  1267. result.push(',');
  1268. }
  1269. result.push(utils.json2str(item));
  1270. preComma = 1;
  1271. }
  1272. }
  1273. result.push("]");
  1274. return result.join("");
  1275. }
  1276. function pad(source) {
  1277. return source < 10 ? '0' + source : source;
  1278. }
  1279. function encodeDate(source){
  1280. return '"' + source.getFullYear() + "-"
  1281. + pad(source.getMonth() + 1) + "-"
  1282. + pad(source.getDate()) + "T"
  1283. + pad(source.getHours()) + ":"
  1284. + pad(source.getMinutes()) + ":"
  1285. + pad(source.getSeconds()) + '"';
  1286. }
  1287. return function (value) {
  1288. switch (typeof value) {
  1289. case 'undefined':
  1290. return 'undefined';
  1291. case 'number':
  1292. return isFinite(value) ? String(value) : "null";
  1293. case 'string':
  1294. return encodeString(value);
  1295. case 'boolean':
  1296. return String(value);
  1297. default:
  1298. if (value === null) {
  1299. return 'null';
  1300. } else if (utils.isArray(value)) {
  1301. return encodeArray(value);
  1302. } else if (utils.isArray(value)) {
  1303. return encodeDate(value);
  1304. } else {
  1305. var result = ['{'],
  1306. encode = utils.json2str,
  1307. preComma,
  1308. item;
  1309. for (var key in value) {
  1310. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1311. item = value[key];
  1312. switch (typeof item) {
  1313. case 'undefined':
  1314. case 'unknown':
  1315. case 'function':
  1316. break;
  1317. default:
  1318. if (preComma) {
  1319. result.push(',');
  1320. }
  1321. preComma = 1;
  1322. result.push(encode(key) + ':' + encode(item));
  1323. }
  1324. }
  1325. }
  1326. result.push('}');
  1327. return result.join('');
  1328. }
  1329. }
  1330. };
  1331. }
  1332. })()
  1333. };
  1334. /**
  1335. * 判断给定的对象是否是字符串
  1336. * @method isString
  1337. * @param { * } object 需要判断的对象
  1338. * @return { Boolean } 给定的对象是否是字符串
  1339. */
  1340. /**
  1341. * 判断给定的对象是否是数组
  1342. * @method isArray
  1343. * @param { * } object 需要判断的对象
  1344. * @return { Boolean } 给定的对象是否是数组
  1345. */
  1346. /**
  1347. * 判断给定的对象是否是一个Function
  1348. * @method isFunction
  1349. * @param { * } object 需要判断的对象
  1350. * @return { Boolean } 给定的对象是否是Function
  1351. */
  1352. /**
  1353. * 判断给定的对象是否是Number
  1354. * @method isNumber
  1355. * @param { * } object 需要判断的对象
  1356. * @return { Boolean } 给定的对象是否是Number
  1357. */
  1358. /**
  1359. * 判断给定的对象是否是一个正则表达式
  1360. * @method isRegExp
  1361. * @param { * } object 需要判断的对象
  1362. * @return { Boolean } 给定的对象是否是正则表达式
  1363. */
  1364. /**
  1365. * 判断给定的对象是否是一个普通对象
  1366. * @method isObject
  1367. * @param { * } object 需要判断的对象
  1368. * @return { Boolean } 给定的对象是否是普通对象
  1369. */
  1370. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1371. UE.utils['is' + v] = function (obj) {
  1372. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1373. }
  1374. });
  1375. // core/EventBase.js
  1376. /**
  1377. * UE采用的事件基类
  1378. * @file
  1379. * @module UE
  1380. * @class EventBase
  1381. * @since 1.2.6.1
  1382. */
  1383. /**
  1384. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1385. * @unfile
  1386. * @module UE
  1387. */
  1388. /**
  1389. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1390. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1391. * @unfile
  1392. * @module UE
  1393. * @class EventBase
  1394. */
  1395. /**
  1396. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1397. * @constructor
  1398. * @example
  1399. * ```javascript
  1400. * UE.EventBase.call(editor);
  1401. * ```
  1402. */
  1403. var EventBase = UE.EventBase = function () {};
  1404. EventBase.prototype = {
  1405. /**
  1406. * 注册事件监听器
  1407. * @method addListener
  1408. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1409. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1410. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1411. * @example
  1412. * ```javascript
  1413. * editor.addListener('selectionchange',function(){
  1414. * console.log("选区已经变化!");
  1415. * })
  1416. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1417. * if(type == 'beforegetcontent'){
  1418. * //do something
  1419. * }else{
  1420. * //do something
  1421. * }
  1422. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1423. * })
  1424. * ```
  1425. * @see UE.EventBase:fireEvent(String)
  1426. */
  1427. addListener:function (types, listener) {
  1428. types = utils.trim(types).split(/\s+/);
  1429. for (var i = 0, ti; ti = types[i++];) {
  1430. getListener(this, ti, true).push(listener);
  1431. }
  1432. },
  1433. on : function(types, listener){
  1434. return this.addListener(types,listener);
  1435. },
  1436. off : function(types, listener){
  1437. return this.removeListener(types, listener)
  1438. },
  1439. trigger:function(){
  1440. return this.fireEvent.apply(this,arguments);
  1441. },
  1442. /**
  1443. * 移除事件监听器
  1444. * @method removeListener
  1445. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1446. * @param { Function } fn 移除监听事件的函数引用
  1447. * @example
  1448. * ```javascript
  1449. * //changeCallback为方法体
  1450. * editor.removeListener("selectionchange",changeCallback);
  1451. * ```
  1452. */
  1453. removeListener:function (types, listener) {
  1454. types = utils.trim(types).split(/\s+/);
  1455. for (var i = 0, ti; ti = types[i++];) {
  1456. utils.removeItem(getListener(this, ti) || [], listener);
  1457. }
  1458. },
  1459. /**
  1460. * 触发事件
  1461. * @method fireEvent
  1462. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1463. * @remind 该方法会触发addListener
  1464. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1465. * @example
  1466. * ```javascript
  1467. * editor.fireEvent("selectionchange");
  1468. * ```
  1469. */
  1470. /**
  1471. * 触发事件
  1472. * @method fireEvent
  1473. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1474. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1475. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1476. * @example
  1477. * ```javascript
  1478. *
  1479. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1480. *
  1481. * console.log( arg1 + " " + arg2 );
  1482. *
  1483. * } );
  1484. *
  1485. * //触发selectionchange事件, 会执行上面的事件监听器
  1486. * //output: Hello World
  1487. * editor.fireEvent("selectionchange", "Hello", "World");
  1488. * ```
  1489. */
  1490. fireEvent:function () {
  1491. var types = arguments[0];
  1492. types = utils.trim(types).split(' ');
  1493. for (var i = 0, ti; ti = types[i++];) {
  1494. var listeners = getListener(this, ti),
  1495. r, t, k;
  1496. if (listeners) {
  1497. k = listeners.length;
  1498. while (k--) {
  1499. if(!listeners[k])continue;
  1500. t = listeners[k].apply(this, arguments);
  1501. if(t === true){
  1502. return t;
  1503. }
  1504. if (t !== undefined) {
  1505. r = t;
  1506. }
  1507. }
  1508. }
  1509. if (t = this['on' + ti.toLowerCase()]) {
  1510. r = t.apply(this, arguments);
  1511. }
  1512. }
  1513. return r;
  1514. }
  1515. };
  1516. /**
  1517. * 获得对象所拥有监听类型的所有监听器
  1518. * @unfile
  1519. * @module UE
  1520. * @since 1.2.6.1
  1521. * @method getListener
  1522. * @public
  1523. * @param { Object } obj 查询监听器的对象
  1524. * @param { String } type 事件类型
  1525. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1526. * @return { Array } 监听器数组
  1527. */
  1528. function getListener(obj, type, force) {
  1529. var allListeners;
  1530. type = type.toLowerCase();
  1531. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1532. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1533. }
  1534. // core/dtd.js
  1535. ///import editor.js
  1536. ///import core/dom/dom.js
  1537. ///import core/utils.js
  1538. /**
  1539. * dtd html语义化的体现类
  1540. * @constructor
  1541. * @namespace dtd
  1542. */
  1543. var dtd = dom.dtd = (function() {
  1544. function _( s ) {
  1545. for (var k in s) {
  1546. s[k.toUpperCase()] = s[k];
  1547. }
  1548. return s;
  1549. }
  1550. var X = utils.extend2;
  1551. var A = _({isindex:1,fieldset:1}),
  1552. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1553. C = X( _({a:1}), B ),
  1554. D = X( {iframe:1}, C ),
  1555. 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}),
  1556. F = _({ins:1,del:1,script:1,style:1}),
  1557. 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 ),
  1558. 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 ),
  1559. I = X( _({p:1}), H ),
  1560. J = X( _({iframe:1}), H, B ),
  1561. 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}),
  1562. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1563. M = _({tr:1}),
  1564. N = _({'#':1}),
  1565. O = X( _({param:1}), K ),
  1566. P = X( _({form:1}), A, D, E, I ),
  1567. Q = _({li:1,ol:1,ul:1}),
  1568. R = _({style:1,script:1}),
  1569. S = _({base:1,link:1,meta:1,title:1}),
  1570. T = X( S, R ),
  1571. U = _({head:1,body:1}),
  1572. V = _({html:1});
  1573. 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}),
  1574. 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});
  1575. return _({
  1576. // $ 表示自定的属性
  1577. // body外的元素列表.
  1578. $nonBodyContent: X( V, U, S ),
  1579. //块结构元素列表
  1580. $block : block,
  1581. //内联元素列表
  1582. $inline : L,
  1583. $inlineWithA : X(_({a:1}),L),
  1584. $body : X( _({script:1,style:1}), block ),
  1585. $cdata : _({script:1,style:1}),
  1586. //自闭和元素
  1587. $empty : empty,
  1588. //不是自闭合,但不能让range选中里边
  1589. $nonChild : _({iframe:1,textarea:1}),
  1590. //列表元素列表
  1591. $listItem : _({dd:1,dt:1,li:1}),
  1592. //列表根元素列表
  1593. $list: _({ul:1,ol:1,dl:1}),
  1594. //不能认为是空的元素
  1595. $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}),
  1596. //如果没有子节点就可以删除的元素列表,像span,a
  1597. $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}),
  1598. $removeEmptyBlock : _({'p':1,'div':1}),
  1599. //在table元素里的元素列表
  1600. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1601. //不转换的标签
  1602. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1603. html: U,
  1604. head: T,
  1605. style: N,
  1606. script: N,
  1607. body: P,
  1608. base: {},
  1609. link: {},
  1610. meta: {},
  1611. title: N,
  1612. col : {},
  1613. tr : _({td:1,th:1}),
  1614. img : {},
  1615. embed: {},
  1616. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1617. noscript : P,
  1618. td : P,
  1619. br : {},
  1620. th : P,
  1621. center : P,
  1622. kbd : L,
  1623. button : X( I, E ),
  1624. basefont : {},
  1625. h5 : L,
  1626. h4 : L,
  1627. samp : L,
  1628. h6 : L,
  1629. ol : Q,
  1630. h1 : L,
  1631. h3 : L,
  1632. option : N,
  1633. h2 : L,
  1634. form : X( A, D, E, I ),
  1635. select : _({optgroup:1,option:1}),
  1636. font : L,
  1637. ins : L,
  1638. menu : Q,
  1639. abbr : L,
  1640. label : L,
  1641. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1642. code : L,
  1643. tfoot : M,
  1644. cite : L,
  1645. li : P,
  1646. input : {},
  1647. iframe : P,
  1648. strong : L,
  1649. textarea : N,
  1650. noframes : P,
  1651. big : L,
  1652. small : L,
  1653. //trace:
  1654. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1655. hr : L,
  1656. dt : L,
  1657. sub : L,
  1658. optgroup : _({option:1}),
  1659. param : {},
  1660. bdo : L,
  1661. 'var' : L,
  1662. div : P,
  1663. object : O,
  1664. sup : L,
  1665. dd : P,
  1666. strike : L,
  1667. area : {},
  1668. dir : Q,
  1669. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1670. applet : O,
  1671. dl : _({dt:1,dd:1}),
  1672. del : L,
  1673. isindex : {},
  1674. fieldset : X( _({legend:1}), K ),
  1675. thead : M,
  1676. ul : Q,
  1677. acronym : L,
  1678. b : L,
  1679. a : X( _({a:1}), J ),
  1680. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1681. caption : L,
  1682. i : L,
  1683. u : L,
  1684. tbody : M,
  1685. s : L,
  1686. address : X( D, I ),
  1687. tt : L,
  1688. legend : L,
  1689. q : L,
  1690. pre : X( G, C ),
  1691. p : X(_({'a':1}),L),
  1692. em :L,
  1693. dfn : L
  1694. });
  1695. })();
  1696. // core/domUtils.js
  1697. /**
  1698. * Dom操作工具包
  1699. * @file
  1700. * @module UE.dom.domUtils
  1701. * @since 1.2.6.1
  1702. */
  1703. /**
  1704. * Dom操作工具包
  1705. * @unfile
  1706. * @module UE.dom.domUtils
  1707. */
  1708. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1709. var tmpNode = startFromChild && node[start],
  1710. parent;
  1711. !tmpNode && (tmpNode = node[ltr]);
  1712. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1713. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1714. return null;
  1715. }
  1716. tmpNode = parent[ltr];
  1717. }
  1718. if (tmpNode && fn && !fn(tmpNode)) {
  1719. return getDomNode(tmpNode, start, ltr, false, fn);
  1720. }
  1721. return tmpNode;
  1722. }
  1723. var attrFix = ie && browser.version < 9 ? {
  1724. tabindex:"tabIndex",
  1725. readonly:"readOnly",
  1726. "for":"htmlFor",
  1727. "class":"className",
  1728. maxlength:"maxLength",
  1729. cellspacing:"cellSpacing",
  1730. cellpadding:"cellPadding",
  1731. rowspan:"rowSpan",
  1732. colspan:"colSpan",
  1733. usemap:"useMap",
  1734. frameborder:"frameBorder"
  1735. } : {
  1736. tabindex:"tabIndex",
  1737. readonly:"readOnly"
  1738. },
  1739. styleBlock = utils.listToMap([
  1740. '-webkit-box', '-moz-box', 'block' ,
  1741. 'list-item' , 'table' , 'table-row-group' ,
  1742. 'table-header-group', 'table-footer-group' ,
  1743. 'table-row' , 'table-column-group' , 'table-column' ,
  1744. 'table-cell' , 'table-caption'
  1745. ]);
  1746. var domUtils = dom.domUtils = {
  1747. //节点常量
  1748. NODE_ELEMENT:1,
  1749. NODE_DOCUMENT:9,
  1750. NODE_TEXT:3,
  1751. NODE_COMMENT:8,
  1752. NODE_DOCUMENT_FRAGMENT:11,
  1753. //位置关系
  1754. POSITION_IDENTICAL:0,
  1755. POSITION_DISCONNECTED:1,
  1756. POSITION_FOLLOWING:2,
  1757. POSITION_PRECEDING:4,
  1758. POSITION_IS_CONTAINED:8,
  1759. POSITION_CONTAINS:16,
  1760. //ie6使用其他的会有一段空白出现
  1761. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1762. //-------------------------Node部分--------------------------------
  1763. keys:{
  1764. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1765. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1766. 37:1, 38:1, 39:1, 40:1,
  1767. 13:1 /*enter*/
  1768. },
  1769. /**
  1770. * 获取节点A相对于节点B的位置关系
  1771. * @method getPosition
  1772. * @param { Node } nodeA 需要查询位置关系的节点A
  1773. * @param { Node } nodeB 需要查询位置关系的节点B
  1774. * @return { Number } 节点A与节点B的关系
  1775. * @example
  1776. * ```javascript
  1777. * //output: 20
  1778. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1779. *
  1780. * switch ( position ) {
  1781. *
  1782. * //0
  1783. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1784. * console.log('元素相同');
  1785. * break;
  1786. * //1
  1787. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1788. * console.log('两个节点在不同的文档中');
  1789. * break;
  1790. * //2
  1791. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1792. * console.log('节点A在节点B之后');
  1793. * break;
  1794. * //4
  1795. * case UE.dom.domUtils.POSITION_PRECEDING;
  1796. * console.log('节点A在节点B之前');
  1797. * break;
  1798. * //8
  1799. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1800. * console.log('节点A被节点B包含');
  1801. * break;
  1802. * case 10:
  1803. * console.log('节点A被节点B包含且节点A在节点B之后');
  1804. * break;
  1805. * //16
  1806. * case UE.dom.domUtils.POSITION_CONTAINS:
  1807. * console.log('节点A包含节点B');
  1808. * break;
  1809. * case 20:
  1810. * console.log('节点A包含节点B且节点A在节点B之前');
  1811. * break;
  1812. *
  1813. * }
  1814. * ```
  1815. */
  1816. getPosition:function (nodeA, nodeB) {
  1817. // 如果两个节点是同一个节点
  1818. if (nodeA === nodeB) {
  1819. // domUtils.POSITION_IDENTICAL
  1820. return 0;
  1821. }
  1822. var node,
  1823. parentsA = [nodeA],
  1824. parentsB = [nodeB];
  1825. node = nodeA;
  1826. while (node = node.parentNode) {
  1827. // 如果nodeB是nodeA的祖先节点
  1828. if (node === nodeB) {
  1829. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1830. return 10;
  1831. }
  1832. parentsA.push(node);
  1833. }
  1834. node = nodeB;
  1835. while (node = node.parentNode) {
  1836. // 如果nodeA是nodeB的祖先节点
  1837. if (node === nodeA) {
  1838. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1839. return 20;
  1840. }
  1841. parentsB.push(node);
  1842. }
  1843. parentsA.reverse();
  1844. parentsB.reverse();
  1845. if (parentsA[0] !== parentsB[0]) {
  1846. // domUtils.POSITION_DISCONNECTED
  1847. return 1;
  1848. }
  1849. var i = -1;
  1850. while (i++, parentsA[i] === parentsB[i]) {
  1851. }
  1852. nodeA = parentsA[i];
  1853. nodeB = parentsB[i];
  1854. while (nodeA = nodeA.nextSibling) {
  1855. if (nodeA === nodeB) {
  1856. // domUtils.POSITION_PRECEDING
  1857. return 4
  1858. }
  1859. }
  1860. // domUtils.POSITION_FOLLOWING
  1861. return 2;
  1862. },
  1863. /**
  1864. * 检测节点node在父节点中的索引位置
  1865. * @method getNodeIndex
  1866. * @param { Node } node 需要检测的节点对象
  1867. * @return { Number } 该节点在父节点中的位置
  1868. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1869. */
  1870. /**
  1871. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1872. * @method getNodeIndex
  1873. * @param { Node } node 需要检测的节点对象
  1874. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1875. * @return { Number } 该节点在父节点中的位置
  1876. * @example
  1877. * ```javascript
  1878. *
  1879. * var node = document.createElement("div");
  1880. *
  1881. * node.appendChild( document.createTextNode( "hello" ) );
  1882. * node.appendChild( document.createTextNode( "world" ) );
  1883. * node.appendChild( node = document.createElement( "div" ) );
  1884. *
  1885. * //output: 2
  1886. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1887. *
  1888. * //output: 1
  1889. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1890. *
  1891. * ```
  1892. */
  1893. getNodeIndex:function (node, ignoreTextNode) {
  1894. var preNode = node,
  1895. i = 0;
  1896. while (preNode = preNode.previousSibling) {
  1897. if (ignoreTextNode && preNode.nodeType == 3) {
  1898. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1899. i++;
  1900. }
  1901. continue;
  1902. }
  1903. i++;
  1904. }
  1905. return i;
  1906. },
  1907. /**
  1908. * 检测节点node是否在给定的document对象上
  1909. * @method inDoc
  1910. * @param { Node } node 需要检测的节点对象
  1911. * @param { DomDocument } doc 需要检测的document对象
  1912. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1913. * @example
  1914. * ```javascript
  1915. *
  1916. * var node = document.createElement("div");
  1917. *
  1918. * //output: false
  1919. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1920. *
  1921. * document.body.appendChild( node );
  1922. *
  1923. * //output: true
  1924. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1925. *
  1926. * ```
  1927. */
  1928. inDoc:function (node, doc) {
  1929. return domUtils.getPosition(node, doc) == 10;
  1930. },
  1931. /**
  1932. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1933. * 查找的起点是给定node节点的父节点。
  1934. * @method findParent
  1935. * @param { Node } node 需要查找的节点
  1936. * @param { Function } filterFn 自定义的过滤方法。
  1937. * @warning 查找的终点是到body节点为止
  1938. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1939. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1940. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1941. * @example
  1942. * ```javascript
  1943. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1944. *
  1945. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1946. * return node.tagName === "HTML";
  1947. *
  1948. * } );
  1949. *
  1950. * //output: true
  1951. * console.log( filterNode === null );
  1952. * ```
  1953. */
  1954. /**
  1955. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1956. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1957. * @method findParent
  1958. * @param { Node } node 需要查找的节点
  1959. * @param { Function } filterFn 自定义的过滤方法。
  1960. * @param { Boolean } includeSelf 查找过程是否包含自身
  1961. * @warning 查找的终点是到body节点为止
  1962. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1963. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1964. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1965. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1966. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1967. * @example
  1968. * ```html
  1969. * <body>
  1970. *
  1971. * <div id="test">
  1972. * </div>
  1973. *
  1974. * <script type="text/javascript">
  1975. *
  1976. * //output: DIV, BODY
  1977. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1978. *
  1979. * console.log( node.tagName );
  1980. * return false;
  1981. *
  1982. * }, true );
  1983. *
  1984. * </script>
  1985. * </body>
  1986. * ```
  1987. */
  1988. findParent:function (node, filterFn, includeSelf) {
  1989. if (node && !domUtils.isBody(node)) {
  1990. node = includeSelf ? node : node.parentNode;
  1991. while (node) {
  1992. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1993. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1994. }
  1995. node = node.parentNode;
  1996. }
  1997. }
  1998. return null;
  1999. },
  2000. /**
  2001. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2002. * @method findParentByTagName
  2003. * @param { Node } node 需要查找的节点对象
  2004. * @param { Array } tagNames 需要查找的父节点的名称数组
  2005. * @warning 查找的终点是到body节点为止
  2006. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2007. * @example
  2008. * ```javascript
  2009. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2010. * //output: BODY
  2011. * console.log( node.tagName );
  2012. * ```
  2013. */
  2014. /**
  2015. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2016. * 否则, 起点是node的父节点。
  2017. * @method findParentByTagName
  2018. * @param { Node } node 需要查找的节点对象
  2019. * @param { Array } tagNames 需要查找的父节点的名称数组
  2020. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2021. * @warning 查找的终点是到body节点为止
  2022. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2023. * @example
  2024. * ```javascript
  2025. * var queryTarget = document.getElementsByTagName("div")[0];
  2026. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2027. * //output: true
  2028. * console.log( queryTarget === node );
  2029. * ```
  2030. */
  2031. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2032. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2033. return domUtils.findParent(node, function (node) {
  2034. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2035. }, includeSelf);
  2036. },
  2037. /**
  2038. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2039. * @method findParents
  2040. * @param { Node } node 需要查找的节点对象
  2041. * @return { Array } 给定节点的祖先节点数组
  2042. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2043. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2044. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2045. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2046. */
  2047. /**
  2048. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2049. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2050. * @method findParents
  2051. * @param { Node } node 需要查找的节点对象
  2052. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2053. * @return { Array } 给定节点的祖先节点数组
  2054. */
  2055. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2056. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2057. while (node = domUtils.findParent(node, filterFn)) {
  2058. parents.push(node);
  2059. }
  2060. return closerFirst ? parents : parents.reverse();
  2061. },
  2062. /**
  2063. * 在节点node后面插入新节点newNode
  2064. * @method insertAfter
  2065. * @param { Node } node 目标节点
  2066. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2067. * @return { Node } 新插入的节点
  2068. */
  2069. insertAfter:function (node, newNode) {
  2070. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2071. node.parentNode.appendChild(newNode);
  2072. },
  2073. /**
  2074. * 删除节点node及其下属的所有节点
  2075. * @method remove
  2076. * @param { Node } node 需要删除的节点对象
  2077. * @return { Node } 返回刚删除的节点对象
  2078. * @example
  2079. * ```html
  2080. * <div id="test">
  2081. * <div id="child">你好</div>
  2082. * </div>
  2083. * <script>
  2084. * UE.dom.domUtils.remove( document.body, false );
  2085. * //output: false
  2086. * console.log( document.getElementById( "child" ) !== null );
  2087. * </script>
  2088. * ```
  2089. */
  2090. /**
  2091. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2092. * @method remove
  2093. * @param { Node } node 需要删除的节点对象
  2094. * @param { Boolean } keepChildren 是否需要保留子节点
  2095. * @return { Node } 返回刚删除的节点对象
  2096. * @example
  2097. * ```html
  2098. * <div id="test">
  2099. * <div id="child">你好</div>
  2100. * </div>
  2101. * <script>
  2102. * UE.dom.domUtils.remove( document.body, true );
  2103. * //output: true
  2104. * console.log( document.getElementById( "child" ) !== null );
  2105. * </script>
  2106. * ```
  2107. */
  2108. remove:function (node, keepChildren) {
  2109. var parent = node.parentNode,
  2110. child;
  2111. if (parent) {
  2112. if (keepChildren && node.hasChildNodes()) {
  2113. while (child = node.firstChild) {
  2114. parent.insertBefore(child, node);
  2115. }
  2116. }
  2117. parent.removeChild(node);
  2118. }
  2119. return node;
  2120. },
  2121. /**
  2122. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2123. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2124. * @method getNextDomNode
  2125. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2126. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2127. * @example
  2128. * ```html
  2129. * <body>
  2130. * <div id="test">
  2131. * <span></span>
  2132. * </div>
  2133. * <i>xxx</i>
  2134. * </body>
  2135. * <script>
  2136. *
  2137. * //output: i节点
  2138. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2139. *
  2140. * </script>
  2141. * ```
  2142. * @example
  2143. * ```html
  2144. * <body>
  2145. * <div>
  2146. * <span></span>
  2147. * <i id="test">xxx</i>
  2148. * </div>
  2149. * <b>xxx</b>
  2150. * </body>
  2151. * <script>
  2152. *
  2153. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2154. * //output: b节点
  2155. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2156. *
  2157. * </script>
  2158. * ```
  2159. */
  2160. /**
  2161. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2162. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2163. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2164. * @method getNextDomNode
  2165. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2166. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2167. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2168. * @see UE.dom.domUtils.getNextDomNode(Node)
  2169. */
  2170. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2171. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2172. },
  2173. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2174. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2175. },
  2176. /**
  2177. * 检测节点node是否属是UEditor定义的bookmark节点
  2178. * @method isBookmarkNode
  2179. * @private
  2180. * @param { Node } node 需要检测的节点对象
  2181. * @return { Boolean } 是否是bookmark节点
  2182. * @example
  2183. * ```html
  2184. * <span id="_baidu_bookmark_1"></span>
  2185. * <script>
  2186. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2187. * //output: true
  2188. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2189. * </script>
  2190. * ```
  2191. */
  2192. isBookmarkNode:function (node) {
  2193. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2194. },
  2195. /**
  2196. * 获取节点node所属的window对象
  2197. * @method getWindow
  2198. * @param { Node } node 节点对象
  2199. * @return { Window } 当前节点所属的window对象
  2200. * @example
  2201. * ```javascript
  2202. * //output: true
  2203. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2204. * ```
  2205. */
  2206. getWindow:function (node) {
  2207. var doc = node.ownerDocument || node;
  2208. return doc.defaultView || doc.parentWindow;
  2209. },
  2210. /**
  2211. * 获取离nodeA与nodeB最近的公共的祖先节点
  2212. * @method getCommonAncestor
  2213. * @param { Node } nodeA 第一个节点
  2214. * @param { Node } nodeB 第二个节点
  2215. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2216. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2217. * @example
  2218. * ```javascript
  2219. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2220. * //output: true
  2221. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2222. * ```
  2223. */
  2224. getCommonAncestor:function (nodeA, nodeB) {
  2225. if (nodeA === nodeB)
  2226. return nodeA;
  2227. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2228. while (parent = parent.parentNode) {
  2229. if (parent === nodeB) {
  2230. return parent;
  2231. }
  2232. parentsA.push(parent);
  2233. }
  2234. parent = nodeB;
  2235. while (parent = parent.parentNode) {
  2236. if (parent === nodeA)
  2237. return parent;
  2238. parentsB.push(parent);
  2239. }
  2240. parentsA.reverse();
  2241. parentsB.reverse();
  2242. while (i++, parentsA[i] === parentsB[i]) {
  2243. }
  2244. return i == 0 ? null : parentsA[i - 1];
  2245. },
  2246. /**
  2247. * 清除node节点左右连续为空的兄弟inline节点
  2248. * @method clearEmptySibling
  2249. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2250. * 则这些兄弟节点将被删除
  2251. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2252. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2253. * @example
  2254. * ```html
  2255. * <body>
  2256. * <div></div>
  2257. * <span id="test"></span>
  2258. * <i></i>
  2259. * <b></b>
  2260. * <em>xxx</em>
  2261. * <span></span>
  2262. * </body>
  2263. * <script>
  2264. *
  2265. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2266. *
  2267. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2268. * console.log( document.body.innerHTML );
  2269. *
  2270. * </script>
  2271. * ```
  2272. */
  2273. /**
  2274. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2275. * 则忽略对右边兄弟节点的操作。
  2276. * @method clearEmptySibling
  2277. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2278. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2279. * 则这些兄弟节点将被删除
  2280. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2281. */
  2282. /**
  2283. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2284. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2285. * @method clearEmptySibling
  2286. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2287. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2288. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2289. * 则这些兄弟节点将被删除
  2290. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2291. */
  2292. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2293. function clear(next, dir) {
  2294. var tmpNode;
  2295. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2296. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2297. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2298. tmpNode = next[dir];
  2299. domUtils.remove(next);
  2300. next = tmpNode;
  2301. }
  2302. }
  2303. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2304. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2305. },
  2306. /**
  2307. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2308. * @method split
  2309. * @param { Node } textNode 需要拆分的文本节点对象
  2310. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2311. * @return { Node } 拆分后形成的新节点
  2312. * @example
  2313. * ```html
  2314. * <div id="test">abcdef</div>
  2315. * <script>
  2316. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2317. * //output: def
  2318. * console.log( newNode.nodeValue );
  2319. * </script>
  2320. * ```
  2321. */
  2322. split:function (node, offset) {
  2323. var doc = node.ownerDocument;
  2324. if (browser.ie && offset == node.nodeValue.length) {
  2325. var next = doc.createTextNode('');
  2326. return domUtils.insertAfter(node, next);
  2327. }
  2328. var retval = node.splitText(offset);
  2329. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2330. if (browser.ie8) {
  2331. var tmpNode = doc.createTextNode('');
  2332. domUtils.insertAfter(retval, tmpNode);
  2333. domUtils.remove(tmpNode);
  2334. }
  2335. return retval;
  2336. },
  2337. /**
  2338. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2339. * @method isWhitespace
  2340. * @param { Node } node 需要检测的节点对象
  2341. * @return { Boolean } 检测的节点是否为空
  2342. * @example
  2343. * ```html
  2344. * <div id="test">
  2345. *
  2346. * </div>
  2347. * <script>
  2348. * //output: true
  2349. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2350. * </script>
  2351. * ```
  2352. */
  2353. isWhitespace:function (node) {
  2354. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2355. },
  2356. /**
  2357. * 获取元素element相对于viewport的位置坐标
  2358. * @method getXY
  2359. * @param { Node } element 需要计算位置的节点对象
  2360. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2361. * y代表垂直偏移距离。
  2362. *
  2363. * @example
  2364. * ```javascript
  2365. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2366. * //output: test的坐标为: 12, 24
  2367. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2368. * ```
  2369. */
  2370. getXY:function (element) {
  2371. var x = 0, y = 0;
  2372. while (element.offsetParent) {
  2373. y += element.offsetTop;
  2374. x += element.offsetLeft;
  2375. element = element.offsetParent;
  2376. }
  2377. return { 'x':x, 'y':y};
  2378. },
  2379. /**
  2380. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2381. * @method on
  2382. * @param { Node } element 需要绑定事件的节点对象
  2383. * @param { String } type 绑定的事件类型
  2384. * @param { Function } handler 事件处理器
  2385. * @example
  2386. * ```javascript
  2387. * UE.dom.domUtils.on(document.body,"click",function(e){
  2388. * //e为事件对象,this为被点击元素对戏那个
  2389. * });
  2390. * ```
  2391. */
  2392. /**
  2393. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2394. * @method on
  2395. * @param { Node } element 需要绑定事件的节点对象
  2396. * @param { Array } type 绑定的事件类型数组
  2397. * @param { Function } handler 事件处理器
  2398. * @example
  2399. * ```javascript
  2400. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2401. * //evt为事件对象,this为被点击元素对象
  2402. * });
  2403. * ```
  2404. */
  2405. on:function (element, type, handler) {
  2406. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2407. k = types.length;
  2408. if (k) while (k--) {
  2409. type = types[k];
  2410. if (element.addEventListener) {
  2411. element.addEventListener(type, handler, false);
  2412. } else {
  2413. if (!handler._d) {
  2414. handler._d = {
  2415. els : []
  2416. };
  2417. }
  2418. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2419. if (!handler._d[key] || index == -1) {
  2420. if(index == -1){
  2421. handler._d.els.push(element);
  2422. }
  2423. if(!handler._d[key]){
  2424. handler._d[key] = function (evt) {
  2425. return handler.call(evt.srcElement, evt || window.event);
  2426. };
  2427. }
  2428. element.attachEvent('on' + type, handler._d[key]);
  2429. }
  2430. }
  2431. }
  2432. element = null;
  2433. },
  2434. /**
  2435. * 解除DOM事件绑定
  2436. * @method un
  2437. * @param { Node } element 需要解除事件绑定的节点对象
  2438. * @param { String } type 需要接触绑定的事件类型
  2439. * @param { Function } handler 对应的事件处理器
  2440. * @example
  2441. * ```javascript
  2442. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2443. * //evt为事件对象,this为被点击元素对象
  2444. * });
  2445. * ```
  2446. */
  2447. /**
  2448. * 解除DOM事件绑定
  2449. * @method un
  2450. * @param { Node } element 需要解除事件绑定的节点对象
  2451. * @param { Array } type 需要接触绑定的事件类型数组
  2452. * @param { Function } handler 对应的事件处理器
  2453. * @example
  2454. * ```javascript
  2455. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2456. * //evt为事件对象,this为被点击元素对象
  2457. * });
  2458. * ```
  2459. */
  2460. un:function (element, type, handler) {
  2461. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2462. k = types.length;
  2463. if (k) while (k--) {
  2464. type = types[k];
  2465. if (element.removeEventListener) {
  2466. element.removeEventListener(type, handler, false);
  2467. } else {
  2468. var key = type + handler.toString();
  2469. try{
  2470. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2471. }catch(e){}
  2472. if (handler._d && handler._d[key]) {
  2473. var index = utils.indexOf(handler._d.els,element);
  2474. if(index!=-1){
  2475. handler._d.els.splice(index,1);
  2476. }
  2477. handler._d.els.length == 0 && delete handler._d[key];
  2478. }
  2479. }
  2480. }
  2481. },
  2482. /**
  2483. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2484. * @method isSameElement
  2485. * @param { Node } nodeA 需要比较的节点
  2486. * @param { Node } nodeB 需要比较的节点
  2487. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2488. * @example
  2489. * ```html
  2490. * <span style="font-size:12px">ssss</span>
  2491. * <span style="font-size:12px">bbbbb</span>
  2492. * <span style="font-size:13px">ssss</span>
  2493. * <span style="font-size:14px">bbbbb</span>
  2494. *
  2495. * <script>
  2496. *
  2497. * var nodes = document.getElementsByTagName( "span" );
  2498. *
  2499. * //output: true
  2500. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2501. *
  2502. * //output: false
  2503. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2504. *
  2505. * </script>
  2506. * ```
  2507. */
  2508. isSameElement:function (nodeA, nodeB) {
  2509. if (nodeA.tagName != nodeB.tagName) {
  2510. return false;
  2511. }
  2512. var thisAttrs = nodeA.attributes,
  2513. otherAttrs = nodeB.attributes;
  2514. if (!ie && thisAttrs.length != otherAttrs.length) {
  2515. return false;
  2516. }
  2517. var attrA, attrB, al = 0, bl = 0;
  2518. for (var i = 0; attrA = thisAttrs[i++];) {
  2519. if (attrA.nodeName == 'style') {
  2520. if (attrA.specified) {
  2521. al++;
  2522. }
  2523. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2524. continue;
  2525. } else {
  2526. return false;
  2527. }
  2528. }
  2529. if (ie) {
  2530. if (attrA.specified) {
  2531. al++;
  2532. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2533. } else {
  2534. continue;
  2535. }
  2536. } else {
  2537. attrB = nodeB.attributes[attrA.nodeName];
  2538. }
  2539. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2540. return false;
  2541. }
  2542. }
  2543. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2544. if (ie) {
  2545. for (i = 0; attrB = otherAttrs[i++];) {
  2546. if (attrB.specified) {
  2547. bl++;
  2548. }
  2549. }
  2550. if (al != bl) {
  2551. return false;
  2552. }
  2553. }
  2554. return true;
  2555. },
  2556. /**
  2557. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2558. * @method isSameStyle
  2559. * @param { Node } nodeA 需要比较的节点
  2560. * @param { Node } nodeB 需要比较的节点
  2561. * @return { Boolean } 两个节点是否具有相同的style属性值
  2562. * @example
  2563. * ```html
  2564. * <span style="font-size:12px">ssss</span>
  2565. * <span style="font-size:12px">bbbbb</span>
  2566. * <span style="font-size:13px">ssss</span>
  2567. * <span style="font-size:14px">bbbbb</span>
  2568. *
  2569. * <script>
  2570. *
  2571. * var nodes = document.getElementsByTagName( "span" );
  2572. *
  2573. * //output: true
  2574. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2575. *
  2576. * //output: false
  2577. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2578. *
  2579. * </script>
  2580. * ```
  2581. */
  2582. isSameStyle:function (nodeA, nodeB) {
  2583. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2584. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2585. if (browser.opera) {
  2586. styleA = nodeA.style;
  2587. styleB = nodeB.style;
  2588. if (styleA.length != styleB.length)
  2589. return false;
  2590. for (var p in styleA) {
  2591. if (/^(\d+|csstext)$/i.test(p)) {
  2592. continue;
  2593. }
  2594. if (styleA[p] != styleB[p]) {
  2595. return false;
  2596. }
  2597. }
  2598. return true;
  2599. }
  2600. if (!styleA || !styleB) {
  2601. return styleA == styleB;
  2602. }
  2603. styleA = styleA.split(';');
  2604. styleB = styleB.split(';');
  2605. if (styleA.length != styleB.length) {
  2606. return false;
  2607. }
  2608. for (var i = 0, ci; ci = styleA[i++];) {
  2609. if (utils.indexOf(styleB, ci) == -1) {
  2610. return false;
  2611. }
  2612. }
  2613. return true;
  2614. },
  2615. /**
  2616. * 检查节点node是否为block元素
  2617. * @method isBlockElm
  2618. * @param { Node } node 需要检测的节点对象
  2619. * @return { Boolean } 是否是block元素节点
  2620. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2621. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2622. * @example
  2623. * ```html
  2624. * <span id="test1" style="display: block"></span>
  2625. * <span id="test2"></span>
  2626. * <div id="test3" style="display: inline"></div>
  2627. *
  2628. * <script>
  2629. *
  2630. * //output: true
  2631. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2632. *
  2633. * //output: false
  2634. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2635. *
  2636. * //output: true
  2637. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2638. *
  2639. * </script>
  2640. * ```
  2641. */
  2642. isBlockElm:function (node) {
  2643. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2644. },
  2645. /**
  2646. * 检测node节点是否为body节点
  2647. * @method isBody
  2648. * @param { Element } node 需要检测的dom元素
  2649. * @return { Boolean } 给定的元素是否是body元素
  2650. * @example
  2651. * ```javascript
  2652. * //output: true
  2653. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2654. * ```
  2655. */
  2656. isBody:function (node) {
  2657. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2658. },
  2659. /**
  2660. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2661. * 拆分形成的两个节点之间是node节点
  2662. * @method breakParent
  2663. * @param { Node } node 作为分界的节点对象
  2664. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2665. * @return { Node } 给定的node分界节点
  2666. * @example
  2667. * ```javascript
  2668. *
  2669. * var node = document.createElement("span"),
  2670. * wrapNode = document.createElement( "div" ),
  2671. * parent = document.createElement("p");
  2672. *
  2673. * parent.appendChild( node );
  2674. * wrapNode.appendChild( parent );
  2675. *
  2676. * //拆分前
  2677. * //output: <p><span></span></p>
  2678. * console.log( wrapNode.innerHTML );
  2679. *
  2680. *
  2681. * UE.dom.domUtils.breakParent( node, parent );
  2682. * //拆分后
  2683. * //output: <p></p><span></span><p></p>
  2684. * console.log( wrapNode.innerHTML );
  2685. *
  2686. * ```
  2687. */
  2688. breakParent:function (node, parent) {
  2689. var tmpNode,
  2690. parentClone = node,
  2691. clone = node,
  2692. leftNodes,
  2693. rightNodes;
  2694. do {
  2695. parentClone = parentClone.parentNode;
  2696. if (leftNodes) {
  2697. tmpNode = parentClone.cloneNode(false);
  2698. tmpNode.appendChild(leftNodes);
  2699. leftNodes = tmpNode;
  2700. tmpNode = parentClone.cloneNode(false);
  2701. tmpNode.appendChild(rightNodes);
  2702. rightNodes = tmpNode;
  2703. } else {
  2704. leftNodes = parentClone.cloneNode(false);
  2705. rightNodes = leftNodes.cloneNode(false);
  2706. }
  2707. while (tmpNode = clone.previousSibling) {
  2708. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2709. }
  2710. while (tmpNode = clone.nextSibling) {
  2711. rightNodes.appendChild(tmpNode);
  2712. }
  2713. clone = parentClone;
  2714. } while (parent !== parentClone);
  2715. tmpNode = parent.parentNode;
  2716. tmpNode.insertBefore(leftNodes, parent);
  2717. tmpNode.insertBefore(rightNodes, parent);
  2718. tmpNode.insertBefore(node, rightNodes);
  2719. domUtils.remove(parent);
  2720. return node;
  2721. },
  2722. /**
  2723. * 检查节点node是否是空inline节点
  2724. * @method isEmptyInlineElement
  2725. * @param { Node } node 需要检测的节点对象
  2726. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2727. * @example
  2728. * ```html
  2729. * <b><i></i></b> => 1
  2730. * <b><i></i><u></u></b> => 1
  2731. * <b></b> => 1
  2732. * <b>xx<i></i></b> => 0
  2733. * ```
  2734. */
  2735. isEmptyInlineElement:function (node) {
  2736. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2737. return 0;
  2738. }
  2739. node = node.firstChild;
  2740. while (node) {
  2741. //如果是创建的bookmark就跳过
  2742. if (domUtils.isBookmarkNode(node)) {
  2743. return 0;
  2744. }
  2745. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2746. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2747. ) {
  2748. return 0;
  2749. }
  2750. node = node.nextSibling;
  2751. }
  2752. return 1;
  2753. },
  2754. /**
  2755. * 删除node节点下首尾两端的空白文本子节点
  2756. * @method trimWhiteTextNode
  2757. * @param { Element } node 需要执行删除操作的元素对象
  2758. * @example
  2759. * ```javascript
  2760. * var node = document.createElement("div");
  2761. *
  2762. * node.appendChild( document.createTextNode( "" ) );
  2763. *
  2764. * node.appendChild( document.createElement("div") );
  2765. *
  2766. * node.appendChild( document.createTextNode( "" ) );
  2767. *
  2768. * //3
  2769. * console.log( node.childNodes.length );
  2770. *
  2771. * UE.dom.domUtils.trimWhiteTextNode( node );
  2772. *
  2773. * //1
  2774. * console.log( node.childNodes.length );
  2775. * ```
  2776. */
  2777. trimWhiteTextNode:function (node) {
  2778. function remove(dir) {
  2779. var child;
  2780. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2781. node.removeChild(child);
  2782. }
  2783. }
  2784. remove('firstChild');
  2785. remove('lastChild');
  2786. },
  2787. /**
  2788. * 合并node节点下相同的子节点
  2789. * @name mergeChild
  2790. * @desc
  2791. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2792. * @example
  2793. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2794. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2795. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2796. */
  2797. mergeChild:function (node, tagName, attrs) {
  2798. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2799. for (var i = 0, ci; ci = list[i++];) {
  2800. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2801. continue;
  2802. }
  2803. //span单独处理
  2804. if (ci.tagName.toLowerCase() == 'span') {
  2805. if (node === ci.parentNode) {
  2806. domUtils.trimWhiteTextNode(node);
  2807. if (node.childNodes.length == 1) {
  2808. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2809. domUtils.remove(ci, true);
  2810. continue;
  2811. }
  2812. }
  2813. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2814. if (attrs) {
  2815. var style = attrs.style;
  2816. if (style) {
  2817. style = style.split(';');
  2818. for (var j = 0, s; s = style[j++];) {
  2819. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2820. }
  2821. }
  2822. }
  2823. if (domUtils.isSameStyle(ci, node)) {
  2824. domUtils.remove(ci, true);
  2825. }
  2826. continue;
  2827. }
  2828. if (domUtils.isSameElement(node, ci)) {
  2829. domUtils.remove(ci, true);
  2830. }
  2831. }
  2832. },
  2833. /**
  2834. * 原生方法getElementsByTagName的封装
  2835. * @method getElementsByTagName
  2836. * @param { Node } node 目标节点对象
  2837. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2838. * @return { Array } 符合条件的节点集合
  2839. */
  2840. getElementsByTagName:function (node, name,filter) {
  2841. if(filter && utils.isString(filter)){
  2842. var className = filter;
  2843. filter = function(node){return domUtils.hasClass(node,className)}
  2844. }
  2845. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2846. var arr = [];
  2847. for(var n = 0,ni;ni=name[n++];){
  2848. var list = node.getElementsByTagName(ni);
  2849. for (var i = 0, ci; ci = list[i++];) {
  2850. if(!filter || filter(ci))
  2851. arr.push(ci);
  2852. }
  2853. }
  2854. return arr;
  2855. },
  2856. /**
  2857. * 将节点node提取到父节点上
  2858. * @method mergeToParent
  2859. * @param { Element } node 需要提取的元素对象
  2860. * @example
  2861. * ```html
  2862. * <div id="parent">
  2863. * <div id="sub">
  2864. * <span id="child"></span>
  2865. * </div>
  2866. * </div>
  2867. *
  2868. * <script>
  2869. *
  2870. * var child = document.getElementById( "child" );
  2871. *
  2872. * //output: sub
  2873. * console.log( child.parentNode.id );
  2874. *
  2875. * UE.dom.domUtils.mergeToParent( child );
  2876. *
  2877. * //output: parent
  2878. * console.log( child.parentNode.id );
  2879. *
  2880. * </script>
  2881. * ```
  2882. */
  2883. mergeToParent:function (node) {
  2884. var parent = node.parentNode;
  2885. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2886. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2887. domUtils.trimWhiteTextNode(parent);
  2888. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2889. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2890. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2891. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2892. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2893. parent = parent.parentNode;
  2894. continue;
  2895. } else {
  2896. parent.style.cssText += ";" + node.style.cssText;
  2897. //trace:952 a标签要保持下划线
  2898. if (parent.tagName == 'A') {
  2899. parent.style.textDecoration = 'underline';
  2900. }
  2901. }
  2902. }
  2903. if (parent.tagName != 'A') {
  2904. parent === node.parentNode && domUtils.remove(node, true);
  2905. break;
  2906. }
  2907. }
  2908. parent = parent.parentNode;
  2909. }
  2910. },
  2911. /**
  2912. * 合并节点node的左右兄弟节点
  2913. * @method mergeSibling
  2914. * @param { Element } node 需要合并的目标节点
  2915. * @example
  2916. * ```html
  2917. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2918. *
  2919. * <script>
  2920. * var demoNode = document.getElementById("test");
  2921. * UE.dom.domUtils.mergeSibling( demoNode );
  2922. * //output: xxxxoooxxxx
  2923. * console.log( demoNode.innerHTML );
  2924. * </script>
  2925. * ```
  2926. */
  2927. /**
  2928. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2929. * @method mergeSibling
  2930. * @param { Element } node 需要合并的目标节点
  2931. * @param { Boolean } ignorePre 是否忽略合并左节点
  2932. * @example
  2933. * ```html
  2934. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2935. *
  2936. * <script>
  2937. * var demoNode = document.getElementById("test");
  2938. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2939. * //output: oooxxxx
  2940. * console.log( demoNode.innerHTML );
  2941. * </script>
  2942. * ```
  2943. */
  2944. /**
  2945. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2946. * @method mergeSibling
  2947. * @param { Element } node 需要合并的目标节点
  2948. * @param { Boolean } ignorePre 是否忽略合并左节点
  2949. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2950. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2951. * @example
  2952. * ```html
  2953. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2954. *
  2955. * <script>
  2956. * var demoNode = document.getElementById("test");
  2957. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2958. * //output: xxxxooo
  2959. * console.log( demoNode.innerHTML );
  2960. * </script>
  2961. * ```
  2962. */
  2963. mergeSibling:function (node, ignorePre, ignoreNext) {
  2964. function merge(rtl, start, node) {
  2965. var next;
  2966. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2967. while (next.firstChild) {
  2968. if (start == 'firstChild') {
  2969. node.insertBefore(next.lastChild, node.firstChild);
  2970. } else {
  2971. node.appendChild(next.firstChild);
  2972. }
  2973. }
  2974. domUtils.remove(next);
  2975. }
  2976. }
  2977. !ignorePre && merge('previousSibling', 'firstChild', node);
  2978. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2979. },
  2980. /**
  2981. * 设置节点node及其子节点不会被选中
  2982. * @method unSelectable
  2983. * @param { Element } node 需要执行操作的dom元素
  2984. * @remind 执行该操作后的节点, 将不能被鼠标选中
  2985. * @example
  2986. * ```javascript
  2987. * UE.dom.domUtils.unSelectable( document.body );
  2988. * ```
  2989. */
  2990. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  2991. //for ie9
  2992. node.onselectstart = function () {
  2993. return false;
  2994. };
  2995. node.onclick = node.onkeyup = node.onkeydown = function () {
  2996. return false;
  2997. };
  2998. node.unselectable = 'on';
  2999. node.setAttribute("unselectable", "on");
  3000. for (var i = 0, ci; ci = node.all[i++];) {
  3001. switch (ci.tagName.toLowerCase()) {
  3002. case 'iframe' :
  3003. case 'textarea' :
  3004. case 'input' :
  3005. case 'select' :
  3006. break;
  3007. default :
  3008. ci.unselectable = 'on';
  3009. node.setAttribute("unselectable", "on");
  3010. }
  3011. }
  3012. } : function (node) {
  3013. node.style.MozUserSelect =
  3014. node.style.webkitUserSelect =
  3015. node.style.msUserSelect =
  3016. node.style.KhtmlUserSelect = 'none';
  3017. },
  3018. /**
  3019. * 删除节点node上的指定属性名称的属性
  3020. * @method removeAttributes
  3021. * @param { Node } node 需要删除属性的节点对象
  3022. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3023. * @example
  3024. * ```html
  3025. * <div id="wrap">
  3026. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3027. * </div>
  3028. *
  3029. * <script>
  3030. *
  3031. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3032. *
  3033. * //output: <span style="font-size:14px;">xxxxx</span>
  3034. * console.log( document.getElementById("wrap").innerHTML );
  3035. *
  3036. * </script>
  3037. * ```
  3038. */
  3039. /**
  3040. * 删除节点node上的指定属性名称的属性
  3041. * @method removeAttributes
  3042. * @param { Node } node 需要删除属性的节点对象
  3043. * @param { Array } attrNames 需要删除的属性名数组
  3044. * @example
  3045. * ```html
  3046. * <div id="wrap">
  3047. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3048. * </div>
  3049. *
  3050. * <script>
  3051. *
  3052. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3053. *
  3054. * //output: <span style="font-size:14px;">xxxxx</span>
  3055. * console.log( document.getElementById("wrap").innerHTML );
  3056. *
  3057. * </script>
  3058. * ```
  3059. */
  3060. removeAttributes:function (node, attrNames) {
  3061. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3062. for (var i = 0, ci; ci = attrNames[i++];) {
  3063. ci = attrFix[ci] || ci;
  3064. switch (ci) {
  3065. case 'className':
  3066. node[ci] = '';
  3067. break;
  3068. case 'style':
  3069. node.style.cssText = '';
  3070. var val = node.getAttributeNode('style');
  3071. !browser.ie && val && node.removeAttributeNode(val);
  3072. }
  3073. node.removeAttribute(ci);
  3074. }
  3075. },
  3076. /**
  3077. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3078. * @method createElement
  3079. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3080. * @param { String } tagName 需要创建的元素的标签名
  3081. * @param { Object } attrs 新创建的元素的属性key-value集合
  3082. * @return { Element } 新创建的元素对象
  3083. * @example
  3084. * ```javascript
  3085. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3086. * id: 'test'
  3087. * } );
  3088. *
  3089. * //output: DIV
  3090. * console.log( ele.tagName );
  3091. *
  3092. * //output: test
  3093. * console.log( ele.id );
  3094. *
  3095. * ```
  3096. */
  3097. createElement:function (doc, tag, attrs) {
  3098. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3099. },
  3100. /**
  3101. * 为节点node添加属性attrs,attrs为属性键值对
  3102. * @method setAttributes
  3103. * @param { Element } node 需要设置属性的元素对象
  3104. * @param { Object } attrs 需要设置的属性名-值对
  3105. * @return { Element } 设置属性的元素对象
  3106. * @example
  3107. * ```html
  3108. * <span id="test"></span>
  3109. *
  3110. * <script>
  3111. *
  3112. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3113. * id: 'demo'
  3114. * } );
  3115. *
  3116. * //output: demo
  3117. * console.log( testNode.id );
  3118. *
  3119. * </script>
  3120. *
  3121. */
  3122. setAttributes:function (node, attrs) {
  3123. for (var attr in attrs) {
  3124. if(attrs.hasOwnProperty(attr)){
  3125. var value = attrs[attr];
  3126. switch (attr) {
  3127. case 'class':
  3128. //ie下要这样赋值,setAttribute不起作用
  3129. node.className = value;
  3130. break;
  3131. case 'style' :
  3132. node.style.cssText = node.style.cssText + ";" + value;
  3133. break;
  3134. case 'innerHTML':
  3135. node[attr] = value;
  3136. break;
  3137. case 'value':
  3138. node.value = value;
  3139. break;
  3140. default:
  3141. node.setAttribute(attrFix[attr] || attr, value);
  3142. }
  3143. }
  3144. }
  3145. return node;
  3146. },
  3147. /**
  3148. * 获取元素element经过计算后的样式值
  3149. * @method getComputedStyle
  3150. * @param { Element } element 需要获取样式的元素对象
  3151. * @param { String } styleName 需要获取的样式名
  3152. * @return { String } 获取到的样式值
  3153. * @example
  3154. * ```html
  3155. * <style type="text/css">
  3156. * #test {
  3157. * font-size: 15px;
  3158. * }
  3159. * </style>
  3160. *
  3161. * <span id="test"></span>
  3162. *
  3163. * <script>
  3164. * //output: 15px
  3165. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3166. * </script>
  3167. * ```
  3168. */
  3169. getComputedStyle:function (element, styleName) {
  3170. //一下的属性单独处理
  3171. var pros = 'width height top left';
  3172. if(pros.indexOf(styleName) > -1){
  3173. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3174. }
  3175. //忽略文本节点
  3176. if (element.nodeType == 3) {
  3177. element = element.parentNode;
  3178. }
  3179. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3180. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3181. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3182. var span = element.ownerDocument.createElement('span');
  3183. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3184. span.innerHTML = '.';
  3185. element.appendChild(span);
  3186. var result = span.offsetHeight;
  3187. element.removeChild(span);
  3188. span = null;
  3189. return result + 'px';
  3190. }
  3191. try {
  3192. var value = domUtils.getStyle(element, styleName) ||
  3193. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3194. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3195. } catch (e) {
  3196. return "";
  3197. }
  3198. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3199. },
  3200. /**
  3201. * 删除元素element指定的className
  3202. * @method removeClasses
  3203. * @param { Element } ele 需要删除class的元素节点
  3204. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3205. * @example
  3206. * ```html
  3207. * <span id="test" class="test1 test2 test3">xxx</span>
  3208. *
  3209. * <script>
  3210. *
  3211. * var testNode = document.getElementById( "test" );
  3212. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3213. *
  3214. * //output: test3
  3215. * console.log( testNode.className );
  3216. *
  3217. * </script>
  3218. * ```
  3219. */
  3220. /**
  3221. * 删除元素element指定的className
  3222. * @method removeClasses
  3223. * @param { Element } ele 需要删除class的元素节点
  3224. * @param { Array } classNames 需要删除的className数组
  3225. * @example
  3226. * ```html
  3227. * <span id="test" class="test1 test2 test3">xxx</span>
  3228. *
  3229. * <script>
  3230. *
  3231. * var testNode = document.getElementById( "test" );
  3232. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3233. *
  3234. * //output: test3
  3235. * console.log( testNode.className );
  3236. *
  3237. * </script>
  3238. * ```
  3239. */
  3240. removeClasses:function (elm, classNames) {
  3241. classNames = utils.isArray(classNames) ? classNames :
  3242. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3243. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3244. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3245. }
  3246. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3247. if(cls){
  3248. elm.className = cls;
  3249. }else{
  3250. domUtils.removeAttributes(elm,['class']);
  3251. }
  3252. },
  3253. /**
  3254. * 给元素element添加className
  3255. * @method addClass
  3256. * @param { Node } ele 需要增加className的元素
  3257. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3258. * @remind 相同的类名不会被重复添加
  3259. * @example
  3260. * ```html
  3261. * <span id="test" class="cls1 cls2"></span>
  3262. *
  3263. * <script>
  3264. * var testNode = document.getElementById("test");
  3265. *
  3266. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3267. *
  3268. * //output: cl1 cls2 cls3 cls4
  3269. * console.log( testNode.className );
  3270. *
  3271. * <script>
  3272. * ```
  3273. */
  3274. /**
  3275. * 给元素element添加className
  3276. * @method addClass
  3277. * @param { Node } ele 需要增加className的元素
  3278. * @param { Array } classNames 需要添加的className的数组
  3279. * @remind 相同的类名不会被重复添加
  3280. * @example
  3281. * ```html
  3282. * <span id="test" class="cls1 cls2"></span>
  3283. *
  3284. * <script>
  3285. * var testNode = document.getElementById("test");
  3286. *
  3287. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3288. *
  3289. * //output: cl1 cls2 cls3 cls4
  3290. * console.log( testNode.className );
  3291. *
  3292. * <script>
  3293. * ```
  3294. */
  3295. addClass:function (elm, classNames) {
  3296. if(!elm)return;
  3297. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3298. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3299. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3300. cls += ' ' + ci;
  3301. }
  3302. }
  3303. elm.className = utils.trim(cls);
  3304. },
  3305. /**
  3306. * 判断元素element是否包含给定的样式类名className
  3307. * @method hasClass
  3308. * @param { Node } ele 需要检测的元素
  3309. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3310. * @return { Boolean } 元素是否包含所有给定的className
  3311. * @example
  3312. * ```html
  3313. * <span id="test1" class="cls1 cls2"></span>
  3314. *
  3315. * <script>
  3316. * var test1 = document.getElementById("test1");
  3317. *
  3318. * //output: false
  3319. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3320. *
  3321. * //output: true
  3322. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3323. * </script>
  3324. * ```
  3325. */
  3326. /**
  3327. * 判断元素element是否包含给定的样式类名className
  3328. * @method hasClass
  3329. * @param { Node } ele 需要检测的元素
  3330. * @param { Array } classNames 需要检测的className数组
  3331. * @return { Boolean } 元素是否包含所有给定的className
  3332. * @example
  3333. * ```html
  3334. * <span id="test1" class="cls1 cls2"></span>
  3335. *
  3336. * <script>
  3337. * var test1 = document.getElementById("test1");
  3338. *
  3339. * //output: false
  3340. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3341. *
  3342. * //output: true
  3343. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3344. * </script>
  3345. * ```
  3346. */
  3347. hasClass:function (element, className) {
  3348. if(utils.isRegExp(className)){
  3349. return className.test(element.className)
  3350. }
  3351. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3352. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3353. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3354. return false;
  3355. }
  3356. }
  3357. return i - 1 == className.length;
  3358. },
  3359. /**
  3360. * 阻止事件默认行为
  3361. * @method preventDefault
  3362. * @param { Event } evt 需要阻止默认行为的事件对象
  3363. * @example
  3364. * ```javascript
  3365. * UE.dom.domUtils.preventDefault( evt );
  3366. * ```
  3367. */
  3368. preventDefault:function (evt) {
  3369. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3370. },
  3371. /**
  3372. * 删除元素element指定的样式
  3373. * @method removeStyle
  3374. * @param { Element } element 需要删除样式的元素
  3375. * @param { String } styleName 需要删除的样式名
  3376. * @example
  3377. * ```html
  3378. * <span id="test" style="color: red; background: blue;"></span>
  3379. *
  3380. * <script>
  3381. *
  3382. * var testNode = document.getElementById("test");
  3383. *
  3384. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3385. *
  3386. * //output: background: blue;
  3387. * console.log( testNode.style.cssText );
  3388. *
  3389. * </script>
  3390. * ```
  3391. */
  3392. removeStyle:function (element, name) {
  3393. if(browser.ie ){
  3394. //针对color先单独处理一下
  3395. if(name == 'color'){
  3396. name = '(^|;)' + name;
  3397. }
  3398. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3399. }else{
  3400. if (element.style.removeProperty) {
  3401. element.style.removeProperty (name);
  3402. }else {
  3403. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3404. }
  3405. }
  3406. if (!element.style.cssText) {
  3407. domUtils.removeAttributes(element, ['style']);
  3408. }
  3409. },
  3410. /**
  3411. * 获取元素element的style属性的指定值
  3412. * @method getStyle
  3413. * @param { Element } element 需要获取属性值的元素
  3414. * @param { String } styleName 需要获取的style的名称
  3415. * @warning 该方法仅获取元素style属性中所标明的值
  3416. * @return { String } 该元素包含指定的style属性值
  3417. * @example
  3418. * ```html
  3419. * <div id="test" style="color: red;"></div>
  3420. *
  3421. * <script>
  3422. *
  3423. * var testNode = document.getElementById( "test" );
  3424. *
  3425. * //output: red
  3426. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3427. *
  3428. * //output: ""
  3429. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3430. *
  3431. * </script>
  3432. * ```
  3433. */
  3434. getStyle:function (element, name) {
  3435. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3436. return utils.fixColor(name, value);
  3437. },
  3438. /**
  3439. * 为元素element设置样式属性值
  3440. * @method setStyle
  3441. * @param { Element } element 需要设置样式的元素
  3442. * @param { String } styleName 样式名
  3443. * @param { String } styleValue 样式值
  3444. * @example
  3445. * ```html
  3446. * <div id="test"></div>
  3447. *
  3448. * <script>
  3449. *
  3450. * var testNode = document.getElementById( "test" );
  3451. *
  3452. * //output: ""
  3453. * console.log( testNode.style.color );
  3454. *
  3455. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3456. * //output: "red"
  3457. * console.log( testNode.style.color );
  3458. *
  3459. * </script>
  3460. * ```
  3461. */
  3462. setStyle:function (element, name, value) {
  3463. element.style[utils.cssStyleToDomStyle(name)] = value;
  3464. if(!utils.trim(element.style.cssText)){
  3465. this.removeAttributes(element,'style')
  3466. }
  3467. },
  3468. /**
  3469. * 为元素element设置多个样式属性值
  3470. * @method setStyles
  3471. * @param { Element } element 需要设置样式的元素
  3472. * @param { Object } styles 样式名值对
  3473. * @example
  3474. * ```html
  3475. * <div id="test"></div>
  3476. *
  3477. * <script>
  3478. *
  3479. * var testNode = document.getElementById( "test" );
  3480. *
  3481. * //output: ""
  3482. * console.log( testNode.style.color );
  3483. *
  3484. * UE.dom.domUtils.setStyles( testNode, {
  3485. * 'color': 'red'
  3486. * } );
  3487. * //output: "red"
  3488. * console.log( testNode.style.color );
  3489. *
  3490. * </script>
  3491. * ```
  3492. */
  3493. setStyles:function (element, styles) {
  3494. for (var name in styles) {
  3495. if (styles.hasOwnProperty(name)) {
  3496. domUtils.setStyle(element, name, styles[name]);
  3497. }
  3498. }
  3499. },
  3500. /**
  3501. * 删除_moz_dirty属性
  3502. * @private
  3503. * @method removeDirtyAttr
  3504. */
  3505. removeDirtyAttr:function (node) {
  3506. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3507. ci.removeAttribute('_moz_dirty');
  3508. }
  3509. node.removeAttribute('_moz_dirty');
  3510. },
  3511. /**
  3512. * 获取子节点的数量
  3513. * @method getChildCount
  3514. * @param { Element } node 需要检测的元素
  3515. * @return { Number } 给定的node元素的子节点数量
  3516. * @example
  3517. * ```html
  3518. * <div id="test">
  3519. * <span></span>
  3520. * </div>
  3521. *
  3522. * <script>
  3523. *
  3524. * //output: 3
  3525. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3526. *
  3527. * </script>
  3528. * ```
  3529. */
  3530. /**
  3531. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3532. * @method getChildCount
  3533. * @param { Element } node 需要检测的元素
  3534. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3535. * @return { Number } 符合过滤条件的node元素的子节点数量
  3536. * @example
  3537. * ```html
  3538. * <div id="test">
  3539. * <span></span>
  3540. * </div>
  3541. *
  3542. * <script>
  3543. *
  3544. * //output: 1
  3545. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3546. *
  3547. * return node.nodeType === 1;
  3548. *
  3549. * } ) );
  3550. *
  3551. * </script>
  3552. * ```
  3553. */
  3554. getChildCount:function (node, fn) {
  3555. var count = 0, first = node.firstChild;
  3556. fn = fn || function () {
  3557. return 1;
  3558. };
  3559. while (first) {
  3560. if (fn(first)) {
  3561. count++;
  3562. }
  3563. first = first.nextSibling;
  3564. }
  3565. return count;
  3566. },
  3567. /**
  3568. * 判断给定节点是否为空节点
  3569. * @method isEmptyNode
  3570. * @param { Node } node 需要检测的节点对象
  3571. * @return { Boolean } 节点是否为空
  3572. * @example
  3573. * ```javascript
  3574. * UE.dom.domUtils.isEmptyNode( document.body );
  3575. * ```
  3576. */
  3577. isEmptyNode:function (node) {
  3578. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3579. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3580. }) == 0
  3581. },
  3582. clearSelectedArr:function (nodes) {
  3583. var node;
  3584. while (node = nodes.pop()) {
  3585. domUtils.removeAttributes(node, ['class']);
  3586. }
  3587. },
  3588. /**
  3589. * 将显示区域滚动到指定节点的位置
  3590. * @method scrollToView
  3591. * @param {Node} node 节点
  3592. * @param {window} win window对象
  3593. * @param {Number} offsetTop 距离上方的偏移量
  3594. */
  3595. scrollToView:function (node, win, offsetTop) {
  3596. var getViewPaneSize = function () {
  3597. var doc = win.document,
  3598. mode = doc.compatMode == 'CSS1Compat';
  3599. return {
  3600. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3601. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3602. };
  3603. },
  3604. getScrollPosition = function (win) {
  3605. if ('pageXOffset' in win) {
  3606. return {
  3607. x:win.pageXOffset || 0,
  3608. y:win.pageYOffset || 0
  3609. };
  3610. }
  3611. else {
  3612. var doc = win.document;
  3613. return {
  3614. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3615. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3616. };
  3617. }
  3618. };
  3619. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3620. offset += (node.offsetHeight || 0);
  3621. var elementPosition = domUtils.getXY(node);
  3622. offset += elementPosition.y;
  3623. var currentScroll = getScrollPosition(win).y;
  3624. // offset += 50;
  3625. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3626. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3627. }
  3628. },
  3629. /**
  3630. * 判断给定节点是否为br
  3631. * @method isBr
  3632. * @param { Node } node 需要判断的节点对象
  3633. * @return { Boolean } 给定的节点是否是br节点
  3634. */
  3635. isBr:function (node) {
  3636. return node.nodeType == 1 && node.tagName == 'BR';
  3637. },
  3638. /**
  3639. * 判断给定的节点是否是一个“填充”节点
  3640. * @private
  3641. * @method isFillChar
  3642. * @param { Node } node 需要判断的节点
  3643. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3644. * @returns { Boolean } 节点是否是填充节点
  3645. */
  3646. isFillChar:function (node,isInStart) {
  3647. if(node.nodeType != 3)
  3648. return false;
  3649. var text = node.nodeValue;
  3650. if(isInStart){
  3651. return new RegExp('^' + domUtils.fillChar).test(text)
  3652. }
  3653. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3654. },
  3655. isStartInblock:function (range) {
  3656. var tmpRange = range.cloneRange(),
  3657. flag = 0,
  3658. start = tmpRange.startContainer,
  3659. tmp;
  3660. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3661. start = start.childNodes[tmpRange.startOffset];
  3662. var pre = start.previousSibling;
  3663. while(pre && domUtils.isFillChar(pre)){
  3664. start = pre;
  3665. pre = pre.previousSibling;
  3666. }
  3667. }
  3668. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3669. tmpRange.setStartBefore(start);
  3670. start = tmpRange.startContainer;
  3671. }
  3672. while (start && domUtils.isFillChar(start)) {
  3673. tmp = start;
  3674. start = start.previousSibling
  3675. }
  3676. if (tmp) {
  3677. tmpRange.setStartBefore(tmp);
  3678. start = tmpRange.startContainer;
  3679. }
  3680. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3681. tmpRange.setStart(start, 0).collapse(true);
  3682. }
  3683. while (!tmpRange.startOffset) {
  3684. start = tmpRange.startContainer;
  3685. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3686. flag = 1;
  3687. break;
  3688. }
  3689. var pre = tmpRange.startContainer.previousSibling,
  3690. tmpNode;
  3691. if (!pre) {
  3692. tmpRange.setStartBefore(tmpRange.startContainer);
  3693. } else {
  3694. while (pre && domUtils.isFillChar(pre)) {
  3695. tmpNode = pre;
  3696. pre = pre.previousSibling;
  3697. }
  3698. if (tmpNode) {
  3699. tmpRange.setStartBefore(tmpNode);
  3700. } else {
  3701. tmpRange.setStartBefore(tmpRange.startContainer);
  3702. }
  3703. }
  3704. }
  3705. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3706. },
  3707. /**
  3708. * 判断给定的元素是否是一个空元素
  3709. * @method isEmptyBlock
  3710. * @param { Element } node 需要判断的元素
  3711. * @return { Boolean } 是否是空元素
  3712. * @example
  3713. * ```html
  3714. * <div id="test"></div>
  3715. *
  3716. * <script>
  3717. * //output: true
  3718. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3719. * </script>
  3720. * ```
  3721. */
  3722. /**
  3723. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3724. * @method isEmptyBlock
  3725. * @param { Element } node 需要判断的元素
  3726. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3727. * @return { Boolean } 是否是空元素
  3728. */
  3729. isEmptyBlock:function (node,reg) {
  3730. if(node.nodeType != 1)
  3731. return 0;
  3732. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  3733. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3734. return 0;
  3735. }
  3736. for (var n in dtd.$isNotEmpty) {
  3737. if (node.getElementsByTagName(n).length) {
  3738. return 0;
  3739. }
  3740. }
  3741. return 1;
  3742. },
  3743. /**
  3744. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3745. * @method setViewportOffset
  3746. * @param { Element } element 需要设置偏移量的元素
  3747. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3748. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3749. * offset.top的距离
  3750. * @example
  3751. * ```html
  3752. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3753. *
  3754. * <script>
  3755. *
  3756. * var testNode = document.getElementById("test");
  3757. *
  3758. * UE.dom.domUtils.setViewportOffset( testNode, {
  3759. * left: 200,
  3760. * top: 50
  3761. * } );
  3762. *
  3763. * //output: top: 300px; left: 100px; position: absolute;
  3764. * console.log( testNode.style.cssText );
  3765. *
  3766. * </script>
  3767. * ```
  3768. */
  3769. setViewportOffset:function (element, offset) {
  3770. var left = parseInt(element.style.left) | 0;
  3771. var top = parseInt(element.style.top) | 0;
  3772. var rect = element.getBoundingClientRect();
  3773. var offsetLeft = offset.left - rect.left;
  3774. var offsetTop = offset.top - rect.top;
  3775. if (offsetLeft) {
  3776. element.style.left = left + offsetLeft + 'px';
  3777. }
  3778. if (offsetTop) {
  3779. element.style.top = top + offsetTop + 'px';
  3780. }
  3781. },
  3782. /**
  3783. * 用“填充字符”填充节点
  3784. * @method fillNode
  3785. * @private
  3786. * @param { DomDocument } doc 填充的节点所在的docment对象
  3787. * @param { Node } node 需要填充的节点对象
  3788. * @example
  3789. * ```html
  3790. * <div id="test"></div>
  3791. *
  3792. * <script>
  3793. * var testNode = document.getElementById("test");
  3794. *
  3795. * //output: 0
  3796. * console.log( testNode.childNodes.length );
  3797. *
  3798. * UE.dom.domUtils.fillNode( document, testNode );
  3799. *
  3800. * //output: 1
  3801. * console.log( testNode.childNodes.length );
  3802. *
  3803. * </script>
  3804. * ```
  3805. */
  3806. fillNode:function (doc, node) {
  3807. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3808. node.innerHTML = '';
  3809. node.appendChild(tmpNode);
  3810. },
  3811. /**
  3812. * 把节点src的所有子节点追加到另一个节点tag上去
  3813. * @method moveChild
  3814. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3815. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3816. * @example
  3817. * ```html
  3818. * <div id="test1">
  3819. * <span></span>
  3820. * </div>
  3821. * <div id="test2">
  3822. * <div></div>
  3823. * </div>
  3824. *
  3825. * <script>
  3826. *
  3827. * var test1 = document.getElementById("test1"),
  3828. * test2 = document.getElementById("test2");
  3829. *
  3830. * UE.dom.domUtils.moveChild( test1, test2 );
  3831. *
  3832. * //output: ""(空字符串)
  3833. * console.log( test1.innerHTML );
  3834. *
  3835. * //output: "<div></div><span></span>"
  3836. * console.log( test2.innerHTML );
  3837. *
  3838. * </script>
  3839. * ```
  3840. */
  3841. /**
  3842. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3843. * @method moveChild
  3844. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3845. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3846. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3847. * @example
  3848. * ```html
  3849. * <div id="test1">
  3850. * <span></span>
  3851. * </div>
  3852. * <div id="test2">
  3853. * <div></div>
  3854. * </div>
  3855. *
  3856. * <script>
  3857. *
  3858. * var test1 = document.getElementById("test1"),
  3859. * test2 = document.getElementById("test2");
  3860. *
  3861. * UE.dom.domUtils.moveChild( test1, test2, true );
  3862. *
  3863. * //output: ""(空字符串)
  3864. * console.log( test1.innerHTML );
  3865. *
  3866. * //output: "<span></span><div></div>"
  3867. * console.log( test2.innerHTML );
  3868. *
  3869. * </script>
  3870. * ```
  3871. */
  3872. moveChild:function (src, tag, dir) {
  3873. while (src.firstChild) {
  3874. if (dir && tag.firstChild) {
  3875. tag.insertBefore(src.lastChild, tag.firstChild);
  3876. } else {
  3877. tag.appendChild(src.firstChild);
  3878. }
  3879. }
  3880. },
  3881. /**
  3882. * 判断节点的标签上是否不存在任何属性
  3883. * @method hasNoAttributes
  3884. * @private
  3885. * @param { Node } node 需要检测的节点对象
  3886. * @return { Boolean } 节点是否不包含任何属性
  3887. * @example
  3888. * ```html
  3889. * <div id="test"><span>xxxx</span></div>
  3890. *
  3891. * <script>
  3892. *
  3893. * //output: false
  3894. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3895. *
  3896. * //output: true
  3897. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3898. *
  3899. * </script>
  3900. * ```
  3901. */
  3902. hasNoAttributes:function (node) {
  3903. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3904. },
  3905. /**
  3906. * 检测节点是否是UEditor所使用的辅助节点
  3907. * @method isCustomeNode
  3908. * @private
  3909. * @param { Node } node 需要检测的节点
  3910. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3911. * @return { Boolean } 给定的节点是否是一个辅助节点
  3912. */
  3913. isCustomeNode:function (node) {
  3914. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3915. },
  3916. /**
  3917. * 检测节点的标签是否是给定的标签
  3918. * @method isTagNode
  3919. * @param { Node } node 需要检测的节点对象
  3920. * @param { String } tagName 标签
  3921. * @return { Boolean } 节点的标签是否是给定的标签
  3922. * @example
  3923. * ```html
  3924. * <div id="test"></div>
  3925. *
  3926. * <script>
  3927. *
  3928. * //output: true
  3929. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3930. *
  3931. * </script>
  3932. * ```
  3933. */
  3934. isTagNode:function (node, tagNames) {
  3935. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3936. },
  3937. /**
  3938. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3939. * @method filterNodeList
  3940. * @param { Array } nodeList 需要过滤的节点数组
  3941. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3942. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3943. * @example
  3944. * ```javascript
  3945. * var divNodes = document.getElementsByTagName("div");
  3946. * divNodes = [].slice.call( divNodes, 0 );
  3947. *
  3948. * //output: null
  3949. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3950. * return node.tagName.toLowerCase() !== 'div';
  3951. * } ) );
  3952. * ```
  3953. */
  3954. /**
  3955. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3956. * @method filterNodeList
  3957. * @param { Array } nodeList 需要过滤的节点数组
  3958. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3959. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3960. * @example
  3961. * ```javascript
  3962. * var divNodes = document.getElementsByTagName("div");
  3963. * divNodes = [].slice.call( divNodes, 0 );
  3964. *
  3965. * //output: null
  3966. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3967. * ```
  3968. */
  3969. /**
  3970. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3971. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3972. * @method filterNodeList
  3973. * @param { Array } nodeList 需要过滤的节点数组
  3974. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3975. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3976. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3977. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3978. * @example
  3979. * ```javascript
  3980. * var divNodes = document.getElementsByTagName("div");
  3981. * divNodes = [].slice.call( divNodes, 0 );
  3982. *
  3983. * //output: 3(假定有3个div)
  3984. * console.log( divNodes.length );
  3985. *
  3986. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3987. * return node.tagName.toLowerCase() === 'div';
  3988. * }, true );
  3989. *
  3990. * //output: 3
  3991. * console.log( nodes.length );
  3992. *
  3993. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3994. * return node.tagName.toLowerCase() === 'div';
  3995. * }, false );
  3996. *
  3997. * //output: div
  3998. * console.log( node.nodeName );
  3999. * ```
  4000. */
  4001. filterNodeList : function(nodelist,filter,forAll){
  4002. var results = [];
  4003. if(!utils .isFunction(filter)){
  4004. var str = filter;
  4005. filter = function(n){
  4006. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4007. };
  4008. }
  4009. utils.each(nodelist,function(n){
  4010. filter(n) && results.push(n)
  4011. });
  4012. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4013. },
  4014. /**
  4015. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4016. * @method isInNodeEndBoundary
  4017. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4018. * @param node 需要检测的节点对象
  4019. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4020. */
  4021. isInNodeEndBoundary : function (rng,node){
  4022. var start = rng.startContainer;
  4023. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4024. return 0;
  4025. }
  4026. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4027. return 0;
  4028. }
  4029. while(start !== node){
  4030. if(start.nextSibling){
  4031. return 0
  4032. };
  4033. start = start.parentNode;
  4034. }
  4035. return 1;
  4036. },
  4037. isBoundaryNode : function (node,dir){
  4038. var tmp;
  4039. while(!domUtils.isBody(node)){
  4040. tmp = node;
  4041. node = node.parentNode;
  4042. if(tmp !== node[dir]){
  4043. return false;
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. };
  4049. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4050. // core/Range.js
  4051. /**
  4052. * Range封装
  4053. * @file
  4054. * @module UE.dom
  4055. * @class Range
  4056. * @since 1.2.6.1
  4057. */
  4058. /**
  4059. * dom操作封装
  4060. * @unfile
  4061. * @module UE.dom
  4062. */
  4063. /**
  4064. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4065. * @unfile
  4066. * @module UE.dom
  4067. * @class Range
  4068. */
  4069. (function () {
  4070. var guid = 0,
  4071. fillChar = domUtils.fillChar,
  4072. fillData;
  4073. /**
  4074. * 更新range的collapse状态
  4075. * @param {Range} range range对象
  4076. */
  4077. function updateCollapse(range) {
  4078. range.collapsed =
  4079. range.startContainer && range.endContainer &&
  4080. range.startContainer === range.endContainer &&
  4081. range.startOffset == range.endOffset;
  4082. }
  4083. function selectOneNode(rng){
  4084. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4085. }
  4086. function setEndPoint(toStart, node, offset, range) {
  4087. //如果node是自闭合标签要处理
  4088. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4089. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4090. node = node.parentNode;
  4091. }
  4092. if (toStart) {
  4093. range.startContainer = node;
  4094. range.startOffset = offset;
  4095. if (!range.endContainer) {
  4096. range.collapse(true);
  4097. }
  4098. } else {
  4099. range.endContainer = node;
  4100. range.endOffset = offset;
  4101. if (!range.startContainer) {
  4102. range.collapse(false);
  4103. }
  4104. }
  4105. updateCollapse(range);
  4106. return range;
  4107. }
  4108. function execContentsAction(range, action) {
  4109. //调整边界
  4110. //range.includeBookmark();
  4111. var start = range.startContainer,
  4112. end = range.endContainer,
  4113. startOffset = range.startOffset,
  4114. endOffset = range.endOffset,
  4115. doc = range.document,
  4116. frag = doc.createDocumentFragment(),
  4117. tmpStart, tmpEnd;
  4118. if (start.nodeType == 1) {
  4119. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4120. }
  4121. if (end.nodeType == 1) {
  4122. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4123. }
  4124. if (start === end && start.nodeType == 3) {
  4125. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4126. //is not clone
  4127. if (action) {
  4128. start.deleteData(startOffset, endOffset - startOffset);
  4129. range.collapse(true);
  4130. }
  4131. return frag;
  4132. }
  4133. var current, currentLevel, clone = frag,
  4134. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4135. for (var i = 0; startParents[i] == endParents[i];) {
  4136. i++;
  4137. }
  4138. for (var j = i, si; si = startParents[j]; j++) {
  4139. current = si.nextSibling;
  4140. if (si == start) {
  4141. if (!tmpStart) {
  4142. if (range.startContainer.nodeType == 3) {
  4143. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4144. //is not clone
  4145. if (action) {
  4146. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4147. }
  4148. } else {
  4149. clone.appendChild(!action ? start.cloneNode(true) : start);
  4150. }
  4151. }
  4152. } else {
  4153. currentLevel = si.cloneNode(false);
  4154. clone.appendChild(currentLevel);
  4155. }
  4156. while (current) {
  4157. if (current === end || current === endParents[j]) {
  4158. break;
  4159. }
  4160. si = current.nextSibling;
  4161. clone.appendChild(!action ? current.cloneNode(true) : current);
  4162. current = si;
  4163. }
  4164. clone = currentLevel;
  4165. }
  4166. clone = frag;
  4167. if (!startParents[i]) {
  4168. clone.appendChild(startParents[i - 1].cloneNode(false));
  4169. clone = clone.firstChild;
  4170. }
  4171. for (var j = i, ei; ei = endParents[j]; j++) {
  4172. current = ei.previousSibling;
  4173. if (ei == end) {
  4174. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4175. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4176. //is not clone
  4177. if (action) {
  4178. end.deleteData(0, endOffset);
  4179. }
  4180. }
  4181. } else {
  4182. currentLevel = ei.cloneNode(false);
  4183. clone.appendChild(currentLevel);
  4184. }
  4185. //如果两端同级,右边第一次已经被开始做了
  4186. if (j != i || !startParents[i]) {
  4187. while (current) {
  4188. if (current === start) {
  4189. break;
  4190. }
  4191. ei = current.previousSibling;
  4192. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4193. current = ei;
  4194. }
  4195. }
  4196. clone = currentLevel;
  4197. }
  4198. if (action) {
  4199. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4200. }
  4201. tmpStart && domUtils.remove(tmpStart);
  4202. tmpEnd && domUtils.remove(tmpEnd);
  4203. return frag;
  4204. }
  4205. /**
  4206. * 创建一个跟document绑定的空的Range实例
  4207. * @constructor
  4208. * @param { Document } document 新建的选区所属的文档对象
  4209. */
  4210. /**
  4211. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4212. */
  4213. /**
  4214. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4215. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4216. */
  4217. /**
  4218. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4219. */
  4220. /**
  4221. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4222. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4223. */
  4224. /**
  4225. * @property { Boolean } collapsed 当前Range是否闭合
  4226. * @default true
  4227. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4228. */
  4229. /**
  4230. * @property { Document } document 当前Range所属的Document对象
  4231. * @remind 不同range的的document属性可以是不同的
  4232. */
  4233. var Range = dom.Range = function (document) {
  4234. var me = this;
  4235. me.startContainer =
  4236. me.startOffset =
  4237. me.endContainer =
  4238. me.endOffset = null;
  4239. me.document = document;
  4240. me.collapsed = true;
  4241. };
  4242. /**
  4243. * 删除fillData
  4244. * @param doc
  4245. * @param excludeNode
  4246. */
  4247. function removeFillData(doc, excludeNode) {
  4248. try {
  4249. if (fillData && domUtils.inDoc(fillData, doc)) {
  4250. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4251. var tmpNode = fillData.parentNode;
  4252. domUtils.remove(fillData);
  4253. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4254. //safari的contains有bug
  4255. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4256. ) {
  4257. fillData = tmpNode.parentNode;
  4258. domUtils.remove(tmpNode);
  4259. tmpNode = fillData;
  4260. }
  4261. } else {
  4262. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4263. }
  4264. }
  4265. } catch (e) {
  4266. }
  4267. }
  4268. /**
  4269. * @param node
  4270. * @param dir
  4271. */
  4272. function mergeSibling(node, dir) {
  4273. var tmpNode;
  4274. node = node[dir];
  4275. while (node && domUtils.isFillChar(node)) {
  4276. tmpNode = node[dir];
  4277. domUtils.remove(node);
  4278. node = tmpNode;
  4279. }
  4280. }
  4281. Range.prototype = {
  4282. /**
  4283. * 克隆选区的内容到一个DocumentFragment里
  4284. * @method cloneContents
  4285. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4286. * @example
  4287. * ```html
  4288. * <body>
  4289. * <!-- 中括号表示选区 -->
  4290. * <b>x<i>x[x</i>xx]x</b>
  4291. *
  4292. * <script>
  4293. * //range是已选中的选区
  4294. * var fragment = range.cloneContents(),
  4295. * node = document.createElement("div");
  4296. *
  4297. * node.appendChild( fragment );
  4298. *
  4299. * //output: <i>x</i>xx
  4300. * console.log( node.innerHTML );
  4301. *
  4302. * </script>
  4303. * </body>
  4304. * ```
  4305. */
  4306. cloneContents:function () {
  4307. return this.collapsed ? null : execContentsAction(this, 0);
  4308. },
  4309. /**
  4310. * 删除当前选区范围中的所有内容
  4311. * @method deleteContents
  4312. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4313. * @return { UE.dom.Range } 当前操作的Range对象
  4314. * @example
  4315. * ```html
  4316. * <body>
  4317. * <!-- 中括号表示选区 -->
  4318. * <b>x<i>x[x</i>xx]x</b>
  4319. *
  4320. * <script>
  4321. * //range是已选中的选区
  4322. * range.deleteContents();
  4323. *
  4324. * //竖线表示闭合后的选区位置
  4325. * //output: <b>x<i>x</i>|x</b>
  4326. * console.log( document.body.innerHTML );
  4327. *
  4328. * //此时, range的各项属性为
  4329. * //output: B
  4330. * console.log( range.startContainer.tagName );
  4331. * //output: 2
  4332. * console.log( range.startOffset );
  4333. * //output: B
  4334. * console.log( range.endContainer.tagName );
  4335. * //output: 2
  4336. * console.log( range.endOffset );
  4337. * //output: true
  4338. * console.log( range.collapsed );
  4339. *
  4340. * </script>
  4341. * </body>
  4342. * ```
  4343. */
  4344. deleteContents:function () {
  4345. var txt;
  4346. if (!this.collapsed) {
  4347. execContentsAction(this, 1);
  4348. }
  4349. if (browser.webkit) {
  4350. txt = this.startContainer;
  4351. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4352. this.setStartBefore(txt).collapse(true);
  4353. domUtils.remove(txt);
  4354. }
  4355. }
  4356. return this;
  4357. },
  4358. /**
  4359. * 将当前选区的内容提取到一个DocumentFragment里
  4360. * @method extractContents
  4361. * @remind 执行该操作后, 选区将变成闭合状态
  4362. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4363. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4364. * @example
  4365. * ```html
  4366. * <body>
  4367. * <!-- 中括号表示选区 -->
  4368. * <b>x<i>x[x</i>xx]x</b>
  4369. *
  4370. * <script>
  4371. * //range是已选中的选区
  4372. * var fragment = range.extractContents(),
  4373. * node = document.createElement( "div" );
  4374. *
  4375. * node.appendChild( fragment );
  4376. *
  4377. * //竖线表示闭合后的选区位置
  4378. *
  4379. * //output: <b>x<i>x</i>|x</b>
  4380. * console.log( document.body.innerHTML );
  4381. * //output: <i>x</i>xx
  4382. * console.log( node.innerHTML );
  4383. *
  4384. * //此时, range的各项属性为
  4385. * //output: B
  4386. * console.log( range.startContainer.tagName );
  4387. * //output: 2
  4388. * console.log( range.startOffset );
  4389. * //output: B
  4390. * console.log( range.endContainer.tagName );
  4391. * //output: 2
  4392. * console.log( range.endOffset );
  4393. * //output: true
  4394. * console.log( range.collapsed );
  4395. *
  4396. * </script>
  4397. * </body>
  4398. */
  4399. extractContents:function () {
  4400. return this.collapsed ? null : execContentsAction(this, 2);
  4401. },
  4402. /**
  4403. * 设置Range的开始容器节点和偏移量
  4404. * @method setStart
  4405. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4406. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4407. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4408. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4409. * 中的索引
  4410. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4411. * @param { int } offset 选区的开始位置偏移量
  4412. * @return { UE.dom.Range } 当前range对象
  4413. * @example
  4414. * ```html
  4415. * <!-- 选区 -->
  4416. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4417. *
  4418. * <script>
  4419. *
  4420. * //执行操作
  4421. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4422. *
  4423. * //此时, 选区变成了
  4424. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4425. *
  4426. * </script>
  4427. * ```
  4428. * @example
  4429. * ```html
  4430. * <!-- 选区 -->
  4431. * <b>xxx<img>[xx]x</b>
  4432. *
  4433. * <script>
  4434. *
  4435. * //执行操作
  4436. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4437. *
  4438. * //此时, 选区变成了
  4439. * //<b>xxx[<img>xx]x</b>
  4440. *
  4441. * </script>
  4442. * ```
  4443. */
  4444. setStart:function (node, offset) {
  4445. return setEndPoint(true, node, offset, this);
  4446. },
  4447. /**
  4448. * 设置Range的结束容器和偏移量
  4449. * @method setEnd
  4450. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4451. * @param { int } offset 结束边界的偏移量
  4452. * @see UE.dom.Range:setStart(Node,int)
  4453. * @return { UE.dom.Range } 当前range对象
  4454. */
  4455. setEnd:function (node, offset) {
  4456. return setEndPoint(false, node, offset, this);
  4457. },
  4458. /**
  4459. * 将Range开始位置设置到node节点之后
  4460. * @method setStartAfter
  4461. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4462. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4463. * @return { UE.dom.Range } 当前range对象
  4464. * @example
  4465. * ```html
  4466. * <!-- 选区示例 -->
  4467. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4468. *
  4469. * <script>
  4470. *
  4471. * //执行操作
  4472. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4473. *
  4474. * //结果选区
  4475. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4476. *
  4477. * </script>
  4478. * ```
  4479. */
  4480. setStartAfter:function (node) {
  4481. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4482. },
  4483. /**
  4484. * 将Range开始位置设置到node节点之前
  4485. * @method setStartBefore
  4486. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4487. * @param { Node } node 新的选区开始位置在该节点之前
  4488. * @see UE.dom.Range:setStartAfter(Node)
  4489. * @return { UE.dom.Range } 当前range对象
  4490. */
  4491. setStartBefore:function (node) {
  4492. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4493. },
  4494. /**
  4495. * 将Range结束位置设置到node节点之后
  4496. * @method setEndAfter
  4497. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4498. * @param { Node } node 目标节点
  4499. * @see UE.dom.Range:setStartAfter(Node)
  4500. * @return { UE.dom.Range } 当前range对象
  4501. * @example
  4502. * ```html
  4503. * <!-- 选区示例 -->
  4504. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4505. *
  4506. * <script>
  4507. *
  4508. * //执行操作
  4509. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4510. *
  4511. * //结果选区
  4512. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4513. *
  4514. * </script>
  4515. * ```
  4516. */
  4517. setEndAfter:function (node) {
  4518. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4519. },
  4520. /**
  4521. * 将Range结束位置设置到node节点之前
  4522. * @method setEndBefore
  4523. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4524. * @param { Node } node 目标节点
  4525. * @see UE.dom.Range:setEndAfter(Node)
  4526. * @return { UE.dom.Range } 当前range对象
  4527. */
  4528. setEndBefore:function (node) {
  4529. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4530. },
  4531. /**
  4532. * 设置Range的开始位置到node节点内的第一个子节点之前
  4533. * @method setStartAtFirst
  4534. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4535. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4536. * @param { Node } node 目标节点
  4537. * @see UE.dom.Range:setStartBefore(Node)
  4538. * @return { UE.dom.Range } 当前range对象
  4539. * @example
  4540. * ```html
  4541. * <!-- 选区示例 -->
  4542. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4543. *
  4544. * <script>
  4545. *
  4546. * //执行操作
  4547. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4548. *
  4549. * //结果选区
  4550. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4551. *
  4552. * </script>
  4553. * ```
  4554. */
  4555. setStartAtFirst:function (node) {
  4556. return this.setStart(node, 0);
  4557. },
  4558. /**
  4559. * 设置Range的开始位置到node节点内的最后一个节点之后
  4560. * @method setStartAtLast
  4561. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4562. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4563. * @param { Node } node 目标节点
  4564. * @see UE.dom.Range:setStartAtFirst(Node)
  4565. * @return { UE.dom.Range } 当前range对象
  4566. */
  4567. setStartAtLast:function (node) {
  4568. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4569. },
  4570. /**
  4571. * 设置Range的结束位置到node节点内的第一个节点之前
  4572. * @method setEndAtFirst
  4573. * @param { Node } node 目标节点
  4574. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4575. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4576. * @see UE.dom.Range:setStartAtFirst(Node)
  4577. * @return { UE.dom.Range } 当前range对象
  4578. */
  4579. setEndAtFirst:function (node) {
  4580. return this.setEnd(node, 0);
  4581. },
  4582. /**
  4583. * 设置Range的结束位置到node节点内的最后一个节点之后
  4584. * @method setEndAtLast
  4585. * @param { Node } node 目标节点
  4586. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4587. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4588. * @see UE.dom.Range:setStartAtFirst(Node)
  4589. * @return { UE.dom.Range } 当前range对象
  4590. */
  4591. setEndAtLast:function (node) {
  4592. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4593. },
  4594. /**
  4595. * 选中给定节点
  4596. * @method selectNode
  4597. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4598. * 而endOffset为startOffset+1
  4599. * @param { Node } node 需要选中的节点
  4600. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4601. * @example
  4602. * ```html
  4603. * <!-- 选区示例 -->
  4604. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4605. *
  4606. * <script>
  4607. *
  4608. * //执行操作
  4609. * range.selectNode( document.getElementsByTagName("i")[0] );
  4610. *
  4611. * //结果选区
  4612. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4613. *
  4614. * </script>
  4615. * ```
  4616. */
  4617. selectNode:function (node) {
  4618. return this.setStartBefore(node).setEndAfter(node);
  4619. },
  4620. /**
  4621. * 选中给定节点内部的所有节点
  4622. * @method selectNodeContents
  4623. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4624. * 而endOffset是该节点的子节点数。
  4625. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4626. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4627. * @example
  4628. * ```html
  4629. * <!-- 选区示例 -->
  4630. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4631. *
  4632. * <script>
  4633. *
  4634. * //执行操作
  4635. * range.selectNode( document.getElementsByTagName("b")[0] );
  4636. *
  4637. * //结果选区
  4638. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4639. *
  4640. * </script>
  4641. * ```
  4642. */
  4643. selectNodeContents:function (node) {
  4644. return this.setStart(node, 0).setEndAtLast(node);
  4645. },
  4646. /**
  4647. * clone当前Range对象
  4648. * @method cloneRange
  4649. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4650. * @return { UE.dom.Range } 当前range对象的一个副本
  4651. */
  4652. cloneRange:function () {
  4653. var me = this;
  4654. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4655. },
  4656. /**
  4657. * 向当前选区的结束处闭合选区
  4658. * @method collapse
  4659. * @return { UE.dom.Range } 当前range对象
  4660. * @example
  4661. * ```html
  4662. * <!-- 选区示例 -->
  4663. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4664. *
  4665. * <script>
  4666. *
  4667. * //执行操作
  4668. * range.collapse();
  4669. *
  4670. * //结果选区
  4671. * //“|”表示选区已闭合
  4672. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4673. *
  4674. * </script>
  4675. * ```
  4676. */
  4677. /**
  4678. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4679. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4680. * @method collapse
  4681. * @param { Boolean } toStart 是否向选区开始处闭合
  4682. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4683. * @see UE.dom.Range:collapse()
  4684. * @example
  4685. * ```html
  4686. * <!-- 选区示例 -->
  4687. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4688. *
  4689. * <script>
  4690. *
  4691. * //执行操作
  4692. * range.collapse( true );
  4693. *
  4694. * //结果选区
  4695. * //“|”表示选区已闭合
  4696. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4697. *
  4698. * </script>
  4699. * ```
  4700. */
  4701. collapse:function (toStart) {
  4702. var me = this;
  4703. if (toStart) {
  4704. me.endContainer = me.startContainer;
  4705. me.endOffset = me.startOffset;
  4706. } else {
  4707. me.startContainer = me.endContainer;
  4708. me.startOffset = me.endOffset;
  4709. }
  4710. me.collapsed = true;
  4711. return me;
  4712. },
  4713. /**
  4714. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4715. * @method shrinkBoundary
  4716. * @return { UE.dom.Range } 当前range对象
  4717. * @example
  4718. * ```html
  4719. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4720. * ```
  4721. *
  4722. * @example
  4723. * ```html
  4724. * <!-- 选区示例 -->
  4725. * <b>x[xx</b><i>]xxx</i>
  4726. *
  4727. * <script>
  4728. *
  4729. * //执行收缩
  4730. * range.shrinkBoundary();
  4731. *
  4732. * //结果选区
  4733. * //<b>x[xx]</b><i>xxx</i>
  4734. * </script>
  4735. * ```
  4736. *
  4737. * @example
  4738. * ```html
  4739. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4740. * ```
  4741. */
  4742. /**
  4743. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4744. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4745. * @method shrinkBoundary
  4746. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4747. * @return { UE.dom.Range } 当前range对象
  4748. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4749. */
  4750. shrinkBoundary:function (ignoreEnd) {
  4751. var me = this, child,
  4752. collapsed = me.collapsed;
  4753. function check(node){
  4754. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4755. }
  4756. while (me.startContainer.nodeType == 1 //是element
  4757. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4758. && check(child)) {
  4759. me.setStart(child, 0);
  4760. }
  4761. if (collapsed) {
  4762. return me.collapse(true);
  4763. }
  4764. if (!ignoreEnd) {
  4765. while (me.endContainer.nodeType == 1//是element
  4766. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4767. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4768. && check(child)) {
  4769. me.setEnd(child, child.childNodes.length);
  4770. }
  4771. }
  4772. return me;
  4773. },
  4774. /**
  4775. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4776. * @method getCommonAncestor
  4777. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4778. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4779. * @example
  4780. * ```html
  4781. * //选区示例
  4782. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4783. * <script>
  4784. *
  4785. * var node = range.getCommonAncestor();
  4786. *
  4787. * //公共祖先节点是: b节点
  4788. * //输出: B
  4789. * console.log(node.tagName);
  4790. *
  4791. * </script>
  4792. * ```
  4793. */
  4794. /**
  4795. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4796. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4797. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4798. * @method getCommonAncestor
  4799. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4800. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4801. * @see UE.dom.Range:getCommonAncestor()
  4802. * @example
  4803. * ```html
  4804. * <body>
  4805. *
  4806. * <!-- 选区示例 -->
  4807. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4808. *
  4809. * <script>
  4810. *
  4811. * var node = range.getCommonAncestor( false );
  4812. *
  4813. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4814. * //output: B
  4815. * console.log( node.tagName );
  4816. *
  4817. * </script>
  4818. *
  4819. * </body>
  4820. * ```
  4821. */
  4822. /**
  4823. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4824. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4825. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4826. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4827. * @method getCommonAncestor
  4828. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4829. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4830. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4831. * @see UE.dom.Range:getCommonAncestor()
  4832. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4833. * @example
  4834. * ```html
  4835. * <body>
  4836. *
  4837. * <!-- 选区示例 -->
  4838. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4839. *
  4840. * <script>
  4841. *
  4842. * var node = range.getCommonAncestor( true, false );
  4843. *
  4844. * //output: SPAN
  4845. * console.log( node.tagName );
  4846. *
  4847. * </script>
  4848. *
  4849. * </body>
  4850. * ```
  4851. */
  4852. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4853. var me = this,
  4854. start = me.startContainer,
  4855. end = me.endContainer;
  4856. if (start === end) {
  4857. if (includeSelf && selectOneNode(this)) {
  4858. start = start.childNodes[me.startOffset];
  4859. if(start.nodeType == 1)
  4860. return start;
  4861. }
  4862. //只有在上来就相等的情况下才会出现是文本的情况
  4863. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4864. }
  4865. return domUtils.getCommonAncestor(start, end);
  4866. },
  4867. /**
  4868. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4869. * @method trimBoundary
  4870. * @remind 该操作有可能会引起文本节点被切开
  4871. * @return { UE.dom.Range } 当前range对象
  4872. * @example
  4873. * ```html
  4874. *
  4875. * //选区示例
  4876. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4877. *
  4878. * <script>
  4879. * //未调整前, 选区的开始容器和结束都是文本节点
  4880. * //执行调整
  4881. * range.trimBoundary();
  4882. *
  4883. * //调整之后, 容器节点变成了i节点
  4884. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4885. * </script>
  4886. * ```
  4887. */
  4888. /**
  4889. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4890. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4891. * @method trimBoundary
  4892. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4893. * @return { UE.dom.Range } 当前range对象
  4894. * @example
  4895. * ```html
  4896. *
  4897. * //选区示例
  4898. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4899. *
  4900. * <script>
  4901. * //未调整前, 选区的开始容器和结束都是文本节点
  4902. * //执行调整
  4903. * range.trimBoundary( true );
  4904. *
  4905. * //调整之后, 开始容器节点变成了i节点
  4906. * //但是, 结束容器没有发生变化
  4907. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4908. * </script>
  4909. * ```
  4910. */
  4911. trimBoundary:function (ignoreEnd) {
  4912. this.txtToElmBoundary();
  4913. var start = this.startContainer,
  4914. offset = this.startOffset,
  4915. collapsed = this.collapsed,
  4916. end = this.endContainer;
  4917. if (start.nodeType == 3) {
  4918. if (offset == 0) {
  4919. this.setStartBefore(start);
  4920. } else {
  4921. if (offset >= start.nodeValue.length) {
  4922. this.setStartAfter(start);
  4923. } else {
  4924. var textNode = domUtils.split(start, offset);
  4925. //跟新结束边界
  4926. if (start === end) {
  4927. this.setEnd(textNode, this.endOffset - offset);
  4928. } else if (start.parentNode === end) {
  4929. this.endOffset += 1;
  4930. }
  4931. this.setStartBefore(textNode);
  4932. }
  4933. }
  4934. if (collapsed) {
  4935. return this.collapse(true);
  4936. }
  4937. }
  4938. if (!ignoreEnd) {
  4939. offset = this.endOffset;
  4940. end = this.endContainer;
  4941. if (end.nodeType == 3) {
  4942. if (offset == 0) {
  4943. this.setEndBefore(end);
  4944. } else {
  4945. offset < end.nodeValue.length && domUtils.split(end, offset);
  4946. this.setEndAfter(end);
  4947. }
  4948. }
  4949. }
  4950. return this;
  4951. },
  4952. /**
  4953. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4954. * @method txtToElmBoundary
  4955. * @remind 该操作不会修改dom节点
  4956. * @return { UE.dom.Range } 当前range对象
  4957. */
  4958. /**
  4959. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4960. * ignoreCollapsed 的值决定是否执行该调整
  4961. * @method txtToElmBoundary
  4962. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4963. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4964. * @return { UE.dom.Range } 当前range对象
  4965. */
  4966. txtToElmBoundary:function (ignoreCollapsed) {
  4967. function adjust(r, c) {
  4968. var container = r[c + 'Container'],
  4969. offset = r[c + 'Offset'];
  4970. if (container.nodeType == 3) {
  4971. if (!offset) {
  4972. r['set' + c.replace(/(\w)/, function (a) {
  4973. return a.toUpperCase();
  4974. }) + 'Before'](container);
  4975. } else if (offset >= container.nodeValue.length) {
  4976. r['set' + c.replace(/(\w)/, function (a) {
  4977. return a.toUpperCase();
  4978. }) + 'After' ](container);
  4979. }
  4980. }
  4981. }
  4982. if (ignoreCollapsed || !this.collapsed) {
  4983. adjust(this, 'start');
  4984. adjust(this, 'end');
  4985. }
  4986. return this;
  4987. },
  4988. /**
  4989. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  4990. * @method insertNode
  4991. * @param { Node } node 需要插入的节点
  4992. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  4993. * @return { UE.dom.Range } 当前range对象
  4994. */
  4995. insertNode:function (node) {
  4996. var first = node, length = 1;
  4997. if (node.nodeType == 11) {
  4998. first = node.firstChild;
  4999. length = node.childNodes.length;
  5000. }
  5001. this.trimBoundary(true);
  5002. var start = this.startContainer,
  5003. offset = this.startOffset;
  5004. var nextNode = start.childNodes[ offset ];
  5005. if (nextNode) {
  5006. start.insertBefore(node, nextNode);
  5007. } else {
  5008. start.appendChild(node);
  5009. }
  5010. if (first.parentNode === this.endContainer) {
  5011. this.endOffset = this.endOffset + length;
  5012. }
  5013. return this.setStartBefore(first);
  5014. },
  5015. /**
  5016. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5017. * @method setCursor
  5018. * @return { UE.dom.Range } 当前range对象
  5019. * @see UE.dom.Range:collapse()
  5020. */
  5021. /**
  5022. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5023. * @method setCursor
  5024. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5025. * 反之,则向开始容器方向闭合
  5026. * @return { UE.dom.Range } 当前range对象
  5027. * @see UE.dom.Range:collapse(Boolean)
  5028. */
  5029. setCursor:function (toEnd, noFillData) {
  5030. return this.collapse(!toEnd).select(noFillData);
  5031. },
  5032. /**
  5033. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5034. * @method createBookmark
  5035. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5036. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5037. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5038. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5039. * 返回的记录的类型为ID, 反之则为引用
  5040. */
  5041. createBookmark:function (serialize, same) {
  5042. var endNode,
  5043. startNode = this.document.createElement('span');
  5044. startNode.style.cssText = 'display:none;line-height:0px;';
  5045. startNode.appendChild(this.document.createTextNode('\u200D'));
  5046. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5047. if (!this.collapsed) {
  5048. endNode = startNode.cloneNode(true);
  5049. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5050. }
  5051. this.insertNode(startNode);
  5052. if (endNode) {
  5053. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5054. }
  5055. this.setStartAfter(startNode);
  5056. return {
  5057. start:serialize ? startNode.id : startNode,
  5058. end:endNode ? serialize ? endNode.id : endNode : null,
  5059. id:serialize
  5060. }
  5061. },
  5062. /**
  5063. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5064. * @method moveToBookmark
  5065. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5066. * @return { UE.dom.Range } 当前range对象
  5067. * @see UE.dom.Range:createBookmark(Boolean)
  5068. */
  5069. moveToBookmark:function (bookmark) {
  5070. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5071. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5072. this.setStartBefore(start);
  5073. domUtils.remove(start);
  5074. if (end) {
  5075. this.setEndBefore(end);
  5076. domUtils.remove(end);
  5077. } else {
  5078. this.collapse(true);
  5079. }
  5080. return this;
  5081. },
  5082. /**
  5083. * 调整range的边界,使其"放大"到最近的父节点
  5084. * @method enlarge
  5085. * @remind 会引起选区的变化
  5086. * @return { UE.dom.Range } 当前range对象
  5087. */
  5088. /**
  5089. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5090. * 要求扩大之后的父节点是block节点
  5091. * @method enlarge
  5092. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5093. * @return { UE.dom.Range } 当前range对象
  5094. */
  5095. enlarge:function (toBlock, stopFn) {
  5096. var isBody = domUtils.isBody,
  5097. pre, node, tmp = this.document.createTextNode('');
  5098. if (toBlock) {
  5099. node = this.startContainer;
  5100. if (node.nodeType == 1) {
  5101. if (node.childNodes[this.startOffset]) {
  5102. pre = node = node.childNodes[this.startOffset]
  5103. } else {
  5104. node.appendChild(tmp);
  5105. pre = node = tmp;
  5106. }
  5107. } else {
  5108. pre = node;
  5109. }
  5110. while (1) {
  5111. if (domUtils.isBlockElm(node)) {
  5112. node = pre;
  5113. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5114. node = pre;
  5115. }
  5116. this.setStartBefore(node);
  5117. break;
  5118. }
  5119. pre = node;
  5120. node = node.parentNode;
  5121. }
  5122. node = this.endContainer;
  5123. if (node.nodeType == 1) {
  5124. if (pre = node.childNodes[this.endOffset]) {
  5125. node.insertBefore(tmp, pre);
  5126. } else {
  5127. node.appendChild(tmp);
  5128. }
  5129. pre = node = tmp;
  5130. } else {
  5131. pre = node;
  5132. }
  5133. while (1) {
  5134. if (domUtils.isBlockElm(node)) {
  5135. node = pre;
  5136. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5137. node = pre;
  5138. }
  5139. this.setEndAfter(node);
  5140. break;
  5141. }
  5142. pre = node;
  5143. node = node.parentNode;
  5144. }
  5145. if (tmp.parentNode === this.endContainer) {
  5146. this.endOffset--;
  5147. }
  5148. domUtils.remove(tmp);
  5149. }
  5150. // 扩展边界到最大
  5151. if (!this.collapsed) {
  5152. while (this.startOffset == 0) {
  5153. if (stopFn && stopFn(this.startContainer)) {
  5154. break;
  5155. }
  5156. if (isBody(this.startContainer)) {
  5157. break;
  5158. }
  5159. this.setStartBefore(this.startContainer);
  5160. }
  5161. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5162. if (stopFn && stopFn(this.endContainer)) {
  5163. break;
  5164. }
  5165. if (isBody(this.endContainer)) {
  5166. break;
  5167. }
  5168. this.setEndAfter(this.endContainer);
  5169. }
  5170. }
  5171. return this;
  5172. },
  5173. enlargeToBlockElm:function(ignoreEnd){
  5174. while(!domUtils.isBlockElm(this.startContainer)){
  5175. this.setStartBefore(this.startContainer);
  5176. }
  5177. if(!ignoreEnd){
  5178. while(!domUtils.isBlockElm(this.endContainer)){
  5179. this.setEndAfter(this.endContainer);
  5180. }
  5181. }
  5182. return this;
  5183. },
  5184. /**
  5185. * 调整Range的边界,使其"缩小"到最合适的位置
  5186. * @method adjustmentBoundary
  5187. * @return { UE.dom.Range } 当前range对象
  5188. * @see UE.dom.Range:shrinkBoundary()
  5189. */
  5190. adjustmentBoundary:function () {
  5191. if (!this.collapsed) {
  5192. while (!domUtils.isBody(this.startContainer) &&
  5193. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5194. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5195. ) {
  5196. this.setStartAfter(this.startContainer);
  5197. }
  5198. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5199. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5200. ) {
  5201. this.setEndBefore(this.endContainer);
  5202. }
  5203. }
  5204. return this;
  5205. },
  5206. /**
  5207. * 给range选区中的内容添加给定的inline标签
  5208. * @method applyInlineStyle
  5209. * @param { String } tagName 需要添加的标签名
  5210. * @example
  5211. * ```html
  5212. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5213. * ```
  5214. */
  5215. /**
  5216. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5217. * @method applyInlineStyle
  5218. * @param { String } tagName 需要添加的标签名
  5219. * @param { Object } attrs 跟随新添加的标签的属性
  5220. * @return { UE.dom.Range } 当前选区
  5221. * @example
  5222. * ```html
  5223. * <p>xxxx[xxxx]x</p>
  5224. *
  5225. * ==>
  5226. *
  5227. * <!-- 执行操作 -->
  5228. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5229. *
  5230. * ==>
  5231. *
  5232. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5233. * ```
  5234. */
  5235. applyInlineStyle:function (tagName, attrs, list) {
  5236. if (this.collapsed)return this;
  5237. this.trimBoundary().enlarge(false,
  5238. function (node) {
  5239. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5240. }).adjustmentBoundary();
  5241. var bookmark = this.createBookmark(),
  5242. end = bookmark.end,
  5243. filterFn = function (node) {
  5244. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5245. },
  5246. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5247. node,
  5248. pre,
  5249. range = this.cloneRange();
  5250. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5251. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5252. range.setStartBefore(current);
  5253. node = current;
  5254. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5255. pre = node;
  5256. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5257. return dtd[tagName][parent.tagName];
  5258. });
  5259. }
  5260. var frag = range.setEndAfter(pre).extractContents(), elm;
  5261. if (list && list.length > 0) {
  5262. var level, top;
  5263. top = level = list[0].cloneNode(false);
  5264. for (var i = 1, ci; ci = list[i++];) {
  5265. level.appendChild(ci.cloneNode(false));
  5266. level = level.firstChild;
  5267. }
  5268. elm = level;
  5269. } else {
  5270. elm = range.document.createElement(tagName);
  5271. }
  5272. if (attrs) {
  5273. domUtils.setAttributes(elm, attrs);
  5274. }
  5275. elm.appendChild(frag);
  5276. range.insertNode(list ? top : elm);
  5277. //处理下滑线在a上的情况
  5278. var aNode;
  5279. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5280. domUtils.setAttributes(aNode, attrs);
  5281. domUtils.remove(elm, true);
  5282. elm = aNode;
  5283. } else {
  5284. domUtils.mergeSibling(elm);
  5285. domUtils.clearEmptySibling(elm);
  5286. }
  5287. //去除子节点相同的
  5288. domUtils.mergeChild(elm, attrs);
  5289. current = domUtils.getNextDomNode(elm, false, filterFn);
  5290. domUtils.mergeToParent(elm);
  5291. if (node === end) {
  5292. break;
  5293. }
  5294. } else {
  5295. current = domUtils.getNextDomNode(current, true, filterFn);
  5296. }
  5297. }
  5298. return this.moveToBookmark(bookmark);
  5299. },
  5300. /**
  5301. * 移除当前选区内指定的inline标签,但保留其中的内容
  5302. * @method removeInlineStyle
  5303. * @param { String } tagName 需要移除的标签名
  5304. * @return { UE.dom.Range } 当前的range对象
  5305. * @example
  5306. * ```html
  5307. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5308. * ```
  5309. */
  5310. /**
  5311. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5312. * @method removeInlineStyle
  5313. * @param { Array } tagNameArr 需要移除的标签名的数组
  5314. * @return { UE.dom.Range } 当前的range对象
  5315. * @see UE.dom.Range:removeInlineStyle(String)
  5316. */
  5317. removeInlineStyle:function (tagNames) {
  5318. if (this.collapsed)return this;
  5319. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5320. this.shrinkBoundary().adjustmentBoundary();
  5321. var start = this.startContainer, end = this.endContainer;
  5322. while (1) {
  5323. if (start.nodeType == 1) {
  5324. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5325. break;
  5326. }
  5327. if (start.tagName.toLowerCase() == 'body') {
  5328. start = null;
  5329. break;
  5330. }
  5331. }
  5332. start = start.parentNode;
  5333. }
  5334. while (1) {
  5335. if (end.nodeType == 1) {
  5336. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5337. break;
  5338. }
  5339. if (end.tagName.toLowerCase() == 'body') {
  5340. end = null;
  5341. break;
  5342. }
  5343. }
  5344. end = end.parentNode;
  5345. }
  5346. var bookmark = this.createBookmark(),
  5347. frag,
  5348. tmpRange;
  5349. if (start) {
  5350. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5351. frag = tmpRange.extractContents();
  5352. tmpRange.insertNode(frag);
  5353. domUtils.clearEmptySibling(start, true);
  5354. start.parentNode.insertBefore(bookmark.start, start);
  5355. }
  5356. if (end) {
  5357. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5358. frag = tmpRange.extractContents();
  5359. tmpRange.insertNode(frag);
  5360. domUtils.clearEmptySibling(end, false, true);
  5361. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5362. }
  5363. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5364. return node.nodeType == 1;
  5365. }), next;
  5366. while (current && current !== bookmark.end) {
  5367. next = domUtils.getNextDomNode(current, true, function (node) {
  5368. return node.nodeType == 1;
  5369. });
  5370. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5371. domUtils.remove(current, true);
  5372. }
  5373. current = next;
  5374. }
  5375. return this.moveToBookmark(bookmark);
  5376. },
  5377. /**
  5378. * 获取当前选中的自闭合的节点
  5379. * @method getClosedNode
  5380. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5381. */
  5382. getClosedNode:function () {
  5383. var node;
  5384. if (!this.collapsed) {
  5385. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5386. if (selectOneNode(range)) {
  5387. var child = range.startContainer.childNodes[range.startOffset];
  5388. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5389. node = child;
  5390. }
  5391. }
  5392. }
  5393. return node;
  5394. },
  5395. /**
  5396. * 在页面上高亮range所表示的选区
  5397. * @method select
  5398. * @return { UE.dom.Range } 返回当前Range对象
  5399. */
  5400. //这里不区分ie9以上,trace:3824
  5401. select:browser.ie ? function (noFillData, textRange) {
  5402. var nativeRange;
  5403. if (!this.collapsed)
  5404. this.shrinkBoundary();
  5405. var node = this.getClosedNode();
  5406. if (node && !textRange) {
  5407. try {
  5408. nativeRange = this.document.body.createControlRange();
  5409. nativeRange.addElement(node);
  5410. nativeRange.select();
  5411. } catch (e) {}
  5412. return this;
  5413. }
  5414. var bookmark = this.createBookmark(),
  5415. start = bookmark.start,
  5416. end;
  5417. nativeRange = this.document.body.createTextRange();
  5418. nativeRange.moveToElementText(start);
  5419. nativeRange.moveStart('character', 1);
  5420. if (!this.collapsed) {
  5421. var nativeRangeEnd = this.document.body.createTextRange();
  5422. end = bookmark.end;
  5423. nativeRangeEnd.moveToElementText(end);
  5424. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5425. } else {
  5426. if (!noFillData && this.startContainer.nodeType != 3) {
  5427. //使用<span>|x<span>固定住光标
  5428. var tmpText = this.document.createTextNode(fillChar),
  5429. tmp = this.document.createElement('span');
  5430. tmp.appendChild(this.document.createTextNode(fillChar));
  5431. start.parentNode.insertBefore(tmp, start);
  5432. start.parentNode.insertBefore(tmpText, start);
  5433. //当点b,i,u时,不能清除i上边的b
  5434. removeFillData(this.document, tmpText);
  5435. fillData = tmpText;
  5436. mergeSibling(tmp, 'previousSibling');
  5437. mergeSibling(start, 'nextSibling');
  5438. nativeRange.moveStart('character', -1);
  5439. nativeRange.collapse(true);
  5440. }
  5441. }
  5442. this.moveToBookmark(bookmark);
  5443. tmp && domUtils.remove(tmp);
  5444. //IE在隐藏状态下不支持range操作,catch一下
  5445. try {
  5446. nativeRange.select();
  5447. } catch (e) {
  5448. }
  5449. return this;
  5450. } : function (notInsertFillData) {
  5451. function checkOffset(rng){
  5452. function check(node,offset,dir){
  5453. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5454. rng[dir + 'Offset'] = node.nodeValue.length
  5455. }
  5456. }
  5457. check(rng.startContainer,rng.startOffset,'start');
  5458. check(rng.endContainer,rng.endOffset,'end');
  5459. }
  5460. var win = domUtils.getWindow(this.document),
  5461. sel = win.getSelection(),
  5462. txtNode;
  5463. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5464. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5465. browser.gecko ? this.document.body.focus() : win.focus();
  5466. if (sel) {
  5467. sel.removeAllRanges();
  5468. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5469. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5470. if (this.collapsed && !notInsertFillData) {
  5471. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5472. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5473. // var tmp = this.document.createTextNode('');
  5474. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5475. // }
  5476. //
  5477. //处理光标落在文本节点的情况
  5478. //处理以下的情况
  5479. //<b>|xxxx</b>
  5480. //<b>xxxx</b>|xxxx
  5481. //xxxx<b>|</b>
  5482. var start = this.startContainer,child = start;
  5483. if(start.nodeType == 1){
  5484. child = start.childNodes[this.startOffset];
  5485. }
  5486. if( !(start.nodeType == 3 && this.startOffset) &&
  5487. (child ?
  5488. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5489. :
  5490. (!start.lastChild || start.lastChild.nodeType != 3)
  5491. )
  5492. ){
  5493. txtNode = this.document.createTextNode(fillChar);
  5494. //跟着前边走
  5495. this.insertNode(txtNode);
  5496. removeFillData(this.document, txtNode);
  5497. mergeSibling(txtNode, 'previousSibling');
  5498. mergeSibling(txtNode, 'nextSibling');
  5499. fillData = txtNode;
  5500. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5501. }
  5502. }
  5503. var nativeRange = this.document.createRange();
  5504. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5505. var child = this.startContainer.childNodes[this.startOffset];
  5506. if(!child){
  5507. //往前靠拢
  5508. child = this.startContainer.lastChild;
  5509. if( child && domUtils.isBr(child)){
  5510. this.setStartBefore(child).collapse(true);
  5511. }
  5512. }else{
  5513. //向后靠拢
  5514. while(child && domUtils.isBlockElm(child)){
  5515. if(child.nodeType == 1 && child.childNodes[0]){
  5516. child = child.childNodes[0]
  5517. }else{
  5518. break;
  5519. }
  5520. }
  5521. child && this.setStartBefore(child).collapse(true)
  5522. }
  5523. }
  5524. //是createAddress最后一位算的不准,现在这里进行微调
  5525. checkOffset(this);
  5526. nativeRange.setStart(this.startContainer, this.startOffset);
  5527. nativeRange.setEnd(this.endContainer, this.endOffset);
  5528. sel.addRange(nativeRange);
  5529. }
  5530. return this;
  5531. },
  5532. /**
  5533. * 滚动到当前range开始的位置
  5534. * @method scrollToView
  5535. * @param { Window } win 当前range对象所属的window对象
  5536. * @return { UE.dom.Range } 当前Range对象
  5537. */
  5538. /**
  5539. * 滚动到距离当前range开始位置 offset 的位置处
  5540. * @method scrollToView
  5541. * @param { Window } win 当前range对象所属的window对象
  5542. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5543. * @return { UE.dom.Range } 当前Range对象
  5544. */
  5545. scrollToView:function (win, offset) {
  5546. win = win ? window : domUtils.getWindow(this.document);
  5547. var me = this,
  5548. span = me.document.createElement('span');
  5549. //trace:717
  5550. span.innerHTML = '&nbsp;';
  5551. me.cloneRange().insertNode(span);
  5552. domUtils.scrollToView(span, win, offset);
  5553. domUtils.remove(span);
  5554. return me;
  5555. },
  5556. /**
  5557. * 判断当前选区内容是否占位符
  5558. * @private
  5559. * @method inFillChar
  5560. * @return { Boolean } 如果是占位符返回true,否则返回false
  5561. */
  5562. inFillChar : function(){
  5563. var start = this.startContainer;
  5564. if(this.collapsed && start.nodeType == 3
  5565. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5566. ){
  5567. return true;
  5568. }
  5569. return false;
  5570. },
  5571. /**
  5572. * 保存
  5573. * @method createAddress
  5574. * @private
  5575. * @return { Boolean } 返回开始和结束的位置
  5576. * @example
  5577. * ```html
  5578. * <body>
  5579. * <p>
  5580. * aaaa
  5581. * <em>
  5582. * <!-- 选区开始 -->
  5583. * bbbb
  5584. * <!-- 选区结束 -->
  5585. * </em>
  5586. * </p>
  5587. *
  5588. * <script>
  5589. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5590. * console.log( range.createAddress() );
  5591. * </script>
  5592. * </body>
  5593. * ```
  5594. */
  5595. createAddress : function(ignoreEnd,ignoreTxt){
  5596. var addr = {},me = this;
  5597. function getAddress(isStart){
  5598. var node = isStart ? me.startContainer : me.endContainer;
  5599. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5600. addrs = [];
  5601. for(var i = 0,ci;ci = parents[i++];){
  5602. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5603. }
  5604. var firstIndex = 0;
  5605. if(ignoreTxt){
  5606. if(node.nodeType == 3){
  5607. var tmpNode = node.previousSibling;
  5608. while(tmpNode && tmpNode.nodeType == 3){
  5609. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5610. tmpNode = tmpNode.previousSibling;
  5611. }
  5612. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5613. }else{
  5614. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5615. if(node){
  5616. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5617. }else{
  5618. node = isStart ? me.startContainer : me.endContainer;
  5619. var first = node.firstChild;
  5620. while(first){
  5621. if(domUtils.isFillChar(first)){
  5622. first = first.nextSibling;
  5623. continue;
  5624. }
  5625. firstIndex++;
  5626. if(first.nodeType == 3){
  5627. while( first && first.nodeType == 3){
  5628. first = first.nextSibling;
  5629. }
  5630. }else{
  5631. first = first.nextSibling;
  5632. }
  5633. }
  5634. }
  5635. }
  5636. }else{
  5637. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5638. }
  5639. if(firstIndex < 0){
  5640. firstIndex = 0;
  5641. }
  5642. addrs.push(firstIndex);
  5643. return addrs;
  5644. }
  5645. addr.startAddress = getAddress(true);
  5646. if(!ignoreEnd){
  5647. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5648. }
  5649. return addr;
  5650. },
  5651. /**
  5652. * 保存
  5653. * @method createAddress
  5654. * @private
  5655. * @return { Boolean } 返回开始和结束的位置
  5656. * @example
  5657. * ```html
  5658. * <body>
  5659. * <p>
  5660. * aaaa
  5661. * <em>
  5662. * <!-- 选区开始 -->
  5663. * bbbb
  5664. * <!-- 选区结束 -->
  5665. * </em>
  5666. * </p>
  5667. *
  5668. * <script>
  5669. * var range = editor.selection.getRange();
  5670. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5671. * range.select();
  5672. * //output: 'bbbb'
  5673. * console.log(editor.selection.getText());
  5674. * </script>
  5675. * </body>
  5676. * ```
  5677. */
  5678. moveToAddress : function(addr,ignoreEnd){
  5679. var me = this;
  5680. function getNode(address,isStart){
  5681. var tmpNode = me.document.body,
  5682. parentNode,offset;
  5683. for(var i= 0,ci,l=address.length;i<l;i++){
  5684. ci = address[i];
  5685. parentNode = tmpNode;
  5686. tmpNode = tmpNode.childNodes[ci];
  5687. if(!tmpNode){
  5688. offset = ci;
  5689. break;
  5690. }
  5691. }
  5692. if(isStart){
  5693. if(tmpNode){
  5694. me.setStartBefore(tmpNode)
  5695. }else{
  5696. me.setStart(parentNode,offset)
  5697. }
  5698. }else{
  5699. if(tmpNode){
  5700. me.setEndBefore(tmpNode)
  5701. }else{
  5702. me.setEnd(parentNode,offset)
  5703. }
  5704. }
  5705. }
  5706. getNode(addr.startAddress,true);
  5707. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5708. return me;
  5709. },
  5710. /**
  5711. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5712. * @method equals
  5713. * @param { UE.dom.Range } 需要判断的Range对象
  5714. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5715. */
  5716. equals : function(rng){
  5717. for(var p in this){
  5718. if(this.hasOwnProperty(p)){
  5719. if(this[p] !== rng[p])
  5720. return false
  5721. }
  5722. }
  5723. return true;
  5724. },
  5725. /**
  5726. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5727. * 作为其参数。
  5728. * @method traversal
  5729. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5730. * @return { UE.dom.Range } 当前range对象
  5731. * @example
  5732. * ```html
  5733. *
  5734. * <body>
  5735. *
  5736. * <!-- 选区开始 -->
  5737. * <span></span>
  5738. * <a></a>
  5739. * <!-- 选区结束 -->
  5740. * </body>
  5741. *
  5742. * <script>
  5743. *
  5744. * //output: <span></span><a></a>
  5745. * console.log( range.cloneContents() );
  5746. *
  5747. * range.traversal( function ( node ) {
  5748. *
  5749. * if ( node.nodeType === 1 ) {
  5750. * node.className = "test";
  5751. * }
  5752. *
  5753. * } );
  5754. *
  5755. * //output: <span class="test"></span><a class="test"></a>
  5756. * console.log( range.cloneContents() );
  5757. *
  5758. * </script>
  5759. * ```
  5760. */
  5761. /**
  5762. * 遍历range内的节点。
  5763. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5764. * 作为其参数。
  5765. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5766. * 发doFn函数的执行
  5767. * @method traversal
  5768. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5769. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5770. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5771. * 会触发doFn。
  5772. * @return { UE.dom.Range } 当前range对象
  5773. * @see UE.dom.Range:traversal(Function)
  5774. * @example
  5775. * ```html
  5776. *
  5777. * <body>
  5778. *
  5779. * <!-- 选区开始 -->
  5780. * <span></span>
  5781. * <a></a>
  5782. * <!-- 选区结束 -->
  5783. * </body>
  5784. *
  5785. * <script>
  5786. *
  5787. * //output: <span></span><a></a>
  5788. * console.log( range.cloneContents() );
  5789. *
  5790. * range.traversal( function ( node ) {
  5791. *
  5792. * node.className = "test";
  5793. *
  5794. * }, function ( node ) {
  5795. * return node.nodeType === 1;
  5796. * } );
  5797. *
  5798. * //output: <span class="test"></span><a class="test"></a>
  5799. * console.log( range.cloneContents() );
  5800. *
  5801. * </script>
  5802. * ```
  5803. */
  5804. traversal:function(doFn,filterFn){
  5805. if (this.collapsed)
  5806. return this;
  5807. var bookmark = this.createBookmark(),
  5808. end = bookmark.end,
  5809. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5810. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5811. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5812. doFn(current);
  5813. current = tmpNode;
  5814. }
  5815. return this.moveToBookmark(bookmark);
  5816. }
  5817. };
  5818. })();
  5819. // core/Selection.js
  5820. /**
  5821. * 选集
  5822. * @file
  5823. * @module UE.dom
  5824. * @class Selection
  5825. * @since 1.2.6.1
  5826. */
  5827. /**
  5828. * 选区集合
  5829. * @unfile
  5830. * @module UE.dom
  5831. * @class Selection
  5832. */
  5833. (function () {
  5834. function getBoundaryInformation( range, start ) {
  5835. var getIndex = domUtils.getNodeIndex;
  5836. range = range.duplicate();
  5837. range.collapse( start );
  5838. var parent = range.parentElement();
  5839. //如果节点里没有子节点,直接退出
  5840. if ( !parent.hasChildNodes() ) {
  5841. return {container:parent, offset:0};
  5842. }
  5843. var siblings = parent.children,
  5844. child,
  5845. testRange = range.duplicate(),
  5846. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5847. distance;
  5848. while ( startIndex <= endIndex ) {
  5849. index = Math.floor( (startIndex + endIndex) / 2 );
  5850. child = siblings[index];
  5851. testRange.moveToElementText( child );
  5852. var position = testRange.compareEndPoints( 'StartToStart', range );
  5853. if ( position > 0 ) {
  5854. endIndex = index - 1;
  5855. } else if ( position < 0 ) {
  5856. startIndex = index + 1;
  5857. } else {
  5858. //trace:1043
  5859. return {container:parent, offset:getIndex( child )};
  5860. }
  5861. }
  5862. if ( index == -1 ) {
  5863. testRange.moveToElementText( parent );
  5864. testRange.setEndPoint( 'StartToStart', range );
  5865. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5866. siblings = parent.childNodes;
  5867. if ( !distance ) {
  5868. child = siblings[siblings.length - 1];
  5869. return {container:child, offset:child.nodeValue.length};
  5870. }
  5871. var i = siblings.length;
  5872. while ( distance > 0 ){
  5873. distance -= siblings[ --i ].nodeValue.length;
  5874. }
  5875. return {container:siblings[i], offset:-distance};
  5876. }
  5877. testRange.collapse( position > 0 );
  5878. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5879. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5880. if ( !distance ) {
  5881. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5882. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5883. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5884. }
  5885. while ( distance > 0 ) {
  5886. try {
  5887. var pre = child;
  5888. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5889. distance -= child.nodeValue.length;
  5890. } catch ( e ) {
  5891. return {container:parent, offset:getIndex( pre )};
  5892. }
  5893. }
  5894. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5895. }
  5896. /**
  5897. * 将ieRange转换为Range对象
  5898. * @param {Range} ieRange ieRange对象
  5899. * @param {Range} range Range对象
  5900. * @return {Range} range 返回转换后的Range对象
  5901. */
  5902. function transformIERangeToRange( ieRange, range ) {
  5903. if ( ieRange.item ) {
  5904. range.selectNode( ieRange.item( 0 ) );
  5905. } else {
  5906. var bi = getBoundaryInformation( ieRange, true );
  5907. range.setStart( bi.container, bi.offset );
  5908. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5909. bi = getBoundaryInformation( ieRange, false );
  5910. range.setEnd( bi.container, bi.offset );
  5911. }
  5912. }
  5913. return range;
  5914. }
  5915. /**
  5916. * 获得ieRange
  5917. * @param {Selection} sel Selection对象
  5918. * @return {ieRange} 得到ieRange
  5919. */
  5920. function _getIERange( sel ) {
  5921. var ieRange;
  5922. //ie下有可能报错
  5923. try {
  5924. ieRange = sel.getNative().createRange();
  5925. } catch ( e ) {
  5926. return null;
  5927. }
  5928. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5929. if ( ( el.ownerDocument || el ) === sel.document ) {
  5930. return ieRange;
  5931. }
  5932. return null;
  5933. }
  5934. var Selection = dom.Selection = function ( doc ) {
  5935. var me = this, iframe;
  5936. me.document = doc;
  5937. if ( browser.ie9below ) {
  5938. iframe = domUtils.getWindow( doc ).frameElement;
  5939. domUtils.on( iframe, 'beforedeactivate', function () {
  5940. me._bakIERange = me.getIERange();
  5941. } );
  5942. domUtils.on( iframe, 'activate', function () {
  5943. try {
  5944. if ( !_getIERange( me ) && me._bakIERange ) {
  5945. me._bakIERange.select();
  5946. }
  5947. } catch ( ex ) {
  5948. }
  5949. me._bakIERange = null;
  5950. } );
  5951. }
  5952. iframe = doc = null;
  5953. };
  5954. Selection.prototype = {
  5955. rangeInBody : function(rng,txtRange){
  5956. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5957. return node === this.document.body || domUtils.inDoc(node,this.document);
  5958. },
  5959. /**
  5960. * 获取原生seleciton对象
  5961. * @method getNative
  5962. * @return { Object } 获得selection对象
  5963. * @example
  5964. * ```javascript
  5965. * editor.selection.getNative();
  5966. * ```
  5967. */
  5968. getNative:function () {
  5969. var doc = this.document;
  5970. try {
  5971. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5972. } catch ( e ) {
  5973. return null;
  5974. }
  5975. },
  5976. /**
  5977. * 获得ieRange
  5978. * @method getIERange
  5979. * @return { Object } 返回ie原生的Range
  5980. * @example
  5981. * ```javascript
  5982. * editor.selection.getIERange();
  5983. * ```
  5984. */
  5985. getIERange:function () {
  5986. var ieRange = _getIERange( this );
  5987. if ( !ieRange ) {
  5988. if ( this._bakIERange ) {
  5989. return this._bakIERange;
  5990. }
  5991. }
  5992. return ieRange;
  5993. },
  5994. /**
  5995. * 缓存当前选区的range和选区的开始节点
  5996. * @method cache
  5997. */
  5998. cache:function () {
  5999. this.clear();
  6000. this._cachedRange = this.getRange();
  6001. this._cachedStartElement = this.getStart();
  6002. this._cachedStartElementPath = this.getStartElementPath();
  6003. },
  6004. /**
  6005. * 获取选区开始位置的父节点到body
  6006. * @method getStartElementPath
  6007. * @return { Array } 返回父节点集合
  6008. * @example
  6009. * ```javascript
  6010. * editor.selection.getStartElementPath();
  6011. * ```
  6012. */
  6013. getStartElementPath:function () {
  6014. if ( this._cachedStartElementPath ) {
  6015. return this._cachedStartElementPath;
  6016. }
  6017. var start = this.getStart();
  6018. if ( start ) {
  6019. return domUtils.findParents( start, true, null, true )
  6020. }
  6021. return [];
  6022. },
  6023. /**
  6024. * 清空缓存
  6025. * @method clear
  6026. */
  6027. clear:function () {
  6028. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6029. },
  6030. /**
  6031. * 编辑器是否得到了选区
  6032. * @method isFocus
  6033. */
  6034. isFocus:function () {
  6035. try {
  6036. if(browser.ie9below){
  6037. var nativeRange = _getIERange(this);
  6038. return !!(nativeRange && this.rangeInBody(nativeRange));
  6039. }else{
  6040. return !!this.getNative().rangeCount;
  6041. }
  6042. } catch ( e ) {
  6043. return false;
  6044. }
  6045. },
  6046. /**
  6047. * 获取选区对应的Range
  6048. * @method getRange
  6049. * @return { Object } 得到Range对象
  6050. * @example
  6051. * ```javascript
  6052. * editor.selection.getRange();
  6053. * ```
  6054. */
  6055. getRange:function () {
  6056. var me = this;
  6057. function optimze( range ) {
  6058. var child = me.document.body.firstChild,
  6059. collapsed = range.collapsed;
  6060. while ( child && child.firstChild ) {
  6061. range.setStart( child, 0 );
  6062. child = child.firstChild;
  6063. }
  6064. if ( !range.startContainer ) {
  6065. range.setStart( me.document.body, 0 )
  6066. }
  6067. if ( collapsed ) {
  6068. range.collapse( true );
  6069. }
  6070. }
  6071. if ( me._cachedRange != null ) {
  6072. return this._cachedRange;
  6073. }
  6074. var range = new baidu.editor.dom.Range( me.document );
  6075. if ( browser.ie9below ) {
  6076. var nativeRange = me.getIERange();
  6077. if ( nativeRange ) {
  6078. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6079. try{
  6080. transformIERangeToRange( nativeRange, range );
  6081. }catch(e){
  6082. optimze( range );
  6083. }
  6084. } else {
  6085. optimze( range );
  6086. }
  6087. } else {
  6088. var sel = me.getNative();
  6089. if ( sel && sel.rangeCount ) {
  6090. var firstRange = sel.getRangeAt( 0 );
  6091. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6092. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6093. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6094. optimze( range );
  6095. }
  6096. } else {
  6097. //trace:1734 有可能已经不在dom树上了,标识的节点
  6098. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6099. return this._bakRange;
  6100. }
  6101. optimze( range );
  6102. }
  6103. }
  6104. return this._bakRange = range;
  6105. },
  6106. /**
  6107. * 获取开始元素,用于状态反射
  6108. * @method getStart
  6109. * @return { Element } 获得开始元素
  6110. * @example
  6111. * ```javascript
  6112. * editor.selection.getStart();
  6113. * ```
  6114. */
  6115. getStart:function () {
  6116. if ( this._cachedStartElement ) {
  6117. return this._cachedStartElement;
  6118. }
  6119. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6120. tmpRange,
  6121. start, tmp, parent;
  6122. if ( browser.ie9below ) {
  6123. if ( !range ) {
  6124. //todo 给第一个值可能会有问题
  6125. return this.document.body.firstChild;
  6126. }
  6127. //control元素
  6128. if ( range.item ){
  6129. return range.item( 0 );
  6130. }
  6131. tmpRange = range.duplicate();
  6132. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6133. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6134. tmpRange.collapse( 1 );
  6135. start = tmpRange.parentElement();
  6136. parent = tmp = range.parentElement();
  6137. while ( tmp = tmp.parentNode ) {
  6138. if ( tmp == start ) {
  6139. start = parent;
  6140. break;
  6141. }
  6142. }
  6143. } else {
  6144. range.shrinkBoundary();
  6145. start = range.startContainer;
  6146. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6147. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6148. }
  6149. if ( start.nodeType == 3 ){
  6150. return start.parentNode;
  6151. }
  6152. }
  6153. return start;
  6154. },
  6155. /**
  6156. * 得到选区中的文本
  6157. * @method getText
  6158. * @return { String } 选区中包含的文本
  6159. * @example
  6160. * ```javascript
  6161. * editor.selection.getText();
  6162. * ```
  6163. */
  6164. getText:function () {
  6165. var nativeSel, nativeRange;
  6166. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6167. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6168. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6169. }
  6170. return '';
  6171. },
  6172. /**
  6173. * 清除选区
  6174. * @method clearRange
  6175. * @example
  6176. * ```javascript
  6177. * editor.selection.clearRange();
  6178. * ```
  6179. */
  6180. clearRange : function(){
  6181. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6182. }
  6183. };
  6184. })();
  6185. // core/Editor.js
  6186. /**
  6187. * 编辑器主类,包含编辑器提供的大部分公用接口
  6188. * @file
  6189. * @module UE
  6190. * @class Editor
  6191. * @since 1.2.6.1
  6192. */
  6193. /**
  6194. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6195. * @unfile
  6196. * @module UE
  6197. */
  6198. /**
  6199. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6200. * @unfile
  6201. * @module UE
  6202. * @class Editor
  6203. */
  6204. (function () {
  6205. var uid = 0, _selectionChangeTimer;
  6206. /**
  6207. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6208. * @private
  6209. * @method setValue
  6210. * @param { UE.Editor } editor 编辑器事例
  6211. */
  6212. function setValue(form, editor) {
  6213. var textarea;
  6214. if (editor.textarea) {
  6215. if (utils.isString(editor.textarea)) {
  6216. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6217. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6218. textarea = ti;
  6219. break;
  6220. }
  6221. }
  6222. } else {
  6223. textarea = editor.textarea;
  6224. }
  6225. }
  6226. if (!textarea) {
  6227. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6228. 'name': editor.options.textarea,
  6229. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6230. 'style': "display:none"
  6231. }));
  6232. //不要产生多个textarea
  6233. editor.textarea = textarea;
  6234. }
  6235. textarea.value = editor.hasContents() ?
  6236. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6237. ''
  6238. }
  6239. function loadPlugins(me){
  6240. //初始化插件
  6241. for (var pi in UE.plugins) {
  6242. UE.plugins[pi].call(me);
  6243. }
  6244. }
  6245. function checkCurLang(I18N){
  6246. for(var lang in I18N){
  6247. return lang
  6248. }
  6249. }
  6250. function langReadied(me){
  6251. me.langIsReady = true;
  6252. me.fireEvent("langReady");
  6253. }
  6254. /**
  6255. * 编辑器准备就绪后会触发该事件
  6256. * @module UE
  6257. * @class Editor
  6258. * @event ready
  6259. * @remind render方法执行完成之后,会触发该事件
  6260. * @remind
  6261. * @example
  6262. * ```javascript
  6263. * editor.addListener( 'ready', function( editor ) {
  6264. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6265. * } );
  6266. * ```
  6267. */
  6268. /**
  6269. * 执行destroy方法,会触发该事件
  6270. * @module UE
  6271. * @class Editor
  6272. * @event destroy
  6273. * @see UE.Editor:destroy()
  6274. */
  6275. /**
  6276. * 执行reset方法,会触发该事件
  6277. * @module UE
  6278. * @class Editor
  6279. * @event reset
  6280. * @see UE.Editor:reset()
  6281. */
  6282. /**
  6283. * 执行focus方法,会触发该事件
  6284. * @module UE
  6285. * @class Editor
  6286. * @event focus
  6287. * @see UE.Editor:focus(Boolean)
  6288. */
  6289. /**
  6290. * 语言加载完成会触发该事件
  6291. * @module UE
  6292. * @class Editor
  6293. * @event langReady
  6294. */
  6295. /**
  6296. * 运行命令之后会触发该命令
  6297. * @module UE
  6298. * @class Editor
  6299. * @event beforeExecCommand
  6300. */
  6301. /**
  6302. * 运行命令之后会触发该命令
  6303. * @module UE
  6304. * @class Editor
  6305. * @event afterExecCommand
  6306. */
  6307. /**
  6308. * 运行命令之前会触发该命令
  6309. * @module UE
  6310. * @class Editor
  6311. * @event firstBeforeExecCommand
  6312. */
  6313. /**
  6314. * 在getContent方法执行之前会触发该事件
  6315. * @module UE
  6316. * @class Editor
  6317. * @event beforeGetContent
  6318. * @see UE.Editor:getContent()
  6319. */
  6320. /**
  6321. * 在getContent方法执行之后会触发该事件
  6322. * @module UE
  6323. * @class Editor
  6324. * @event afterGetContent
  6325. * @see UE.Editor:getContent()
  6326. */
  6327. /**
  6328. * 在getAllHtml方法执行时会触发该事件
  6329. * @module UE
  6330. * @class Editor
  6331. * @event getAllHtml
  6332. * @see UE.Editor:getAllHtml()
  6333. */
  6334. /**
  6335. * 在setContent方法执行之前会触发该事件
  6336. * @module UE
  6337. * @class Editor
  6338. * @event beforeSetContent
  6339. * @see UE.Editor:setContent(String)
  6340. */
  6341. /**
  6342. * 在setContent方法执行之后会触发该事件
  6343. * @module UE
  6344. * @class Editor
  6345. * @event afterSetContent
  6346. * @see UE.Editor:setContent(String)
  6347. */
  6348. /**
  6349. * 每当编辑器内部选区发生改变时,将触发该事件
  6350. * @event selectionchange
  6351. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6352. * @example
  6353. * ```javascript
  6354. * editor.addListener( 'selectionchange', function( editor ) {
  6355. * console.log('选区发生改变');
  6356. * }
  6357. */
  6358. /**
  6359. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6360. * @module UE
  6361. * @class Editor
  6362. * @event beforeSelectionChange
  6363. * @see UE.Editor:selectionchange
  6364. */
  6365. /**
  6366. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6367. * @module UE
  6368. * @class Editor
  6369. * @event afterSelectionChange
  6370. * @see UE.Editor:selectionchange
  6371. */
  6372. /**
  6373. * 编辑器内容发生改变时会触发该事件
  6374. * @module UE
  6375. * @class Editor
  6376. * @event contentChange
  6377. */
  6378. /**
  6379. * 以默认参数构建一个编辑器实例
  6380. * @constructor
  6381. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6382. * @example
  6383. * ```javascript
  6384. * var editor = new UE.Editor();
  6385. * editor.execCommand('blod');
  6386. * ```
  6387. * @see UE.Config
  6388. */
  6389. /**
  6390. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6391. * @constructor
  6392. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6393. * @param { Object } setting 创建编辑器的参数
  6394. * @example
  6395. * ```javascript
  6396. * var editor = new UE.Editor();
  6397. * editor.execCommand('blod');
  6398. * ```
  6399. * @see UE.Config
  6400. */
  6401. var Editor = UE.Editor = function (options) {
  6402. var me = this;
  6403. me.uid = uid++;
  6404. EventBase.call(me);
  6405. me.commands = {};
  6406. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6407. me.shortcutkeys = {};
  6408. me.inputRules = [];
  6409. me.outputRules = [];
  6410. //设置默认的常用属性
  6411. me.setOpt({
  6412. isShow: true,
  6413. initialContent: '',
  6414. initialStyle:'',
  6415. autoClearinitialContent: false,
  6416. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  6417. textarea: 'editorValue',
  6418. focus: false,
  6419. focusInEnd: true,
  6420. autoClearEmptyNode: true,
  6421. fullscreen: false,
  6422. readonly: false,
  6423. zIndex: 999,
  6424. imagePopup: true,
  6425. enterTag: 'p',
  6426. customDomain: false,
  6427. lang: 'zh-cn',
  6428. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  6429. theme: 'default',
  6430. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  6431. allHtmlEnabled: false,
  6432. scaleEnabled: false,
  6433. tableNativeEditInFF: false,
  6434. autoSyncData : true,
  6435. fileNameFormat: '{time}{rand:6}'
  6436. });
  6437. /* 尝试异步加载后台配置 */
  6438. me.loadServerConfig();
  6439. if(!utils.isEmptyObject(UE.I18N)){
  6440. //修改默认的语言类型
  6441. me.options.lang = checkCurLang(UE.I18N);
  6442. UE.plugin.load(me);
  6443. langReadied(me);
  6444. }else{
  6445. utils.loadFile(document, {
  6446. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6447. tag: "script",
  6448. type: "text/javascript",
  6449. defer: "defer"
  6450. }, function () {
  6451. UE.plugin.load(me);
  6452. langReadied(me);
  6453. });
  6454. }
  6455. UE.instants['ueditorInstant' + me.uid] = me;
  6456. };
  6457. Editor.prototype = {
  6458. registerCommand : function(name,obj){
  6459. this.commands[name] = obj;
  6460. },
  6461. /**
  6462. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6463. * @method ready
  6464. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6465. * 立即触发该回调。
  6466. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6467. * @example
  6468. * ```javascript
  6469. * editor.ready( function( editor ) {
  6470. * editor.setContent('初始化完毕');
  6471. * } );
  6472. * ```
  6473. * @see UE.Editor.event:ready
  6474. */
  6475. ready: function (fn) {
  6476. var me = this;
  6477. if (fn) {
  6478. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6479. }
  6480. },
  6481. /**
  6482. * 该方法是提供给插件里面使用,设置配置项默认值
  6483. * @method setOpt
  6484. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6485. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6486. * @param { String } key 编辑器的可接受的选项名称
  6487. * @param { * } val 该选项可接受的值
  6488. * @example
  6489. * ```javascript
  6490. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6491. * ```
  6492. */
  6493. /**
  6494. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6495. * @method setOpt
  6496. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6497. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6498. * @param { Object } options 将要设置的选项的键值对对象
  6499. * @example
  6500. * ```javascript
  6501. * editor.setOpt( {
  6502. * 'initContent': '欢迎使用编辑器'
  6503. * } );
  6504. * ```
  6505. */
  6506. setOpt: function (key, val) {
  6507. var obj = {};
  6508. if (utils.isString(key)) {
  6509. obj[key] = val
  6510. } else {
  6511. obj = key;
  6512. }
  6513. utils.extend(this.options, obj, true);
  6514. },
  6515. getOpt:function(key){
  6516. return this.options[key]
  6517. },
  6518. /**
  6519. * 销毁编辑器实例,使用textarea代替
  6520. * @method destroy
  6521. * @example
  6522. * ```javascript
  6523. * editor.destroy();
  6524. * ```
  6525. */
  6526. destroy: function () {
  6527. var me = this;
  6528. me.fireEvent('destroy');
  6529. var container = me.container.parentNode;
  6530. var textarea = me.textarea;
  6531. if (!textarea) {
  6532. textarea = document.createElement('textarea');
  6533. container.parentNode.insertBefore(textarea, container);
  6534. } else {
  6535. textarea.style.display = ''
  6536. }
  6537. textarea.style.width = me.iframe.offsetWidth + 'px';
  6538. textarea.style.height = me.iframe.offsetHeight + 'px';
  6539. textarea.value = me.getContent();
  6540. textarea.id = me.key;
  6541. container.innerHTML = '';
  6542. domUtils.remove(container);
  6543. var key = me.key;
  6544. //trace:2004
  6545. for (var p in me) {
  6546. if (me.hasOwnProperty(p)) {
  6547. delete this[p];
  6548. }
  6549. }
  6550. UE.delEditor(key);
  6551. },
  6552. /**
  6553. * 渲染编辑器的DOM到指定容器
  6554. * @method render
  6555. * @param { String } containerId 指定一个容器ID
  6556. * @remind 执行该方法,会触发ready事件
  6557. * @warning 必须且只能调用一次
  6558. */
  6559. /**
  6560. * 渲染编辑器的DOM到指定容器
  6561. * @method render
  6562. * @param { Element } containerDom 直接指定容器对象
  6563. * @remind 执行该方法,会触发ready事件
  6564. * @warning 必须且只能调用一次
  6565. */
  6566. render: function (container) {
  6567. var me = this,
  6568. options = me.options,
  6569. getStyleValue=function(attr){
  6570. return parseInt(domUtils.getComputedStyle(container,attr));
  6571. };
  6572. if (utils.isString(container)) {
  6573. container = document.getElementById(container);
  6574. }
  6575. if (container) {
  6576. if(options.initialFrameWidth){
  6577. options.minFrameWidth = options.initialFrameWidth
  6578. }else{
  6579. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6580. }
  6581. if(options.initialFrameHeight){
  6582. options.minFrameHeight = options.initialFrameHeight
  6583. }else{
  6584. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6585. }
  6586. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6587. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6588. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6589. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6590. container.style.zIndex = options.zIndex;
  6591. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6592. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6593. '<style type=\'text/css\'>' +
  6594. //设置四周的留边
  6595. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6596. //设置默认字体和字号
  6597. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6598. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6599. //设置段落间距
  6600. 'p{margin:5px 0;}</style>' +
  6601. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6602. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6603. '</head><body class=\'view\' ></body>' +
  6604. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6605. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6606. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6607. container.appendChild(domUtils.createElement(document, 'iframe', {
  6608. id: 'ueditor_' + me.uid,
  6609. width: "100%",
  6610. height: "100%",
  6611. frameborder: "0",
  6612. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6613. // scrolling :'no',
  6614. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6615. 'document.write("' + html + '");document.close();}())'
  6616. }));
  6617. container.style.overflow = 'hidden';
  6618. //解决如果是给定的百分比,会导致高度算不对的问题
  6619. setTimeout(function(){
  6620. if( /%$/.test(options.initialFrameWidth)){
  6621. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6622. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6623. // container.style.width = options.initialFrameWidth + 'px';
  6624. }
  6625. if(/%$/.test(options.initialFrameHeight)){
  6626. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6627. container.style.height = options.initialFrameHeight + 'px';
  6628. }
  6629. })
  6630. }
  6631. },
  6632. /**
  6633. * 编辑器初始化
  6634. * @method _setup
  6635. * @private
  6636. * @param { Element } doc 编辑器Iframe中的文档对象
  6637. */
  6638. _setup: function (doc) {
  6639. var me = this,
  6640. options = me.options;
  6641. if (ie) {
  6642. doc.body.disabled = true;
  6643. doc.body.contentEditable = true;
  6644. doc.body.disabled = false;
  6645. } else {
  6646. doc.body.contentEditable = true;
  6647. }
  6648. doc.body.spellcheck = false;
  6649. me.document = doc;
  6650. me.window = doc.defaultView || doc.parentWindow;
  6651. me.iframe = me.window.frameElement;
  6652. me.body = doc.body;
  6653. me.selection = new dom.Selection(doc);
  6654. //gecko初始化就能得到range,无法判断isFocus了
  6655. var geckoSel;
  6656. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6657. geckoSel.removeAllRanges();
  6658. }
  6659. this._initEvents();
  6660. //为form提交提供一个隐藏的textarea
  6661. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6662. if (form.tagName == 'FORM') {
  6663. me.form = form;
  6664. if(me.options.autoSyncData){
  6665. domUtils.on(me.window,'blur',function(){
  6666. setValue(form,me);
  6667. });
  6668. }else{
  6669. domUtils.on(form, 'submit', function () {
  6670. setValue(this, me);
  6671. });
  6672. }
  6673. break;
  6674. }
  6675. }
  6676. if (options.initialContent) {
  6677. if (options.autoClearinitialContent) {
  6678. var oldExecCommand = me.execCommand;
  6679. me.execCommand = function () {
  6680. me.fireEvent('firstBeforeExecCommand');
  6681. return oldExecCommand.apply(me, arguments);
  6682. };
  6683. this._setDefaultContent(options.initialContent);
  6684. } else
  6685. this.setContent(options.initialContent, false, true);
  6686. }
  6687. //编辑器不能为空内容
  6688. if (domUtils.isEmptyNode(me.body)) {
  6689. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6690. }
  6691. //如果要求focus, 就把光标定位到内容开始
  6692. if (options.focus) {
  6693. setTimeout(function () {
  6694. me.focus(me.options.focusInEnd);
  6695. //如果自动清除开着,就不需要做selectionchange;
  6696. !me.options.autoClearinitialContent && me._selectionChange();
  6697. }, 0);
  6698. }
  6699. if (!me.container) {
  6700. me.container = this.iframe.parentNode;
  6701. }
  6702. if (options.fullscreen && me.ui) {
  6703. me.ui.setFullScreen(true);
  6704. }
  6705. try {
  6706. me.document.execCommand('2D-position', false, false);
  6707. } catch (e) {
  6708. }
  6709. try {
  6710. me.document.execCommand('enableInlineTableEditing', false, false);
  6711. } catch (e) {
  6712. }
  6713. try {
  6714. me.document.execCommand('enableObjectResizing', false, false);
  6715. } catch (e) {
  6716. }
  6717. //挂接快捷键
  6718. me._bindshortcutKeys();
  6719. me.isReady = 1;
  6720. me.fireEvent('ready');
  6721. options.onready && options.onready.call(me);
  6722. if (!browser.ie9below) {
  6723. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6724. //chrome下会出现alt+tab切换时,导致选区位置不对
  6725. if (e.type == 'blur') {
  6726. me._bakRange = me.selection.getRange();
  6727. try {
  6728. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6729. me.selection.getNative().removeAllRanges();
  6730. } catch (e) {
  6731. me._bakNativeRange = null;
  6732. }
  6733. } else {
  6734. try {
  6735. me._bakRange && me._bakRange.select();
  6736. } catch (e) {
  6737. }
  6738. }
  6739. });
  6740. }
  6741. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6742. if (browser.gecko && browser.version <= 10902) {
  6743. //修复ff3.6初始化进来,不能点击获得焦点
  6744. me.body.contentEditable = false;
  6745. setTimeout(function () {
  6746. me.body.contentEditable = true;
  6747. }, 100);
  6748. setInterval(function () {
  6749. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6750. }, 100)
  6751. }
  6752. !options.isShow && me.setHide();
  6753. options.readonly && me.setDisabled();
  6754. },
  6755. /**
  6756. * 同步数据到编辑器所在的form
  6757. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6758. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6759. * @method sync
  6760. * @example
  6761. * ```javascript
  6762. * editor.sync();
  6763. * form.sumbit(); //form变量已经指向了form元素
  6764. * ```
  6765. */
  6766. /**
  6767. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6768. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6769. * @method sync
  6770. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6771. */
  6772. sync: function (formId) {
  6773. var me = this,
  6774. form = formId ? document.getElementById(formId) :
  6775. domUtils.findParent(me.iframe.parentNode, function (node) {
  6776. return node.tagName == 'FORM'
  6777. }, true);
  6778. form && setValue(form, me);
  6779. },
  6780. /**
  6781. * 设置编辑器高度
  6782. * @method setHeight
  6783. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6784. * @param { Number } number 设置的高度值,纯数值,不带单位
  6785. * @example
  6786. * ```javascript
  6787. * editor.setHeight(number);
  6788. * ```
  6789. */
  6790. setHeight: function (height,notSetHeight) {
  6791. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6792. this.iframe.parentNode.style.height = height + 'px';
  6793. }
  6794. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6795. this.body.style.height = height + 'px';
  6796. !notSetHeight && this.trigger('setHeight')
  6797. },
  6798. /**
  6799. * 为编辑器的编辑命令提供快捷键
  6800. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6801. * @method addshortcutkey
  6802. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6803. * @example
  6804. * ```javascript
  6805. * editor.addshortcutkey({
  6806. * "Bold" : "ctrl+66",//^B
  6807. * "Italic" : "ctrl+73", //^I
  6808. * });
  6809. * ```
  6810. */
  6811. /**
  6812. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6813. * @method addshortcutkey
  6814. * @param { String } cmd 触发快捷键时,响应的命令
  6815. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6816. * @example
  6817. * ```javascript
  6818. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6819. * ```
  6820. */
  6821. addshortcutkey: function (cmd, keys) {
  6822. var obj = {};
  6823. if (keys) {
  6824. obj[cmd] = keys
  6825. } else {
  6826. obj = cmd;
  6827. }
  6828. utils.extend(this.shortcutkeys, obj)
  6829. },
  6830. /**
  6831. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6832. * @method _bindshortcutKeys
  6833. * @private
  6834. */
  6835. _bindshortcutKeys: function () {
  6836. var me = this, shortcutkeys = this.shortcutkeys;
  6837. me.addListener('keydown', function (type, e) {
  6838. var keyCode = e.keyCode || e.which;
  6839. for (var i in shortcutkeys) {
  6840. var tmp = shortcutkeys[i].split(',');
  6841. for (var t = 0, ti; ti = tmp[t++];) {
  6842. ti = ti.split(':');
  6843. var key = ti[0], param = ti[1];
  6844. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6845. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6846. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6847. && keyCode == RegExp.$3
  6848. ) ||
  6849. keyCode == RegExp.$1
  6850. ) {
  6851. if (me.queryCommandState(i,param) != -1)
  6852. me.execCommand(i, param);
  6853. domUtils.preventDefault(e);
  6854. }
  6855. }
  6856. }
  6857. }
  6858. });
  6859. },
  6860. /**
  6861. * 获取编辑器的内容
  6862. * @method getContent
  6863. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6864. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6865. * @example
  6866. * ```javascript
  6867. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6868. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6869. * ```
  6870. */
  6871. /**
  6872. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6873. * @method getContent
  6874. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6875. * 代表当前编辑器的内容是否空,
  6876. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6877. * 经过内置过滤规则处理后的内容。
  6878. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6879. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6880. * @return { String } 编辑器的内容字符串
  6881. * @example
  6882. * ```javascript
  6883. * // editor 是一个编辑器的实例
  6884. * var content = editor.getContent( function ( editor ) {
  6885. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6886. * } );
  6887. * ```
  6888. */
  6889. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6890. var me = this;
  6891. if (cmd && utils.isFunction(cmd)) {
  6892. fn = cmd;
  6893. cmd = '';
  6894. }
  6895. if (fn ? !fn() : !this.hasContents()) {
  6896. return '';
  6897. }
  6898. me.fireEvent('beforegetcontent');
  6899. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6900. me.filterOutputRule(root);
  6901. me.fireEvent('aftergetcontent', cmd,root);
  6902. return root.toHtml(formatter);
  6903. },
  6904. /**
  6905. * 取得完整的html代码,可以直接显示成完整的html文档
  6906. * @method getAllHtml
  6907. * @return { String } 编辑器的内容html文档字符串
  6908. * @eaxmple
  6909. * ```javascript
  6910. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6911. * ```
  6912. */
  6913. getAllHtml: function () {
  6914. var me = this,
  6915. headHtml = [],
  6916. html = '';
  6917. me.fireEvent('getAllHtml', headHtml);
  6918. if (browser.ie && browser.version > 8) {
  6919. var headHtmlForIE9 = '';
  6920. utils.each(me.document.styleSheets, function (si) {
  6921. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6922. });
  6923. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6924. headHtmlForIE9 += si.outerHTML;
  6925. });
  6926. }
  6927. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6928. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6929. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6930. },
  6931. /**
  6932. * 得到编辑器的纯文本内容,但会保留段落格式
  6933. * @method getPlainTxt
  6934. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6935. * @example
  6936. * ```javascript
  6937. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6938. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6939. * ```
  6940. */
  6941. getPlainTxt: function () {
  6942. var reg = new RegExp(domUtils.fillChar, 'g'),
  6943. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6944. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6945. .replace(/<br\/?>/gi, '\n')
  6946. .replace(/<[^>/]+>/g, '')
  6947. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6948. return dtd.$block[c] ? '\n' : b ? b : '';
  6949. });
  6950. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6951. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6952. },
  6953. /**
  6954. * 获取编辑器中的纯文本内容,没有段落格式
  6955. * @method getContentTxt
  6956. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6957. * @example
  6958. * ```javascript
  6959. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6960. * console.log(editor.getPlainTxt()); //输出:"12
  6961. * ```
  6962. */
  6963. getContentTxt: function () {
  6964. var reg = new RegExp(domUtils.fillChar, 'g');
  6965. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6966. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6967. },
  6968. /**
  6969. * 设置编辑器的内容,可修改编辑器当前的html内容
  6970. * @method setContent
  6971. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6972. * @warning 该方法会触发selectionchange事件
  6973. * @param { String } html 要插入的html内容
  6974. * @example
  6975. * ```javascript
  6976. * editor.getContent('<p>test</p>');
  6977. * ```
  6978. */
  6979. /**
  6980. * 设置编辑器的内容,可修改编辑器当前的html内容
  6981. * @method setContent
  6982. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6983. * @warning 该方法会触发selectionchange事件
  6984. * @param { String } html 要插入的html内容
  6985. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6986. * @example
  6987. * ```javascript
  6988. * //假设设置前的编辑器内容是 <p>old text</p>
  6989. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6990. * ```
  6991. */
  6992. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6993. var me = this;
  6994. me.fireEvent('beforesetcontent', html);
  6995. var root = UE.htmlparser(html);
  6996. me.filterInputRule(root);
  6997. html = root.toHtml();
  6998. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6999. function isCdataDiv(node){
  7000. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  7001. }
  7002. //给文本或者inline节点套p标签
  7003. if (me.options.enterTag == 'p') {
  7004. var child = this.body.firstChild, tmpNode;
  7005. if (!child || child.nodeType == 1 &&
  7006. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7007. domUtils.isCustomeNode(child)
  7008. )
  7009. && child === this.body.lastChild) {
  7010. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7011. } else {
  7012. var p = me.document.createElement('p');
  7013. while (child) {
  7014. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7015. tmpNode = child.nextSibling;
  7016. p.appendChild(child);
  7017. child = tmpNode;
  7018. }
  7019. if (p.firstChild) {
  7020. if (!child) {
  7021. me.body.appendChild(p);
  7022. break;
  7023. } else {
  7024. child.parentNode.insertBefore(p, child);
  7025. p = me.document.createElement('p');
  7026. }
  7027. }
  7028. child = child.nextSibling;
  7029. }
  7030. }
  7031. }
  7032. me.fireEvent('aftersetcontent');
  7033. me.fireEvent('contentchange');
  7034. !notFireSelectionchange && me._selectionChange();
  7035. //清除保存的选区
  7036. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7037. //trace:1742 setContent后gecko能得到焦点问题
  7038. var geckoSel;
  7039. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7040. geckoSel.removeAllRanges();
  7041. }
  7042. if(me.options.autoSyncData){
  7043. me.form && setValue(me.form,me);
  7044. }
  7045. },
  7046. /**
  7047. * 让编辑器获得焦点,默认focus到编辑器头部
  7048. * @method focus
  7049. * @example
  7050. * ```javascript
  7051. * editor.focus()
  7052. * ```
  7053. */
  7054. /**
  7055. * 让编辑器获得焦点,toEnd确定focus位置
  7056. * @method focus
  7057. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7058. * @example
  7059. * ```javascript
  7060. * editor.focus(true)
  7061. * ```
  7062. */
  7063. focus: function (toEnd) {
  7064. try {
  7065. var me = this,
  7066. rng = me.selection.getRange();
  7067. if (toEnd) {
  7068. var node = me.body.lastChild;
  7069. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7070. if(domUtils.isEmptyBlock(node)){
  7071. rng.setStartAtFirst(node)
  7072. }else{
  7073. rng.setStartAtLast(node)
  7074. }
  7075. rng.collapse(true);
  7076. }
  7077. rng.setCursor(true);
  7078. } else {
  7079. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7080. var node = me.body.firstChild;
  7081. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7082. rng.setStartAtFirst(node).collapse(true);
  7083. }
  7084. }
  7085. rng.select(true);
  7086. }
  7087. this.fireEvent('focus selectionchange');
  7088. } catch (e) {
  7089. }
  7090. },
  7091. isFocus:function(){
  7092. return this.selection.isFocus();
  7093. },
  7094. blur:function(){
  7095. var sel = this.selection.getNative();
  7096. if(sel.empty && browser.ie){
  7097. var nativeRng = document.body.createTextRange();
  7098. nativeRng.moveToElementText(document.body);
  7099. nativeRng.collapse(true);
  7100. nativeRng.select();
  7101. sel.empty()
  7102. }else{
  7103. sel.removeAllRanges()
  7104. }
  7105. //this.fireEvent('blur selectionchange');
  7106. },
  7107. /**
  7108. * 初始化UE事件及部分事件代理
  7109. * @method _initEvents
  7110. * @private
  7111. */
  7112. _initEvents: function () {
  7113. var me = this,
  7114. doc = me.document,
  7115. win = me.window;
  7116. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7117. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7118. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7119. domUtils.on(me.body,'drop',function(e){
  7120. //阻止ff下默认的弹出新页面打开图片
  7121. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7122. me.fireEvent('contentchange')
  7123. });
  7124. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7125. //特殊键不触发selectionchange
  7126. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7127. return;
  7128. }
  7129. if (evt.button == 2)return;
  7130. me._selectionChange(250, evt);
  7131. });
  7132. },
  7133. /**
  7134. * 触发事件代理
  7135. * @method _proxyDomEvent
  7136. * @private
  7137. * @return { * } fireEvent的返回值
  7138. * @see UE.EventBase:fireEvent(String)
  7139. */
  7140. _proxyDomEvent: function (evt) {
  7141. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7142. return false;
  7143. }
  7144. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7145. return false;
  7146. }
  7147. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7148. },
  7149. /**
  7150. * 变化选区
  7151. * @method _selectionChange
  7152. * @private
  7153. */
  7154. _selectionChange: function (delay, evt) {
  7155. var me = this;
  7156. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7157. // if ( !me.selection.isFocus() ){
  7158. // return;
  7159. // }
  7160. var hackForMouseUp = false;
  7161. var mouseX, mouseY;
  7162. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7163. var range = this.selection.getRange();
  7164. if (!range.collapsed) {
  7165. hackForMouseUp = true;
  7166. mouseX = evt.clientX;
  7167. mouseY = evt.clientY;
  7168. }
  7169. }
  7170. clearTimeout(_selectionChangeTimer);
  7171. _selectionChangeTimer = setTimeout(function () {
  7172. if (!me.selection || !me.selection.getNative()) {
  7173. return;
  7174. }
  7175. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7176. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7177. var ieRange;
  7178. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7179. ieRange = me.document.body.createTextRange();
  7180. try {
  7181. ieRange.moveToPoint(mouseX, mouseY);
  7182. } catch (ex) {
  7183. ieRange = null;
  7184. }
  7185. }
  7186. var bakGetIERange;
  7187. if (ieRange) {
  7188. bakGetIERange = me.selection.getIERange;
  7189. me.selection.getIERange = function () {
  7190. return ieRange;
  7191. };
  7192. }
  7193. me.selection.cache();
  7194. if (bakGetIERange) {
  7195. me.selection.getIERange = bakGetIERange;
  7196. }
  7197. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7198. me.fireEvent('beforeselectionchange');
  7199. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7200. me.fireEvent('selectionchange', !!evt);
  7201. me.fireEvent('afterselectionchange');
  7202. me.selection.clear();
  7203. }
  7204. }, delay || 50);
  7205. },
  7206. /**
  7207. * 执行编辑命令
  7208. * @method _callCmdFn
  7209. * @private
  7210. * @param { String } fnName 函数名称
  7211. * @param { * } args 传给命令函数的参数
  7212. * @return { * } 返回命令函数运行的返回值
  7213. */
  7214. _callCmdFn: function (fnName, args) {
  7215. var cmdName = args[0].toLowerCase(),
  7216. cmd, cmdFn;
  7217. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7218. cmdFn = cmd && cmd[fnName];
  7219. //没有querycommandstate或者没有command的都默认返回0
  7220. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7221. return 0;
  7222. } else if (cmdFn) {
  7223. return cmdFn.apply(this, args);
  7224. }
  7225. },
  7226. /**
  7227. * 执行编辑命令cmdName,完成富文本编辑效果
  7228. * @method execCommand
  7229. * @param { String } cmdName 需要执行的命令
  7230. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7231. * @return { * } 返回命令函数运行的返回值
  7232. * @example
  7233. * ```javascript
  7234. * editor.execCommand(cmdName);
  7235. * ```
  7236. */
  7237. execCommand: function (cmdName) {
  7238. cmdName = cmdName.toLowerCase();
  7239. var me = this,
  7240. result,
  7241. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7242. if (!cmd || !cmd.execCommand) {
  7243. return null;
  7244. }
  7245. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7246. me.__hasEnterExecCommand = true;
  7247. if (me.queryCommandState.apply(me,arguments) != -1) {
  7248. me.fireEvent('saveScene');
  7249. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7250. result = this._callCmdFn('execCommand', arguments);
  7251. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7252. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7253. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7254. me.fireEvent('saveScene');
  7255. }
  7256. me.__hasEnterExecCommand = false;
  7257. } else {
  7258. result = this._callCmdFn('execCommand', arguments);
  7259. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7260. }
  7261. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7262. return result;
  7263. },
  7264. /**
  7265. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7266. * @method queryCommandState
  7267. * @param { String } cmdName 需要查询的命令名称
  7268. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7269. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7270. * @example
  7271. * ```javascript
  7272. * editor.queryCommandState(cmdName) => (-1|0|1)
  7273. * ```
  7274. * @see COMMAND.LIST
  7275. */
  7276. queryCommandState: function (cmdName) {
  7277. return this._callCmdFn('queryCommandState', arguments);
  7278. },
  7279. /**
  7280. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7281. * @method queryCommandValue
  7282. * @param { String } cmdName 需要查询的命令名称
  7283. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7284. * @remind 只有部分插件有此方法
  7285. * @return { * } 返回每个命令特定的当前状态值
  7286. * @grammar editor.queryCommandValue(cmdName) => {*}
  7287. * @see COMMAND.LIST
  7288. */
  7289. queryCommandValue: function (cmdName) {
  7290. return this._callCmdFn('queryCommandValue', arguments);
  7291. },
  7292. /**
  7293. * 检查编辑区域中是否有内容
  7294. * @method hasContents
  7295. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7296. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7297. * @return { Boolean } 检查有内容返回true,否则返回false
  7298. * @example
  7299. * ```javascript
  7300. * editor.hasContents()
  7301. * ```
  7302. */
  7303. /**
  7304. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7305. * @method hasContents
  7306. * @param { Array } tags 传入数组判断时用到的节点类型
  7307. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7308. * @example
  7309. * ```javascript
  7310. * editor.hasContents(['span']);
  7311. * ```
  7312. */
  7313. hasContents: function (tags) {
  7314. if (tags) {
  7315. for (var i = 0, ci; ci = tags[i++];) {
  7316. if (this.document.getElementsByTagName(ci).length > 0) {
  7317. return true;
  7318. }
  7319. }
  7320. }
  7321. if (!domUtils.isEmptyBlock(this.body)) {
  7322. return true
  7323. }
  7324. //随时添加,定义的特殊标签如果存在,不能认为是空
  7325. tags = ['div'];
  7326. for (i = 0; ci = tags[i++];) {
  7327. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7328. for (var n = 0, cn; cn = nodes[n++];) {
  7329. if (domUtils.isCustomeNode(cn)) {
  7330. return true;
  7331. }
  7332. }
  7333. }
  7334. return false;
  7335. },
  7336. /**
  7337. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7338. * @method reset
  7339. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7340. * @example
  7341. * ```javascript
  7342. * editor.reset()
  7343. * ```
  7344. */
  7345. reset: function () {
  7346. this.fireEvent('reset');
  7347. },
  7348. /**
  7349. * 设置当前编辑区域可以编辑
  7350. * @method setEnabled
  7351. * @example
  7352. * ```javascript
  7353. * editor.setEnabled()
  7354. * ```
  7355. */
  7356. setEnabled: function () {
  7357. var me = this, range;
  7358. if (me.body.contentEditable == 'false') {
  7359. me.body.contentEditable = true;
  7360. range = me.selection.getRange();
  7361. //有可能内容丢失了
  7362. try {
  7363. range.moveToBookmark(me.lastBk);
  7364. delete me.lastBk
  7365. } catch (e) {
  7366. range.setStartAtFirst(me.body).collapse(true)
  7367. }
  7368. range.select(true);
  7369. if (me.bkqueryCommandState) {
  7370. me.queryCommandState = me.bkqueryCommandState;
  7371. delete me.bkqueryCommandState;
  7372. }
  7373. if (me.bkqueryCommandValue) {
  7374. me.queryCommandValue = me.bkqueryCommandValue;
  7375. delete me.bkqueryCommandValue;
  7376. }
  7377. me.fireEvent('selectionchange');
  7378. }
  7379. },
  7380. enable: function () {
  7381. return this.setEnabled();
  7382. },
  7383. /** 设置当前编辑区域不可编辑
  7384. * @method setDisabled
  7385. */
  7386. /** 设置当前编辑区域不可编辑,except中的命令除外
  7387. * @method setDisabled
  7388. * @param { String } except 例外命令的字符串
  7389. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7390. * @example
  7391. * ```javascript
  7392. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7393. * ```
  7394. */
  7395. /** 设置当前编辑区域不可编辑,except中的命令除外
  7396. * @method setDisabled
  7397. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7398. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7399. * @example
  7400. * ```javascript
  7401. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7402. * ```
  7403. */
  7404. setDisabled: function (except) {
  7405. var me = this;
  7406. except = except ? utils.isArray(except) ? except : [except] : [];
  7407. if (me.body.contentEditable == 'true') {
  7408. if (!me.lastBk) {
  7409. me.lastBk = me.selection.getRange().createBookmark(true);
  7410. }
  7411. me.body.contentEditable = false;
  7412. me.bkqueryCommandState = me.queryCommandState;
  7413. me.bkqueryCommandValue = me.queryCommandValue;
  7414. me.queryCommandState = function (type) {
  7415. if (utils.indexOf(except, type) != -1) {
  7416. return me.bkqueryCommandState.apply(me, arguments);
  7417. }
  7418. return -1;
  7419. };
  7420. me.queryCommandValue = function (type) {
  7421. if (utils.indexOf(except, type) != -1) {
  7422. return me.bkqueryCommandValue.apply(me, arguments);
  7423. }
  7424. return null;
  7425. };
  7426. me.fireEvent('selectionchange');
  7427. }
  7428. },
  7429. disable: function (except) {
  7430. return this.setDisabled(except);
  7431. },
  7432. /**
  7433. * 设置默认内容
  7434. * @method _setDefaultContent
  7435. * @private
  7436. * @param { String } cont 要存入的内容
  7437. */
  7438. _setDefaultContent: function () {
  7439. function clear() {
  7440. var me = this;
  7441. if (me.document.getElementById('initContent')) {
  7442. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7443. me.removeListener('firstBeforeExecCommand focus', clear);
  7444. setTimeout(function () {
  7445. me.focus();
  7446. me._selectionChange();
  7447. }, 0)
  7448. }
  7449. }
  7450. return function (cont) {
  7451. var me = this;
  7452. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7453. me.addListener('firstBeforeExecCommand focus', clear);
  7454. }
  7455. }(),
  7456. /**
  7457. * 显示编辑器
  7458. * @method setShow
  7459. * @example
  7460. * ```javascript
  7461. * editor.setShow()
  7462. * ```
  7463. */
  7464. setShow: function () {
  7465. var me = this, range = me.selection.getRange();
  7466. if (me.container.style.display == 'none') {
  7467. //有可能内容丢失了
  7468. try {
  7469. range.moveToBookmark(me.lastBk);
  7470. delete me.lastBk
  7471. } catch (e) {
  7472. range.setStartAtFirst(me.body).collapse(true)
  7473. }
  7474. //ie下focus实效,所以做了个延迟
  7475. setTimeout(function () {
  7476. range.select(true);
  7477. }, 100);
  7478. me.container.style.display = '';
  7479. }
  7480. },
  7481. show: function () {
  7482. return this.setShow();
  7483. },
  7484. /**
  7485. * 隐藏编辑器
  7486. * @method setHide
  7487. * @example
  7488. * ```javascript
  7489. * editor.setHide()
  7490. * ```
  7491. */
  7492. setHide: function () {
  7493. var me = this;
  7494. if (!me.lastBk) {
  7495. me.lastBk = me.selection.getRange().createBookmark(true);
  7496. }
  7497. me.container.style.display = 'none'
  7498. },
  7499. hide: function () {
  7500. return this.setHide();
  7501. },
  7502. /**
  7503. * 根据指定的路径,获取对应的语言资源
  7504. * @method getLang
  7505. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7506. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7507. * @example
  7508. * ```javascript
  7509. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7510. * ```
  7511. */
  7512. getLang: function (path) {
  7513. var lang = UE.I18N[this.options.lang];
  7514. if (!lang) {
  7515. throw Error("not import language file");
  7516. }
  7517. path = (path || "").split(".");
  7518. for (var i = 0, ci; ci = path[i++];) {
  7519. lang = lang[ci];
  7520. if (!lang)break;
  7521. }
  7522. return lang;
  7523. },
  7524. /**
  7525. * 计算编辑器html内容字符串的长度
  7526. * @method getContentLength
  7527. * @return { Number } 返回计算的长度
  7528. * @example
  7529. * ```javascript
  7530. * //编辑器html内容<p><strong>132</strong></p>
  7531. * editor.getContentLength() //返回27
  7532. * ```
  7533. */
  7534. /**
  7535. * 计算编辑器当前纯文本内容的长度
  7536. * @method getContentLength
  7537. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7538. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7539. * @example
  7540. * ```javascript
  7541. * //编辑器html内容<p><strong>132</strong></p>
  7542. * editor.getContentLength() //返回3
  7543. * ```
  7544. */
  7545. getContentLength: function (ingoneHtml, tagNames) {
  7546. var count = this.getContent(false,false,true).length;
  7547. if (ingoneHtml) {
  7548. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7549. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7550. for (var i = 0, ci; ci = tagNames[i++];) {
  7551. count += this.document.getElementsByTagName(ci).length;
  7552. }
  7553. }
  7554. return count;
  7555. },
  7556. /**
  7557. * 注册输入过滤规则
  7558. * @method addInputRule
  7559. * @param { Function } rule 要添加的过滤规则
  7560. * @example
  7561. * ```javascript
  7562. * editor.addInputRule(function(root){
  7563. * $.each(root.getNodesByTagName('div'),function(i,node){
  7564. * node.tagName="p";
  7565. * });
  7566. * });
  7567. * ```
  7568. */
  7569. addInputRule: function (rule) {
  7570. this.inputRules.push(rule);
  7571. },
  7572. /**
  7573. * 执行注册的过滤规则
  7574. * @method filterInputRule
  7575. * @param { UE.uNode } root 要过滤的uNode节点
  7576. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7577. * @example
  7578. * ```javascript
  7579. * editor.filterInputRule(editor.body);
  7580. * ```
  7581. * @see UE.Editor:addInputRule
  7582. */
  7583. filterInputRule: function (root) {
  7584. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7585. ci.call(this, root)
  7586. }
  7587. },
  7588. /**
  7589. * 注册输出过滤规则
  7590. * @method addOutputRule
  7591. * @param { Function } rule 要添加的过滤规则
  7592. * @example
  7593. * ```javascript
  7594. * editor.addOutputRule(function(root){
  7595. * $.each(root.getNodesByTagName('p'),function(i,node){
  7596. * node.tagName="div";
  7597. * });
  7598. * });
  7599. * ```
  7600. */
  7601. addOutputRule: function (rule) {
  7602. this.outputRules.push(rule)
  7603. },
  7604. /**
  7605. * 根据输出过滤规则,过滤编辑器内容
  7606. * @method filterOutputRule
  7607. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7608. * @param { UE.uNode } root 要过滤的uNode节点
  7609. * @example
  7610. * ```javascript
  7611. * editor.filterOutputRule(editor.body);
  7612. * ```
  7613. * @see UE.Editor:addOutputRule
  7614. */
  7615. filterOutputRule: function (root) {
  7616. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7617. ci.call(this, root)
  7618. }
  7619. },
  7620. /**
  7621. * 根据action名称获取请求的路径
  7622. * @method getActionUrl
  7623. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7624. * @param { String } action action名称
  7625. * @example
  7626. * ```javascript
  7627. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7628. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7629. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7630. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7631. * ```
  7632. */
  7633. getActionUrl: function(action){
  7634. var actionName = this.getOpt(action) || action,
  7635. imageUrl = this.getOpt('imageUrl'),
  7636. serverUrl = this.getOpt('serverUrl');
  7637. if(!serverUrl && imageUrl) {
  7638. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7639. }
  7640. if(serverUrl) {
  7641. serverUrl = serverUrl + (serverUrl.indexOf('?') ? '?':'&') + 'action=' + actionName;
  7642. return utils.formatUrl(serverUrl);
  7643. } else {
  7644. return '';
  7645. }
  7646. }
  7647. };
  7648. utils.inherits(Editor, EventBase);
  7649. })();
  7650. // core/loadconfig.js
  7651. (function(){
  7652. UE.Editor.prototype.loadServerConfig = function(){
  7653. var me = this;
  7654. setTimeout(function(){
  7655. try{
  7656. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7657. var configUrl = me.getActionUrl('config'),
  7658. isJsonp = utils.isCrossDomainUrl(configUrl);
  7659. /* 发出ajax请求 */
  7660. me._serverConfigLoaded = false;
  7661. configUrl && UE.ajax.request(configUrl,{
  7662. 'method': 'GET',
  7663. 'dataType': isJsonp ? 'jsonp':'',
  7664. 'onsuccess':function(r){
  7665. try {
  7666. var config = isJsonp ? r:eval("("+r.responseText+")");
  7667. utils.extend(me.options, config);
  7668. me.fireEvent('serverConfigLoaded');
  7669. me._serverConfigLoaded = true;
  7670. } catch (e) {
  7671. console && console.error('后台配置项返回出错!');
  7672. }
  7673. },
  7674. 'onerror':function(){
  7675. console && console.error('获取后台配置项出错!');
  7676. }
  7677. });
  7678. } catch(e){
  7679. console && console.log('获取后台配置项请求出错!');
  7680. }
  7681. });
  7682. };
  7683. UE.Editor.prototype.isServerConfigLoaded = function(){
  7684. var me = this;
  7685. return me._serverConfigLoaded || false;
  7686. };
  7687. UE.Editor.prototype.afterConfigReady = function(handler){
  7688. if (!handler || !utils.isFunction(handler)) return;
  7689. var me = this;
  7690. var readyHandler = function(){
  7691. handler.apply(me, arguments);
  7692. me.removeListener('serverConfigLoaded', readyHandler);
  7693. };
  7694. if (me.isServerConfigLoaded()) {
  7695. handler.call(me, 'serverConfigLoaded');
  7696. } else {
  7697. me.addListener('serverConfigLoaded', readyHandler);
  7698. }
  7699. };
  7700. })();
  7701. // core/ajax.js
  7702. /**
  7703. * @file
  7704. * @module UE.ajax
  7705. * @since 1.2.6.1
  7706. */
  7707. /**
  7708. * 提供对ajax请求的支持
  7709. * @module UE.ajax
  7710. */
  7711. UE.ajax = function() {
  7712. //创建一个ajaxRequest对象
  7713. var fnStr = 'XMLHttpRequest()';
  7714. try {
  7715. new ActiveXObject("Msxml2.XMLHTTP");
  7716. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7717. } catch (e) {
  7718. try {
  7719. new ActiveXObject("Microsoft.XMLHTTP");
  7720. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7721. } catch (e) {
  7722. }
  7723. }
  7724. var creatAjaxRequest = new Function('return new ' + fnStr);
  7725. /**
  7726. * 将json参数转化成适合ajax提交的参数列表
  7727. * @param json
  7728. */
  7729. function json2str(json) {
  7730. var strArr = [];
  7731. for (var i in json) {
  7732. //忽略默认的几个参数
  7733. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7734. //忽略控制
  7735. if(json[i] == undefined || json[i] == null) continue;
  7736. //传递过来的对象和函数不在提交之列
  7737. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7738. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7739. } else if (utils.isArray(json[i])) {
  7740. //支持传数组内容
  7741. for(var j = 0; j < json[i].length; j++) {
  7742. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7743. }
  7744. }
  7745. }
  7746. return strArr.join("&");
  7747. }
  7748. function doAjax(url, ajaxOptions) {
  7749. var xhr = creatAjaxRequest(),
  7750. //是否超时
  7751. timeIsOut = false,
  7752. //默认参数
  7753. defaultAjaxOptions = {
  7754. method:"POST",
  7755. timeout:5000,
  7756. async:true,
  7757. data:{},//需要传递对象的话只能覆盖
  7758. onsuccess:function() {
  7759. },
  7760. onerror:function() {
  7761. }
  7762. };
  7763. if (typeof url === "object") {
  7764. ajaxOptions = url;
  7765. url = ajaxOptions.url;
  7766. }
  7767. if (!xhr || !url) return;
  7768. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7769. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7770. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7771. if (!utils.isEmptyObject(ajaxOpts.data)){
  7772. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7773. }
  7774. //超时检测
  7775. var timerID = setTimeout(function() {
  7776. if (xhr.readyState != 4) {
  7777. timeIsOut = true;
  7778. xhr.abort();
  7779. clearTimeout(timerID);
  7780. }
  7781. }, ajaxOpts.timeout);
  7782. var method = ajaxOpts.method.toUpperCase();
  7783. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7784. xhr.open(method, str, ajaxOpts.async);
  7785. xhr.onreadystatechange = function() {
  7786. if (xhr.readyState == 4) {
  7787. if (!timeIsOut && xhr.status == 200) {
  7788. ajaxOpts.onsuccess(xhr);
  7789. } else {
  7790. ajaxOpts.onerror(xhr);
  7791. }
  7792. }
  7793. };
  7794. if (method == "POST") {
  7795. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7796. xhr.send(submitStr);
  7797. } else {
  7798. xhr.send(null);
  7799. }
  7800. }
  7801. function doJsonp(url, opts) {
  7802. var successhandler = opts.onsuccess || function(){},
  7803. scr = document.createElement('SCRIPT'),
  7804. options = opts || {},
  7805. charset = options['charset'],
  7806. callbackField = options['jsonp'] || 'callback',
  7807. callbackFnName,
  7808. timeOut = options['timeOut'] || 0,
  7809. timer,
  7810. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7811. matches;
  7812. if (utils.isFunction(successhandler)) {
  7813. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7814. window[callbackFnName] = getCallBack(0);
  7815. } else if(utils.isString(successhandler)){
  7816. callbackFnName = successhandler;
  7817. } else {
  7818. if (matches = reg.exec(url)) {
  7819. callbackFnName = matches[2];
  7820. }
  7821. }
  7822. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7823. if (url.search(reg) < 0) {
  7824. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7825. }
  7826. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7827. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7828. if (!utils.isEmptyObject(opts.data)){
  7829. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7830. }
  7831. if (queryStr) {
  7832. url = url.replace(/\?/, '?' + queryStr + '&');
  7833. }
  7834. scr.onerror = getCallBack(1);
  7835. if( timeOut ){
  7836. timer = setTimeout(getCallBack(1), timeOut);
  7837. }
  7838. createScriptTag(scr, url, charset);
  7839. function createScriptTag(scr, url, charset) {
  7840. scr.setAttribute('type', 'text/javascript');
  7841. scr.setAttribute('defer', 'defer');
  7842. charset && scr.setAttribute('charset', charset);
  7843. scr.setAttribute('src', url);
  7844. document.getElementsByTagName('head')[0].appendChild(scr);
  7845. }
  7846. function getCallBack(onTimeOut){
  7847. return function(){
  7848. try {
  7849. if(onTimeOut){
  7850. options.onerror && options.onerror();
  7851. }else{
  7852. try{
  7853. clearTimeout(timer);
  7854. successhandler.apply(window, arguments);
  7855. } catch (e){}
  7856. }
  7857. } catch (exception) {
  7858. options.onerror && options.onerror.call(window, exception);
  7859. } finally {
  7860. options.oncomplete && options.oncomplete.apply(window, arguments);
  7861. scr.parentNode && scr.parentNode.removeChild(scr);
  7862. window[callbackFnName] = null;
  7863. try {
  7864. delete window[callbackFnName];
  7865. }catch(e){}
  7866. }
  7867. }
  7868. }
  7869. }
  7870. return {
  7871. /**
  7872. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7873. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7874. * @method request
  7875. * @param { URLString } url ajax请求的url地址
  7876. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7877. * @example
  7878. * ```javascript
  7879. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7880. * UE.ajax.requeset( 'sayhello.php', {
  7881. *
  7882. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7883. * method: 'GET',
  7884. *
  7885. * //超时时间。 默认为5000, 单位是ms
  7886. * timeout: 10000,
  7887. *
  7888. * //是否是异步请求。 true为异步请求, false为同步请求
  7889. * async: true,
  7890. *
  7891. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7892. * data: {
  7893. * name: 'ueditor'
  7894. * },
  7895. *
  7896. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7897. * onsuccess: function ( xhr ) {
  7898. * console.log( xhr.responseText );
  7899. * },
  7900. *
  7901. * //请求失败或者超时后的回调。
  7902. * onerror: function ( xhr ) {
  7903. * alert( 'Ajax请求失败' );
  7904. * }
  7905. *
  7906. * } );
  7907. * ```
  7908. */
  7909. /**
  7910. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7911. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7912. * @method request
  7913. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7914. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7915. * @example
  7916. * ```javascript
  7917. *
  7918. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7919. * UE.ajax.requeset( 'sayhello.php', {
  7920. *
  7921. * //请求的地址, 该项是必须的。
  7922. * url: 'sayhello.php'
  7923. *
  7924. * } );
  7925. * ```
  7926. */
  7927. request:function(url, opts) {
  7928. if (opts && opts.dataType == 'jsonp') {
  7929. doJsonp(url, opts);
  7930. } else {
  7931. doAjax(url, opts);
  7932. }
  7933. },
  7934. getJSONP:function(url, data, fn) {
  7935. var opts = {
  7936. 'data': data,
  7937. 'oncomplete': fn
  7938. };
  7939. doJsonp(url, opts);
  7940. }
  7941. };
  7942. }();
  7943. // core/filterword.js
  7944. /**
  7945. * UE过滤word的静态方法
  7946. * @file
  7947. */
  7948. /**
  7949. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7950. * @module UE
  7951. */
  7952. /**
  7953. * 根据传入html字符串过滤word
  7954. * @module UE
  7955. * @since 1.2.6.1
  7956. * @method filterWord
  7957. * @param { String } html html字符串
  7958. * @return { String } 已过滤后的结果字符串
  7959. * @example
  7960. * ```javascript
  7961. * UE.filterWord(html);
  7962. * ```
  7963. */
  7964. var filterWord = UE.filterWord = function () {
  7965. //是否是word过来的内容
  7966. function isWordDocument( str ) {
  7967. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  7968. }
  7969. //去掉小数
  7970. function transUnit( v ) {
  7971. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  7972. return utils.transUnitToPx(m);
  7973. } );
  7974. return v;
  7975. }
  7976. function filterPasteWord( str ) {
  7977. return str.replace(/[\t\r\n]+/g,' ')
  7978. .replace( /<!--[\s\S]*?-->/ig, "" )
  7979. //转换图片
  7980. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  7981. //opera能自己解析出image所这里直接返回空
  7982. if(browser.opera){
  7983. return '';
  7984. }
  7985. try{
  7986. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  7987. if(/Bitmap/i.test(str)){
  7988. return '';
  7989. }
  7990. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  7991. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  7992. src = str.match(/src=\s*"([^"]*)"/i)[1];
  7993. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  7994. } catch(e){
  7995. return '';
  7996. }
  7997. })
  7998. //针对wps添加的多余标签处理
  7999. .replace(/<\/?div[^>]*>/g,'')
  8000. //去掉多余的属性
  8001. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8002. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8003. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8004. //去掉多余的属性
  8005. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8006. //保留list的标示
  8007. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8008. })
  8009. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8010. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8011. return c.replace(/[\t\r\n ]+/g,' ')
  8012. })
  8013. //处理style的问题
  8014. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8015. var n = [],
  8016. s = style.replace( /^\s+|\s+$/, '' )
  8017. .replace(/&#39;/g,'\'')
  8018. .replace( /&quot;/gi, "'" )
  8019. .split( /;\s*/g );
  8020. for ( var i = 0,v; v = s[i];i++ ) {
  8021. var name, value,
  8022. parts = v.split( ":" );
  8023. if ( parts.length == 2 ) {
  8024. name = parts[0].toLowerCase();
  8025. value = parts[1].toLowerCase();
  8026. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8027. ||
  8028. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8029. ){
  8030. continue;
  8031. }
  8032. switch ( name ) {
  8033. case "mso-padding-alt":
  8034. case "mso-padding-top-alt":
  8035. case "mso-padding-right-alt":
  8036. case "mso-padding-bottom-alt":
  8037. case "mso-padding-left-alt":
  8038. case "mso-margin-alt":
  8039. case "mso-margin-top-alt":
  8040. case "mso-margin-right-alt":
  8041. case "mso-margin-bottom-alt":
  8042. case "mso-margin-left-alt":
  8043. //ie下会出现挤到一起的情况
  8044. //case "mso-table-layout-alt":
  8045. case "mso-height":
  8046. case "mso-width":
  8047. case "mso-vertical-align-alt":
  8048. //trace:1819 ff下会解析出padding在table上
  8049. if(!/<table/.test(tag))
  8050. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8051. continue;
  8052. case "horiz-align":
  8053. n[i] = "text-align:" + value;
  8054. continue;
  8055. case "vert-align":
  8056. n[i] = "vertical-align:" + value;
  8057. continue;
  8058. case "font-color":
  8059. case "mso-foreground":
  8060. n[i] = "color:" + value;
  8061. continue;
  8062. case "mso-background":
  8063. case "mso-highlight":
  8064. n[i] = "background:" + value;
  8065. continue;
  8066. case "mso-default-height":
  8067. n[i] = "min-height:" + transUnit( value );
  8068. continue;
  8069. case "mso-default-width":
  8070. n[i] = "min-width:" + transUnit( value );
  8071. continue;
  8072. case "mso-padding-between-alt":
  8073. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8074. continue;
  8075. case "text-line-through":
  8076. if ( (value == "single") || (value == "double") ) {
  8077. n[i] = "text-decoration:line-through";
  8078. }
  8079. continue;
  8080. case "mso-zero-height":
  8081. if ( value == "yes" ) {
  8082. n[i] = "display:none";
  8083. }
  8084. continue;
  8085. // case 'background':
  8086. // break;
  8087. case 'margin':
  8088. if ( !/[1-9]/.test( value ) ) {
  8089. continue;
  8090. }
  8091. }
  8092. 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 )
  8093. ||
  8094. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8095. ) {
  8096. continue;
  8097. }
  8098. n[i] = name + ":" + parts[1];
  8099. }
  8100. }
  8101. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8102. })
  8103. .replace(/[\d.]+(cm|pt)/g,function(str){
  8104. return utils.transUnitToPx(str)
  8105. })
  8106. }
  8107. return function ( html ) {
  8108. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8109. };
  8110. }();
  8111. // core/node.js
  8112. /**
  8113. * 编辑器模拟的节点类
  8114. * @file
  8115. * @module UE
  8116. * @class uNode
  8117. * @since 1.2.6.1
  8118. */
  8119. /**
  8120. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8121. * @unfile
  8122. * @module UE
  8123. */
  8124. (function () {
  8125. /**
  8126. * 编辑器模拟的节点类
  8127. * @unfile
  8128. * @module UE
  8129. * @class uNode
  8130. */
  8131. /**
  8132. * 通过一个键值对,创建一个uNode对象
  8133. * @constructor
  8134. * @param { Object } attr 传入要创建的uNode的初始属性
  8135. * @example
  8136. * ```javascript
  8137. * var node = new uNode({
  8138. * type:'element',
  8139. * tagName:'span',
  8140. * attrs:{style:'font-size:14px;'}
  8141. * }
  8142. * ```
  8143. */
  8144. var uNode = UE.uNode = function (obj) {
  8145. this.type = obj.type;
  8146. this.data = obj.data;
  8147. this.tagName = obj.tagName;
  8148. this.parentNode = obj.parentNode;
  8149. this.attrs = obj.attrs || {};
  8150. this.children = obj.children;
  8151. };
  8152. var notTransAttrs = {
  8153. 'href':1,
  8154. 'src':1,
  8155. '_src':1,
  8156. '_href':1,
  8157. 'cdata_data':1
  8158. };
  8159. var notTransTagName = {
  8160. style:1,
  8161. script:1
  8162. };
  8163. var indentChar = ' ',
  8164. breakChar = '\n';
  8165. function insertLine(arr, current, begin) {
  8166. arr.push(breakChar);
  8167. return current + (begin ? 1 : -1);
  8168. }
  8169. function insertIndent(arr, current) {
  8170. //插入缩进
  8171. for (var i = 0; i < current; i++) {
  8172. arr.push(indentChar);
  8173. }
  8174. }
  8175. //创建uNode的静态方法
  8176. //支持标签和html
  8177. uNode.createElement = function (html) {
  8178. if (/[<>]/.test(html)) {
  8179. return UE.htmlparser(html).children[0]
  8180. } else {
  8181. return new uNode({
  8182. type:'element',
  8183. children:[],
  8184. tagName:html
  8185. })
  8186. }
  8187. };
  8188. uNode.createText = function (data,noTrans) {
  8189. return new UE.uNode({
  8190. type:'text',
  8191. 'data':noTrans ? data : utils.unhtml(data || '')
  8192. })
  8193. };
  8194. function nodeToHtml(node, arr, formatter, current) {
  8195. switch (node.type) {
  8196. case 'root':
  8197. for (var i = 0, ci; ci = node.children[i++];) {
  8198. //插入新行
  8199. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8200. insertLine(arr, current, true);
  8201. insertIndent(arr, current)
  8202. }
  8203. nodeToHtml(ci, arr, formatter, current)
  8204. }
  8205. break;
  8206. case 'text':
  8207. isText(node, arr);
  8208. break;
  8209. case 'element':
  8210. isElement(node, arr, formatter, current);
  8211. break;
  8212. case 'comment':
  8213. isComment(node, arr, formatter);
  8214. }
  8215. return arr;
  8216. }
  8217. function isText(node, arr) {
  8218. if(node.parentNode.tagName == 'pre'){
  8219. //源码模式下输入html标签,不能做转换处理,直接输出
  8220. arr.push(node.data)
  8221. }else{
  8222. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8223. }
  8224. }
  8225. function isElement(node, arr, formatter, current) {
  8226. var attrhtml = '';
  8227. if (node.attrs) {
  8228. attrhtml = [];
  8229. var attrs = node.attrs;
  8230. for (var a in attrs) {
  8231. //这里就针对
  8232. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8233. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8234. //有可能做的不够
  8235. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8236. return '&quot;'
  8237. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8238. }
  8239. attrhtml = attrhtml.join(' ');
  8240. }
  8241. arr.push('<' + node.tagName +
  8242. (attrhtml ? ' ' + attrhtml : '') +
  8243. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8244. );
  8245. //插入新行
  8246. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8247. if(node.children && node.children.length){
  8248. current = insertLine(arr, current, true);
  8249. insertIndent(arr, current)
  8250. }
  8251. }
  8252. if (node.children && node.children.length) {
  8253. for (var i = 0, ci; ci = node.children[i++];) {
  8254. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8255. insertLine(arr, current);
  8256. insertIndent(arr, current)
  8257. }
  8258. nodeToHtml(ci, arr, formatter, current)
  8259. }
  8260. }
  8261. if (!dtd.$empty[node.tagName]) {
  8262. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8263. if(node.children && node.children.length){
  8264. current = insertLine(arr, current);
  8265. insertIndent(arr, current)
  8266. }
  8267. }
  8268. arr.push('<\/' + node.tagName + '>');
  8269. }
  8270. }
  8271. function isComment(node, arr) {
  8272. arr.push('<!--' + node.data + '-->');
  8273. }
  8274. function getNodeById(root, id) {
  8275. var node;
  8276. if (root.type == 'element' && root.getAttr('id') == id) {
  8277. return root;
  8278. }
  8279. if (root.children && root.children.length) {
  8280. for (var i = 0, ci; ci = root.children[i++];) {
  8281. if (node = getNodeById(ci, id)) {
  8282. return node;
  8283. }
  8284. }
  8285. }
  8286. }
  8287. function getNodesByTagName(node, tagName, arr) {
  8288. if (node.type == 'element' && node.tagName == tagName) {
  8289. arr.push(node);
  8290. }
  8291. if (node.children && node.children.length) {
  8292. for (var i = 0, ci; ci = node.children[i++];) {
  8293. getNodesByTagName(ci, tagName, arr)
  8294. }
  8295. }
  8296. }
  8297. function nodeTraversal(root,fn){
  8298. if(root.children && root.children.length){
  8299. for(var i= 0,ci;ci=root.children[i];){
  8300. nodeTraversal(ci,fn);
  8301. //ci被替换的情况,这里就不再走 fn了
  8302. if(ci.parentNode ){
  8303. if(ci.children && ci.children.length){
  8304. fn(ci)
  8305. }
  8306. if(ci.parentNode) i++
  8307. }
  8308. }
  8309. }else{
  8310. fn(root)
  8311. }
  8312. }
  8313. uNode.prototype = {
  8314. /**
  8315. * 当前节点对象,转换成html文本
  8316. * @method toHtml
  8317. * @return { String } 返回转换后的html字符串
  8318. * @example
  8319. * ```javascript
  8320. * node.toHtml();
  8321. * ```
  8322. */
  8323. /**
  8324. * 当前节点对象,转换成html文本
  8325. * @method toHtml
  8326. * @param { Boolean } formatter 是否格式化返回值
  8327. * @return { String } 返回转换后的html字符串
  8328. * @example
  8329. * ```javascript
  8330. * node.toHtml( true );
  8331. * ```
  8332. */
  8333. toHtml:function (formatter) {
  8334. var arr = [];
  8335. nodeToHtml(this, arr, formatter, 0);
  8336. return arr.join('')
  8337. },
  8338. /**
  8339. * 获取节点的html内容
  8340. * @method innerHTML
  8341. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8342. * @return { String } 返回节点的html内容
  8343. * @example
  8344. * ```javascript
  8345. * var htmlstr = node.innerHTML();
  8346. * ```
  8347. */
  8348. /**
  8349. * 设置节点的html内容
  8350. * @method innerHTML
  8351. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8352. * @param { String } htmlstr 传入要设置的html内容
  8353. * @return { UE.uNode } 返回节点本身
  8354. * @example
  8355. * ```javascript
  8356. * node.innerHTML('<span>text</span>');
  8357. * ```
  8358. */
  8359. innerHTML:function (htmlstr) {
  8360. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8361. return this;
  8362. }
  8363. if (utils.isString(htmlstr)) {
  8364. if(this.children){
  8365. for (var i = 0, ci; ci = this.children[i++];) {
  8366. ci.parentNode = null;
  8367. }
  8368. }
  8369. this.children = [];
  8370. var tmpRoot = UE.htmlparser(htmlstr);
  8371. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8372. this.children.push(ci);
  8373. ci.parentNode = this;
  8374. }
  8375. return this;
  8376. } else {
  8377. var tmpRoot = new UE.uNode({
  8378. type:'root',
  8379. children:this.children
  8380. });
  8381. return tmpRoot.toHtml();
  8382. }
  8383. },
  8384. /**
  8385. * 获取节点的纯文本内容
  8386. * @method innerText
  8387. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8388. * @return { String } 返回节点的存文本内容
  8389. * @example
  8390. * ```javascript
  8391. * var textStr = node.innerText();
  8392. * ```
  8393. */
  8394. /**
  8395. * 设置节点的纯文本内容
  8396. * @method innerText
  8397. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8398. * @param { String } textStr 传入要设置的文本内容
  8399. * @return { UE.uNode } 返回节点本身
  8400. * @example
  8401. * ```javascript
  8402. * node.innerText('<span>text</span>');
  8403. * ```
  8404. */
  8405. innerText:function (textStr,noTrans) {
  8406. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8407. return this;
  8408. }
  8409. if (textStr) {
  8410. if(this.children){
  8411. for (var i = 0, ci; ci = this.children[i++];) {
  8412. ci.parentNode = null;
  8413. }
  8414. }
  8415. this.children = [];
  8416. this.appendChild(uNode.createText(textStr,noTrans));
  8417. return this;
  8418. } else {
  8419. return this.toHtml().replace(/<[^>]+>/g, '');
  8420. }
  8421. },
  8422. /**
  8423. * 获取当前对象的data属性
  8424. * @method getData
  8425. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8426. * @example
  8427. * ```javascript
  8428. * node.getData();
  8429. * ```
  8430. */
  8431. getData:function () {
  8432. if (this.type == 'element')
  8433. return '';
  8434. return this.data
  8435. },
  8436. /**
  8437. * 获取当前节点下的第一个子节点
  8438. * @method firstChild
  8439. * @return { UE.uNode } 返回第一个子节点
  8440. * @example
  8441. * ```javascript
  8442. * node.firstChild(); //返回第一个子节点
  8443. * ```
  8444. */
  8445. firstChild:function () {
  8446. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8447. // return this;
  8448. // }
  8449. return this.children ? this.children[0] : null;
  8450. },
  8451. /**
  8452. * 获取当前节点下的最后一个子节点
  8453. * @method lastChild
  8454. * @return { UE.uNode } 返回最后一个子节点
  8455. * @example
  8456. * ```javascript
  8457. * node.lastChild(); //返回最后一个子节点
  8458. * ```
  8459. */
  8460. lastChild:function () {
  8461. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8462. // return this;
  8463. // }
  8464. return this.children ? this.children[this.children.length - 1] : null;
  8465. },
  8466. /**
  8467. * 获取和当前节点有相同父亲节点的前一个节点
  8468. * @method previousSibling
  8469. * @return { UE.uNode } 返回前一个节点
  8470. * @example
  8471. * ```javascript
  8472. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8473. * ```
  8474. */
  8475. previousSibling : function(){
  8476. var parent = this.parentNode;
  8477. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8478. if (ci === this) {
  8479. return i == 0 ? null : parent.children[i-1];
  8480. }
  8481. }
  8482. },
  8483. /**
  8484. * 获取和当前节点有相同父亲节点的后一个节点
  8485. * @method nextSibling
  8486. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8487. * @example
  8488. * ```javascript
  8489. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8490. * ```
  8491. */
  8492. nextSibling : function(){
  8493. var parent = this.parentNode;
  8494. for (var i = 0, ci; ci = parent.children[i++];) {
  8495. if (ci === this) {
  8496. return parent.children[i];
  8497. }
  8498. }
  8499. },
  8500. /**
  8501. * 用新的节点替换当前节点
  8502. * @method replaceChild
  8503. * @param { UE.uNode } target 要替换成该节点参数
  8504. * @param { UE.uNode } source 要被替换掉的节点
  8505. * @return { UE.uNode } 返回替换之后的节点对象
  8506. * @example
  8507. * ```javascript
  8508. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8509. * ```
  8510. */
  8511. replaceChild:function (target, source) {
  8512. if (this.children) {
  8513. if(target.parentNode){
  8514. target.parentNode.removeChild(target);
  8515. }
  8516. for (var i = 0, ci; ci = this.children[i]; i++) {
  8517. if (ci === source) {
  8518. this.children.splice(i, 1, target);
  8519. source.parentNode = null;
  8520. target.parentNode = this;
  8521. return target;
  8522. }
  8523. }
  8524. }
  8525. },
  8526. /**
  8527. * 在节点的子节点列表最后位置插入一个节点
  8528. * @method appendChild
  8529. * @param { UE.uNode } node 要插入的节点
  8530. * @return { UE.uNode } 返回刚插入的子节点
  8531. * @example
  8532. * ```javascript
  8533. * node.appendChild( newNode ); //在node内插入子节点newNode
  8534. * ```
  8535. */
  8536. appendChild:function (node) {
  8537. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8538. if (!this.children) {
  8539. this.children = []
  8540. }
  8541. if(node.parentNode){
  8542. node.parentNode.removeChild(node);
  8543. }
  8544. for (var i = 0, ci; ci = this.children[i]; i++) {
  8545. if (ci === node) {
  8546. this.children.splice(i, 1);
  8547. break;
  8548. }
  8549. }
  8550. this.children.push(node);
  8551. node.parentNode = this;
  8552. return node;
  8553. }
  8554. },
  8555. /**
  8556. * 在传入节点的前面插入一个节点
  8557. * @method insertBefore
  8558. * @param { UE.uNode } target 要插入的节点
  8559. * @param { UE.uNode } source 在该参数节点前面插入
  8560. * @return { UE.uNode } 返回刚插入的子节点
  8561. * @example
  8562. * ```javascript
  8563. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8564. * ```
  8565. */
  8566. insertBefore:function (target, source) {
  8567. if (this.children) {
  8568. if(target.parentNode){
  8569. target.parentNode.removeChild(target);
  8570. }
  8571. for (var i = 0, ci; ci = this.children[i]; i++) {
  8572. if (ci === source) {
  8573. this.children.splice(i, 0, target);
  8574. target.parentNode = this;
  8575. return target;
  8576. }
  8577. }
  8578. }
  8579. },
  8580. /**
  8581. * 在传入节点的后面插入一个节点
  8582. * @method insertAfter
  8583. * @param { UE.uNode } target 要插入的节点
  8584. * @param { UE.uNode } source 在该参数节点后面插入
  8585. * @return { UE.uNode } 返回刚插入的子节点
  8586. * @example
  8587. * ```javascript
  8588. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8589. * ```
  8590. */
  8591. insertAfter:function (target, source) {
  8592. if (this.children) {
  8593. if(target.parentNode){
  8594. target.parentNode.removeChild(target);
  8595. }
  8596. for (var i = 0, ci; ci = this.children[i]; i++) {
  8597. if (ci === source) {
  8598. this.children.splice(i + 1, 0, target);
  8599. target.parentNode = this;
  8600. return target;
  8601. }
  8602. }
  8603. }
  8604. },
  8605. /**
  8606. * 从当前节点的子节点列表中,移除节点
  8607. * @method removeChild
  8608. * @param { UE.uNode } node 要移除的节点引用
  8609. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8610. * @return { * } 返回刚移除的子节点
  8611. * @example
  8612. * ```javascript
  8613. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8614. * ```
  8615. */
  8616. removeChild:function (node,keepChildren) {
  8617. if (this.children) {
  8618. for (var i = 0, ci; ci = this.children[i]; i++) {
  8619. if (ci === node) {
  8620. this.children.splice(i, 1);
  8621. ci.parentNode = null;
  8622. if(keepChildren && ci.children && ci.children.length){
  8623. for(var j= 0,cj;cj=ci.children[j];j++){
  8624. this.children.splice(i+j,0,cj);
  8625. cj.parentNode = this;
  8626. }
  8627. }
  8628. return ci;
  8629. }
  8630. }
  8631. }
  8632. },
  8633. /**
  8634. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8635. * @method getAttr
  8636. * @param { String } attrName 要获取的属性名称
  8637. * @return { * } 返回attrs对象下的属性值
  8638. * @example
  8639. * ```javascript
  8640. * node.getAttr('title');
  8641. * ```
  8642. */
  8643. getAttr:function (attrName) {
  8644. return this.attrs && this.attrs[attrName.toLowerCase()]
  8645. },
  8646. /**
  8647. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8648. * @method setAttr
  8649. * @param { String } attrName 要设置的属性名称
  8650. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8651. * @return { * } 返回attrs对象下的属性值
  8652. * @example
  8653. * ```javascript
  8654. * node.setAttr('title','标题');
  8655. * ```
  8656. */
  8657. setAttr:function (attrName, attrVal) {
  8658. if (!attrName) {
  8659. delete this.attrs;
  8660. return;
  8661. }
  8662. if(!this.attrs){
  8663. this.attrs = {};
  8664. }
  8665. if (utils.isObject(attrName)) {
  8666. for (var a in attrName) {
  8667. if (!attrName[a]) {
  8668. delete this.attrs[a]
  8669. } else {
  8670. this.attrs[a.toLowerCase()] = attrName[a];
  8671. }
  8672. }
  8673. } else {
  8674. if (!attrVal) {
  8675. delete this.attrs[attrName]
  8676. } else {
  8677. this.attrs[attrName.toLowerCase()] = attrVal;
  8678. }
  8679. }
  8680. },
  8681. /**
  8682. * 获取当前节点在父节点下的位置索引
  8683. * @method getIndex
  8684. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8685. * @example
  8686. * ```javascript
  8687. * node.getIndex();
  8688. * ```
  8689. */
  8690. getIndex:function(){
  8691. var parent = this.parentNode;
  8692. for(var i= 0,ci;ci=parent.children[i];i++){
  8693. if(ci === this){
  8694. return i;
  8695. }
  8696. }
  8697. return -1;
  8698. },
  8699. /**
  8700. * 在当前节点下,根据id查找节点
  8701. * @method getNodeById
  8702. * @param { String } id 要查找的id
  8703. * @return { UE.uNode } 返回找到的节点
  8704. * @example
  8705. * ```javascript
  8706. * node.getNodeById('textId');
  8707. * ```
  8708. */
  8709. getNodeById:function (id) {
  8710. var node;
  8711. if (this.children && this.children.length) {
  8712. for (var i = 0, ci; ci = this.children[i++];) {
  8713. if (node = getNodeById(ci, id)) {
  8714. return node;
  8715. }
  8716. }
  8717. }
  8718. },
  8719. /**
  8720. * 在当前节点下,根据元素名称查找节点列表
  8721. * @method getNodesByTagName
  8722. * @param { String } tagNames 要查找的元素名称
  8723. * @return { Array } 返回找到的节点列表
  8724. * @example
  8725. * ```javascript
  8726. * node.getNodesByTagName('span');
  8727. * ```
  8728. */
  8729. getNodesByTagName:function (tagNames) {
  8730. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8731. var arr = [], me = this;
  8732. utils.each(tagNames, function (tagName) {
  8733. if (me.children && me.children.length) {
  8734. for (var i = 0, ci; ci = me.children[i++];) {
  8735. getNodesByTagName(ci, tagName, arr)
  8736. }
  8737. }
  8738. });
  8739. return arr;
  8740. },
  8741. /**
  8742. * 根据样式名称,获取节点的样式值
  8743. * @method getStyle
  8744. * @param { String } name 要获取的样式名称
  8745. * @return { String } 返回样式值
  8746. * @example
  8747. * ```javascript
  8748. * node.getStyle('font-size');
  8749. * ```
  8750. */
  8751. getStyle:function (name) {
  8752. var cssStyle = this.getAttr('style');
  8753. if (!cssStyle) {
  8754. return ''
  8755. }
  8756. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8757. var match = cssStyle.match(reg);
  8758. if (match && match[0]) {
  8759. return match[2]
  8760. }
  8761. return '';
  8762. },
  8763. /**
  8764. * 给节点设置样式
  8765. * @method setStyle
  8766. * @param { String } name 要设置的的样式名称
  8767. * @param { String } val 要设置的的样值
  8768. * @example
  8769. * ```javascript
  8770. * node.setStyle('font-size', '12px');
  8771. * ```
  8772. */
  8773. setStyle:function (name, val) {
  8774. function exec(name, val) {
  8775. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8776. cssStyle = cssStyle.replace(reg, '$1');
  8777. if (val) {
  8778. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8779. }
  8780. }
  8781. var cssStyle = this.getAttr('style');
  8782. if (!cssStyle) {
  8783. cssStyle = '';
  8784. }
  8785. if (utils.isObject(name)) {
  8786. for (var a in name) {
  8787. exec(a, name[a])
  8788. }
  8789. } else {
  8790. exec(name, val)
  8791. }
  8792. this.setAttr('style', utils.trim(cssStyle))
  8793. },
  8794. /**
  8795. * 传入一个函数,递归遍历当前节点下的所有节点
  8796. * @method traversal
  8797. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8798. * @example
  8799. * ```javascript
  8800. * traversal(node, function(){
  8801. * console.log(node.type);
  8802. * });
  8803. * ```
  8804. */
  8805. traversal:function(fn){
  8806. if(this.children && this.children.length){
  8807. nodeTraversal(this,fn);
  8808. }
  8809. return this;
  8810. }
  8811. }
  8812. })();
  8813. // core/htmlparser.js
  8814. /**
  8815. * html字符串转换成uNode节点
  8816. * @file
  8817. * @module UE
  8818. * @since 1.2.6.1
  8819. */
  8820. /**
  8821. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8822. * @unfile
  8823. * @module UE
  8824. */
  8825. /**
  8826. * html字符串转换成uNode节点的静态方法
  8827. * @method htmlparser
  8828. * @param { String } htmlstr 要转换的html代码
  8829. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8830. * @return { uNode } 给定的html片段转换形成的uNode对象
  8831. * @example
  8832. * ```javascript
  8833. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8834. * ```
  8835. */
  8836. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8837. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8838. //先去掉了,加上的原因忘了,这里先记录
  8839. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8840. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8841. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8842. var allowEmptyTags = {
  8843. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8844. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8845. };
  8846. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8847. if(!ignoreBlank){
  8848. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8849. //br暂时单独处理
  8850. if(b && allowEmptyTags[b.toLowerCase()]){
  8851. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8852. }
  8853. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8854. });
  8855. }
  8856. var notTransAttrs = {
  8857. 'href':1,
  8858. 'src':1
  8859. };
  8860. var uNode = UE.uNode,
  8861. needParentNode = {
  8862. 'td':'tr',
  8863. 'tr':['tbody','thead','tfoot'],
  8864. 'tbody':'table',
  8865. 'th':'tr',
  8866. 'thead':'table',
  8867. 'tfoot':'table',
  8868. 'caption':'table',
  8869. 'li':['ul', 'ol'],
  8870. 'dt':'dl',
  8871. 'dd':'dl',
  8872. 'option':'select'
  8873. },
  8874. needChild = {
  8875. 'ol':'li',
  8876. 'ul':'li'
  8877. };
  8878. function text(parent, data) {
  8879. if(needChild[parent.tagName]){
  8880. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8881. parent.appendChild(tmpNode);
  8882. tmpNode.appendChild(uNode.createText(data));
  8883. parent = tmpNode;
  8884. }else{
  8885. parent.appendChild(uNode.createText(data));
  8886. }
  8887. }
  8888. function element(parent, tagName, htmlattr) {
  8889. var needParentTag;
  8890. if (needParentTag = needParentNode[tagName]) {
  8891. var tmpParent = parent,hasParent;
  8892. while(tmpParent.type != 'root'){
  8893. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8894. parent = tmpParent;
  8895. hasParent = true;
  8896. break;
  8897. }
  8898. tmpParent = tmpParent.parentNode;
  8899. }
  8900. if(!hasParent){
  8901. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8902. }
  8903. }
  8904. //按dtd处理嵌套
  8905. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8906. // parent = parent.parentNode;
  8907. var elm = new uNode({
  8908. parentNode:parent,
  8909. type:'element',
  8910. tagName:tagName.toLowerCase(),
  8911. //是自闭合的处理一下
  8912. children:dtd.$empty[tagName] ? null : []
  8913. });
  8914. //如果属性存在,处理属性
  8915. if (htmlattr) {
  8916. var attrs = {}, match;
  8917. while (match = re_attr.exec(htmlattr)) {
  8918. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8919. }
  8920. elm.attrs = attrs;
  8921. }
  8922. //trace:3970
  8923. // //如果parent下不能放elm
  8924. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8925. // parent = parent.parentNode;
  8926. // elm.parentNode = parent;
  8927. // }
  8928. parent.children.push(elm);
  8929. //如果是自闭合节点返回父亲节点
  8930. return dtd.$empty[tagName] ? parent : elm
  8931. }
  8932. function comment(parent, data) {
  8933. parent.children.push(new uNode({
  8934. type:'comment',
  8935. data:data,
  8936. parentNode:parent
  8937. }));
  8938. }
  8939. var match, currentIndex = 0, nextIndex = 0;
  8940. //设置根节点
  8941. var root = new uNode({
  8942. type:'root',
  8943. children:[]
  8944. });
  8945. var currentParent = root;
  8946. while (match = re_tag.exec(htmlstr)) {
  8947. currentIndex = match.index;
  8948. try{
  8949. if (currentIndex > nextIndex) {
  8950. //text node
  8951. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8952. }
  8953. if (match[3]) {
  8954. if(dtd.$cdata[currentParent.tagName]){
  8955. text(currentParent, match[0]);
  8956. }else{
  8957. //start tag
  8958. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8959. }
  8960. } else if (match[1]) {
  8961. if(currentParent.type != 'root'){
  8962. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8963. text(currentParent, match[0]);
  8964. }else{
  8965. var tmpParent = currentParent;
  8966. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8967. currentParent = currentParent.parentNode;
  8968. if(currentParent.type == 'root'){
  8969. currentParent = tmpParent;
  8970. throw 'break'
  8971. }
  8972. }
  8973. //end tag
  8974. currentParent = currentParent.parentNode;
  8975. }
  8976. }
  8977. } else if (match[2]) {
  8978. //comment
  8979. comment(currentParent, match[2])
  8980. }
  8981. }catch(e){}
  8982. nextIndex = re_tag.lastIndex;
  8983. }
  8984. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  8985. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  8986. if (nextIndex < htmlstr.length) {
  8987. text(currentParent, htmlstr.slice(nextIndex));
  8988. }
  8989. return root;
  8990. };
  8991. // core/filternode.js
  8992. /**
  8993. * UE过滤节点的静态方法
  8994. * @file
  8995. */
  8996. /**
  8997. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8998. * @module UE
  8999. */
  9000. /**
  9001. * 根据传入节点和过滤规则过滤相应节点
  9002. * @module UE
  9003. * @since 1.2.6.1
  9004. * @method filterNode
  9005. * @param { Object } root 指定root节点
  9006. * @param { Object } rules 过滤规则json对象
  9007. * @example
  9008. * ```javascript
  9009. * UE.filterNode(root,editor.options.filterRules);
  9010. * ```
  9011. */
  9012. var filterNode = UE.filterNode = function () {
  9013. function filterNode(node,rules){
  9014. switch (node.type) {
  9015. case 'text':
  9016. break;
  9017. case 'element':
  9018. var val;
  9019. if(val = rules[node.tagName]){
  9020. if(val === '-'){
  9021. node.parentNode.removeChild(node)
  9022. }else if(utils.isFunction(val)){
  9023. var parentNode = node.parentNode,
  9024. index = node.getIndex();
  9025. val(node);
  9026. if(node.parentNode){
  9027. if(node.children){
  9028. for(var i = 0,ci;ci=node.children[i];){
  9029. filterNode(ci,rules);
  9030. if(ci.parentNode){
  9031. i++;
  9032. }
  9033. }
  9034. }
  9035. }else{
  9036. for(var i = index,ci;ci=parentNode.children[i];){
  9037. filterNode(ci,rules);
  9038. if(ci.parentNode){
  9039. i++;
  9040. }
  9041. }
  9042. }
  9043. }else{
  9044. var attrs = val['$'];
  9045. if(attrs && node.attrs){
  9046. var tmpAttrs = {},tmpVal;
  9047. for(var a in attrs){
  9048. tmpVal = node.getAttr(a);
  9049. //todo 只先对style单独处理
  9050. if(a == 'style' && utils.isArray(attrs[a])){
  9051. var tmpCssStyle = [];
  9052. utils.each(attrs[a],function(v){
  9053. var tmp;
  9054. if(tmp = node.getStyle(v)){
  9055. tmpCssStyle.push(v + ':' + tmp);
  9056. }
  9057. });
  9058. tmpVal = tmpCssStyle.join(';')
  9059. }
  9060. if(tmpVal){
  9061. tmpAttrs[a] = tmpVal;
  9062. }
  9063. }
  9064. node.attrs = tmpAttrs;
  9065. }
  9066. if(node.children){
  9067. for(var i = 0,ci;ci=node.children[i];){
  9068. filterNode(ci,rules);
  9069. if(ci.parentNode){
  9070. i++;
  9071. }
  9072. }
  9073. }
  9074. }
  9075. }else{
  9076. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9077. if(dtd.$cdata[node.tagName]){
  9078. node.parentNode.removeChild(node)
  9079. }else{
  9080. var parentNode = node.parentNode,
  9081. index = node.getIndex();
  9082. node.parentNode.removeChild(node,true);
  9083. for(var i = index,ci;ci=parentNode.children[i];){
  9084. filterNode(ci,rules);
  9085. if(ci.parentNode){
  9086. i++;
  9087. }
  9088. }
  9089. }
  9090. }
  9091. break;
  9092. case 'comment':
  9093. node.parentNode.removeChild(node)
  9094. }
  9095. }
  9096. return function(root,rules){
  9097. if(utils.isEmptyObject(rules)){
  9098. return root;
  9099. }
  9100. var val;
  9101. if(val = rules['-']){
  9102. utils.each(val.split(' '),function(k){
  9103. rules[k] = '-'
  9104. })
  9105. }
  9106. for(var i= 0,ci;ci=root.children[i];){
  9107. filterNode(ci,rules);
  9108. if(ci.parentNode){
  9109. i++;
  9110. }
  9111. }
  9112. return root;
  9113. }
  9114. }();
  9115. // core/plugin.js
  9116. /**
  9117. * Created with JetBrains PhpStorm.
  9118. * User: campaign
  9119. * Date: 10/8/13
  9120. * Time: 6:15 PM
  9121. * To change this template use File | Settings | File Templates.
  9122. */
  9123. UE.plugin = function(){
  9124. var _plugins = {};
  9125. return {
  9126. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9127. if(oldOptionName && utils.isFunction(oldOptionName)){
  9128. afterDisabled = oldOptionName;
  9129. oldOptionName = null
  9130. }
  9131. _plugins[pluginName] = {
  9132. optionName : oldOptionName || pluginName,
  9133. execFn : fn,
  9134. //当插件被禁用时执行
  9135. afterDisabled : afterDisabled
  9136. }
  9137. },
  9138. load : function(editor){
  9139. utils.each(_plugins,function(plugin){
  9140. var _export = plugin.execFn.call(editor);
  9141. if(editor.options[plugin.optionName] !== false){
  9142. if(_export){
  9143. //后边需要再做扩展
  9144. utils.each(_export,function(v,k){
  9145. switch(k.toLowerCase()){
  9146. case 'shortcutkey':
  9147. editor.addshortcutkey(v);
  9148. break;
  9149. case 'bindevents':
  9150. utils.each(v,function(fn,eventName){
  9151. editor.addListener(eventName,fn);
  9152. });
  9153. break;
  9154. case 'bindmultievents':
  9155. utils.each(utils.isArray(v) ? v:[v],function(event){
  9156. var types = utils.trim(event.type).split(/\s+/);
  9157. utils.each(types,function(eventName){
  9158. editor.addListener(eventName, event.handler);
  9159. });
  9160. });
  9161. break;
  9162. case 'commands':
  9163. utils.each(v,function(execFn,execName){
  9164. editor.commands[execName] = execFn
  9165. });
  9166. break;
  9167. case 'outputrule':
  9168. editor.addOutputRule(v);
  9169. break;
  9170. case 'inputrule':
  9171. editor.addInputRule(v);
  9172. break;
  9173. case 'defaultoptions':
  9174. editor.setOpt(v)
  9175. }
  9176. })
  9177. }
  9178. }else if(plugin.afterDisabled){
  9179. plugin.afterDisabled.call(editor)
  9180. }
  9181. });
  9182. //向下兼容
  9183. utils.each(UE.plugins,function(plugin){
  9184. plugin.call(editor);
  9185. });
  9186. },
  9187. run : function(pluginName,editor){
  9188. var plugin = _plugins[pluginName];
  9189. if(plugin){
  9190. plugin.exeFn.call(editor)
  9191. }
  9192. }
  9193. }
  9194. }();
  9195. // core/keymap.js
  9196. var keymap = UE.keymap = {
  9197. 'Backspace' : 8,
  9198. 'Tab' : 9,
  9199. 'Enter' : 13,
  9200. 'Shift':16,
  9201. 'Control':17,
  9202. 'Alt':18,
  9203. 'CapsLock':20,
  9204. 'Esc':27,
  9205. 'Spacebar':32,
  9206. 'PageUp':33,
  9207. 'PageDown':34,
  9208. 'End':35,
  9209. 'Home':36,
  9210. 'Left':37,
  9211. 'Up':38,
  9212. 'Right':39,
  9213. 'Down':40,
  9214. 'Insert':45,
  9215. 'Del':46,
  9216. 'NumLock':144,
  9217. 'Cmd':91,
  9218. '=':187,
  9219. '-':189,
  9220. "b":66,
  9221. 'i':73,
  9222. //回退
  9223. 'z':90,
  9224. 'y':89,
  9225. //粘贴
  9226. 'v' : 86,
  9227. 'x' : 88,
  9228. 's' : 83,
  9229. 'n' : 78
  9230. };
  9231. // core/localstorage.js
  9232. //存储媒介封装
  9233. var LocalStorage = UE.LocalStorage = (function () {
  9234. var storage = window.localStorage || getUserData() || null,
  9235. LOCAL_FILE = 'localStorage';
  9236. return {
  9237. saveLocalData: function (key, data) {
  9238. if (storage && data) {
  9239. storage.setItem(key, data);
  9240. return true;
  9241. }
  9242. return false;
  9243. },
  9244. getLocalData: function (key) {
  9245. if (storage) {
  9246. return storage.getItem(key);
  9247. }
  9248. return null;
  9249. },
  9250. removeItem: function (key) {
  9251. storage && storage.removeItem(key);
  9252. }
  9253. };
  9254. function getUserData() {
  9255. var container = document.createElement("div");
  9256. container.style.display = "none";
  9257. if (!container.addBehavior) {
  9258. return null;
  9259. }
  9260. container.addBehavior("#default#userdata");
  9261. return {
  9262. getItem: function (key) {
  9263. var result = null;
  9264. try {
  9265. document.body.appendChild(container);
  9266. container.load(LOCAL_FILE);
  9267. result = container.getAttribute(key);
  9268. document.body.removeChild(container);
  9269. } catch (e) {
  9270. }
  9271. return result;
  9272. },
  9273. setItem: function (key, value) {
  9274. document.body.appendChild(container);
  9275. container.setAttribute(key, value);
  9276. container.save(LOCAL_FILE);
  9277. document.body.removeChild(container);
  9278. },
  9279. //// 暂时没有用到
  9280. //clear: function () {
  9281. //
  9282. // var expiresTime = new Date();
  9283. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9284. // document.body.appendChild(container);
  9285. // container.expires = expiresTime.toUTCString();
  9286. // container.save(LOCAL_FILE);
  9287. // document.body.removeChild(container);
  9288. //
  9289. //},
  9290. removeItem: function (key) {
  9291. document.body.appendChild(container);
  9292. container.removeAttribute(key);
  9293. container.save(LOCAL_FILE);
  9294. document.body.removeChild(container);
  9295. }
  9296. };
  9297. }
  9298. })();
  9299. (function () {
  9300. var ROOTKEY = 'ueditor_preference';
  9301. UE.Editor.prototype.setPreferences = function(key,value){
  9302. var obj = {};
  9303. if (utils.isString(key)) {
  9304. obj[ key ] = value;
  9305. } else {
  9306. obj = key;
  9307. }
  9308. var data = LocalStorage.getLocalData(ROOTKEY);
  9309. if (data && (data = utils.str2json(data))) {
  9310. utils.extend(data, obj);
  9311. } else {
  9312. data = obj;
  9313. }
  9314. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9315. };
  9316. UE.Editor.prototype.getPreferences = function(key){
  9317. var data = LocalStorage.getLocalData(ROOTKEY);
  9318. if (data && (data = utils.str2json(data))) {
  9319. return key ? data[key] : data
  9320. }
  9321. return null;
  9322. };
  9323. UE.Editor.prototype.removePreferences = function (key) {
  9324. var data = LocalStorage.getLocalData(ROOTKEY);
  9325. if (data && (data = utils.str2json(data))) {
  9326. data[key] = undefined;
  9327. delete data[key]
  9328. }
  9329. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9330. };
  9331. })();
  9332. // plugins/defaultfilter.js
  9333. ///import core
  9334. ///plugin 编辑器默认的过滤转换机制
  9335. UE.plugins['defaultfilter'] = function () {
  9336. var me = this;
  9337. me.setOpt({
  9338. 'allowDivTransToP':true,
  9339. 'disabledTableInTable':true
  9340. });
  9341. //默认的过滤处理
  9342. //进入编辑器的内容处理
  9343. me.addInputRule(function (root) {
  9344. var allowDivTransToP = this.options.allowDivTransToP;
  9345. var val;
  9346. function tdParent(node){
  9347. while(node && node.type == 'element'){
  9348. if(node.tagName == 'td'){
  9349. return true;
  9350. }
  9351. node = node.parentNode;
  9352. }
  9353. return false;
  9354. }
  9355. //进行默认的处理
  9356. root.traversal(function (node) {
  9357. if (node.type == 'element') {
  9358. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9359. if (!node.firstChild()) node.parentNode.removeChild(node);
  9360. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9361. node.parentNode.removeChild(node, true)
  9362. }
  9363. return;
  9364. }
  9365. switch (node.tagName) {
  9366. case 'style':
  9367. case 'script':
  9368. node.setAttr({
  9369. cdata_tag: node.tagName,
  9370. cdata_data: (node.innerHTML() || ''),
  9371. '_ue_custom_node_':'true'
  9372. });
  9373. node.tagName = 'div';
  9374. node.innerHTML('');
  9375. break;
  9376. case 'a':
  9377. if (val = node.getAttr('href')) {
  9378. node.setAttr('_href', val)
  9379. }
  9380. break;
  9381. case 'img':
  9382. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9383. if (val = node.getAttr('src')) {
  9384. if (/^data:/.test(val)) {
  9385. node.parentNode.removeChild(node);
  9386. break;
  9387. }
  9388. }
  9389. node.setAttr('_src', node.getAttr('src'));
  9390. break;
  9391. case 'span':
  9392. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9393. if (/nowrap|normal/.test(val)) {
  9394. node.setStyle('white-space', '');
  9395. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9396. node.parentNode.removeChild(node, true)
  9397. }
  9398. }
  9399. }
  9400. val = node.getAttr('id');
  9401. if(val && /^_baidu_bookmark_/i.test(val)){
  9402. node.parentNode.removeChild(node)
  9403. }
  9404. break;
  9405. case 'p':
  9406. if (val = node.getAttr('align')) {
  9407. node.setAttr('align');
  9408. node.setStyle('text-align', val)
  9409. }
  9410. //trace:3431
  9411. // var cssStyle = node.getAttr('style');
  9412. // if (cssStyle) {
  9413. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9414. // node.setAttr('style', cssStyle)
  9415. //
  9416. // }
  9417. //p标签不允许嵌套
  9418. utils.each(node.children,function(n){
  9419. if(n.type == 'element' && n.tagName == 'p'){
  9420. var next = n.nextSibling();
  9421. node.parentNode.insertAfter(n,node);
  9422. var last = n;
  9423. while(next){
  9424. var tmp = next.nextSibling();
  9425. node.parentNode.insertAfter(next,last);
  9426. last = next;
  9427. next = tmp;
  9428. }
  9429. return false;
  9430. }
  9431. });
  9432. if (!node.firstChild()) {
  9433. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9434. }
  9435. break;
  9436. case 'div':
  9437. if(node.getAttr('cdata_tag')){
  9438. break;
  9439. }
  9440. //针对代码这里不处理插入代码的div
  9441. val = node.getAttr('class');
  9442. if(val && /^line number\d+/.test(val)){
  9443. break;
  9444. }
  9445. if(!allowDivTransToP){
  9446. break;
  9447. }
  9448. var tmpNode, p = UE.uNode.createElement('p');
  9449. while (tmpNode = node.firstChild()) {
  9450. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9451. p.appendChild(tmpNode);
  9452. } else {
  9453. if (p.firstChild()) {
  9454. node.parentNode.insertBefore(p, node);
  9455. p = UE.uNode.createElement('p');
  9456. } else {
  9457. node.parentNode.insertBefore(tmpNode, node);
  9458. }
  9459. }
  9460. }
  9461. if (p.firstChild()) {
  9462. node.parentNode.insertBefore(p, node);
  9463. }
  9464. node.parentNode.removeChild(node);
  9465. break;
  9466. case 'dl':
  9467. node.tagName = 'ul';
  9468. break;
  9469. case 'dt':
  9470. case 'dd':
  9471. node.tagName = 'li';
  9472. break;
  9473. case 'li':
  9474. var className = node.getAttr('class');
  9475. if (!className || !/list\-/.test(className)) {
  9476. node.setAttr()
  9477. }
  9478. var tmpNodes = node.getNodesByTagName('ol ul');
  9479. UE.utils.each(tmpNodes, function (n) {
  9480. node.parentNode.insertAfter(n, node);
  9481. });
  9482. break;
  9483. case 'td':
  9484. case 'th':
  9485. case 'caption':
  9486. if(!node.children || !node.children.length){
  9487. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9488. }
  9489. break;
  9490. case 'table':
  9491. if(me.options.disabledTableInTable && tdParent(node)){
  9492. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9493. node.parentNode.removeChild(node)
  9494. }
  9495. }
  9496. }
  9497. // if(node.type == 'comment'){
  9498. // node.parentNode.removeChild(node);
  9499. // }
  9500. })
  9501. });
  9502. //从编辑器出去的内容处理
  9503. me.addOutputRule(function (root) {
  9504. var val;
  9505. root.traversal(function (node) {
  9506. if (node.type == 'element') {
  9507. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9508. if (!node.firstChild()) node.parentNode.removeChild(node);
  9509. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9510. node.parentNode.removeChild(node, true)
  9511. }
  9512. return;
  9513. }
  9514. switch (node.tagName) {
  9515. case 'div':
  9516. if (val = node.getAttr('cdata_tag')) {
  9517. node.tagName = val;
  9518. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9519. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9520. }
  9521. break;
  9522. case 'a':
  9523. if (val = node.getAttr('_href')) {
  9524. node.setAttr({
  9525. 'href': utils.html(val),
  9526. '_href': ''
  9527. })
  9528. }
  9529. break;
  9530. break;
  9531. case 'span':
  9532. val = node.getAttr('id');
  9533. if(val && /^_baidu_bookmark_/i.test(val)){
  9534. node.parentNode.removeChild(node)
  9535. }
  9536. break;
  9537. case 'img':
  9538. if (val = node.getAttr('_src')) {
  9539. node.setAttr({
  9540. 'src': node.getAttr('_src'),
  9541. '_src': ''
  9542. })
  9543. }
  9544. }
  9545. }
  9546. })
  9547. });
  9548. };
  9549. // plugins/inserthtml.js
  9550. /**
  9551. * 插入html字符串插件
  9552. * @file
  9553. * @since 1.2.6.1
  9554. */
  9555. /**
  9556. * 插入html代码
  9557. * @command inserthtml
  9558. * @method execCommand
  9559. * @param { String } cmd 命令字符串
  9560. * @param { String } html 插入的html字符串
  9561. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9562. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9563. * @example
  9564. * ```javascript
  9565. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9566. * //执行命令,插入<b>CC</b>
  9567. * //插入后的效果 xxx<b>CC</b>xxx
  9568. * //<p>xx|xxx</p> 当前选区为闭合状态
  9569. * //插入<p>CC</p>
  9570. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9571. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9572. * //插入 xxxx
  9573. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9574. * ```
  9575. */
  9576. UE.commands['inserthtml'] = {
  9577. execCommand: function (command,html,notNeedFilter){
  9578. var me = this,
  9579. range,
  9580. div;
  9581. if(!html){
  9582. return;
  9583. }
  9584. if(me.fireEvent('beforeinserthtml',html) === true){
  9585. return;
  9586. }
  9587. range = me.selection.getRange();
  9588. div = range.document.createElement( 'div' );
  9589. div.style.display = 'inline';
  9590. if (!notNeedFilter) {
  9591. var root = UE.htmlparser(html);
  9592. //如果给了过滤规则就先进行过滤
  9593. if(me.options.filterRules){
  9594. UE.filterNode(root,me.options.filterRules);
  9595. }
  9596. //执行默认的处理
  9597. me.filterInputRule(root);
  9598. html = root.toHtml()
  9599. }
  9600. div.innerHTML = utils.trim( html );
  9601. if ( !range.collapsed ) {
  9602. var tmpNode = range.startContainer;
  9603. if(domUtils.isFillChar(tmpNode)){
  9604. range.setStartBefore(tmpNode)
  9605. }
  9606. tmpNode = range.endContainer;
  9607. if(domUtils.isFillChar(tmpNode)){
  9608. range.setEndAfter(tmpNode)
  9609. }
  9610. range.txtToElmBoundary();
  9611. //结束边界可能放到了br的前边,要把br包含进来
  9612. // x[xxx]<br/>
  9613. if(range.endContainer && range.endContainer.nodeType == 1){
  9614. tmpNode = range.endContainer.childNodes[range.endOffset];
  9615. if(tmpNode && domUtils.isBr(tmpNode)){
  9616. range.setEndAfter(tmpNode);
  9617. }
  9618. }
  9619. if(range.startOffset == 0){
  9620. tmpNode = range.startContainer;
  9621. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9622. tmpNode = range.endContainer;
  9623. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9624. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9625. range.setStart(me.body.firstChild,0).collapse(true)
  9626. }
  9627. }
  9628. }
  9629. !range.collapsed && range.deleteContents();
  9630. if(range.startContainer.nodeType == 1){
  9631. var child = range.startContainer.childNodes[range.startOffset],pre;
  9632. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9633. range.setEnd(pre,pre.childNodes.length).collapse();
  9634. while(child.firstChild){
  9635. pre.appendChild(child.firstChild);
  9636. }
  9637. domUtils.remove(child);
  9638. }
  9639. }
  9640. }
  9641. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9642. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9643. if(range.inFillChar()){
  9644. child = range.startContainer;
  9645. if(domUtils.isFillChar(child)){
  9646. range.setStartBefore(child).collapse(true);
  9647. domUtils.remove(child);
  9648. }else if(domUtils.isFillChar(child,true)){
  9649. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9650. range.startOffset--;
  9651. range.collapsed && range.collapse(true)
  9652. }
  9653. }
  9654. //列表单独处理
  9655. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9656. if(li){
  9657. var next,last;
  9658. while(child = div.firstChild){
  9659. //针对hr单独处理一下先
  9660. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9661. next = child.nextSibling;
  9662. range.insertNode( child).collapse();
  9663. last = child;
  9664. child = next;
  9665. }
  9666. if(child){
  9667. if(/^(ol|ul)$/i.test(child.tagName)){
  9668. while(child.firstChild){
  9669. last = child.firstChild;
  9670. domUtils.insertAfter(li,child.firstChild);
  9671. li = li.nextSibling;
  9672. }
  9673. domUtils.remove(child)
  9674. }else{
  9675. var tmpLi;
  9676. next = child.nextSibling;
  9677. tmpLi = me.document.createElement('li');
  9678. domUtils.insertAfter(li,tmpLi);
  9679. tmpLi.appendChild(child);
  9680. last = child;
  9681. child = next;
  9682. li = tmpLi;
  9683. }
  9684. }
  9685. }
  9686. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9687. if(domUtils.isEmptyBlock(li)){
  9688. domUtils.remove(li)
  9689. }
  9690. if(last){
  9691. range.setStartAfter(last).collapse(true).select(true)
  9692. }
  9693. }else{
  9694. while ( child = div.firstChild ) {
  9695. if(hadBreak){
  9696. var p = me.document.createElement('p');
  9697. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9698. nextNode = child.nextSibling;
  9699. p.appendChild(child);
  9700. child = nextNode;
  9701. }
  9702. if(p.firstChild){
  9703. child = p
  9704. }
  9705. }
  9706. range.insertNode( child );
  9707. nextNode = child.nextSibling;
  9708. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9709. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9710. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9711. if(!dtd[parent.tagName][child.nodeName]){
  9712. pre = parent;
  9713. }else{
  9714. tmp = child.parentNode;
  9715. while (tmp !== parent){
  9716. pre = tmp;
  9717. tmp = tmp.parentNode;
  9718. }
  9719. }
  9720. domUtils.breakParent( child, pre || tmp );
  9721. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9722. var pre = child.previousSibling;
  9723. domUtils.trimWhiteTextNode(pre);
  9724. if(!pre.childNodes.length){
  9725. domUtils.remove(pre);
  9726. }
  9727. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9728. if(!browser.ie &&
  9729. (next = child.nextSibling) &&
  9730. domUtils.isBlockElm(next) &&
  9731. next.lastChild &&
  9732. !domUtils.isBr(next.lastChild)){
  9733. next.appendChild(me.document.createElement('br'));
  9734. }
  9735. hadBreak = 1;
  9736. }
  9737. }
  9738. var next = child.nextSibling;
  9739. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9740. range.setStart(next,0).collapse(true);
  9741. break;
  9742. }
  9743. range.setEndAfter( child ).collapse();
  9744. }
  9745. child = range.startContainer;
  9746. if(nextNode && domUtils.isBr(nextNode)){
  9747. domUtils.remove(nextNode)
  9748. }
  9749. //用chrome可能有空白展位符
  9750. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9751. if(nextNode = child.nextSibling){
  9752. domUtils.remove(child);
  9753. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9754. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9755. }
  9756. }else{
  9757. try{
  9758. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9759. }catch(e){
  9760. range.setStartBefore(child);
  9761. domUtils.remove(child)
  9762. }
  9763. }
  9764. }
  9765. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9766. try{
  9767. range.select(true);
  9768. }catch(e){}
  9769. }
  9770. setTimeout(function(){
  9771. range = me.selection.getRange();
  9772. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9773. me.fireEvent('afterinserthtml', html);
  9774. },200);
  9775. }
  9776. };
  9777. // plugins/autotypeset.js
  9778. /**
  9779. * 自动排版
  9780. * @file
  9781. * @since 1.2.6.1
  9782. */
  9783. /**
  9784. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9785. * @command autotypeset
  9786. * @method execCommand
  9787. * @param { String } cmd 命令字符串
  9788. * @example
  9789. * ```javascript
  9790. * editor.execCommand( 'autotypeset' );
  9791. * ```
  9792. */
  9793. UE.plugins['autotypeset'] = function(){
  9794. this.setOpt({'autotypeset': {
  9795. mergeEmptyline: true, //合并空行
  9796. removeClass: true, //去掉冗余的class
  9797. removeEmptyline: false, //去掉空行
  9798. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9799. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9800. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9801. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9802. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9803. removeEmptyNode: false, // 去掉空节点
  9804. //可以去掉的标签
  9805. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9806. indent: false, // 行首缩进
  9807. indentValue : '2em', //行首缩进的大小
  9808. bdc2sb: false,
  9809. tobdc: false
  9810. }});
  9811. var me = this,
  9812. opt = me.options.autotypeset,
  9813. remainClass = {
  9814. 'selectTdClass':1,
  9815. 'pagebreak':1,
  9816. 'anchorclass':1
  9817. },
  9818. remainTag = {
  9819. 'li':1
  9820. },
  9821. tags = {
  9822. div:1,
  9823. p:1,
  9824. //trace:2183 这些也认为是行
  9825. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9826. span:1
  9827. },
  9828. highlightCont;
  9829. //升级了版本,但配置项目里没有autotypeset
  9830. if(!opt){
  9831. return;
  9832. }
  9833. readLocalOpts();
  9834. function isLine(node,notEmpty){
  9835. if(!node || node.nodeType == 3)
  9836. return 0;
  9837. if(domUtils.isBr(node))
  9838. return 1;
  9839. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9840. if(highlightCont && highlightCont.contains(node)
  9841. ||
  9842. node.getAttribute('pagebreak')
  9843. ){
  9844. return 0;
  9845. }
  9846. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9847. +']','g'));
  9848. }
  9849. }
  9850. function removeNotAttributeSpan(node){
  9851. if(!node.style.cssText){
  9852. domUtils.removeAttributes(node,['style']);
  9853. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9854. domUtils.remove(node,true);
  9855. }
  9856. }
  9857. }
  9858. function autotype(type,html){
  9859. var me = this,cont;
  9860. if(html){
  9861. if(!opt.pasteFilter){
  9862. return;
  9863. }
  9864. cont = me.document.createElement('div');
  9865. cont.innerHTML = html.html;
  9866. }else{
  9867. cont = me.document.body;
  9868. }
  9869. var nodes = domUtils.getElementsByTagName(cont,'*');
  9870. // 行首缩进,段落方向,段间距,段内间距
  9871. for(var i=0,ci;ci=nodes[i++];){
  9872. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9873. continue;
  9874. }
  9875. //font-size
  9876. if(opt.clearFontSize && ci.style.fontSize){
  9877. domUtils.removeStyle(ci,'font-size');
  9878. removeNotAttributeSpan(ci);
  9879. }
  9880. //font-family
  9881. if(opt.clearFontFamily && ci.style.fontFamily){
  9882. domUtils.removeStyle(ci,'font-family');
  9883. removeNotAttributeSpan(ci);
  9884. }
  9885. if(isLine(ci)){
  9886. //合并空行
  9887. if(opt.mergeEmptyline ){
  9888. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9889. while(isLine(next)){
  9890. tmpNode = next;
  9891. next = tmpNode.nextSibling;
  9892. if(isBr && (!next || next && !domUtils.isBr(next))){
  9893. break;
  9894. }
  9895. domUtils.remove(tmpNode);
  9896. }
  9897. }
  9898. //去掉空行,保留占位的空行
  9899. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9900. if(domUtils.isBr(ci)){
  9901. next = ci.nextSibling;
  9902. if(next && !domUtils.isBr(next)){
  9903. continue;
  9904. }
  9905. }
  9906. domUtils.remove(ci);
  9907. continue;
  9908. }
  9909. }
  9910. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9911. if(opt.indent){
  9912. ci.style.textIndent = opt.indentValue;
  9913. }
  9914. if(opt.textAlign){
  9915. ci.style.textAlign = opt.textAlign;
  9916. }
  9917. // if(opt.lineHeight)
  9918. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9919. }
  9920. //去掉class,保留的class不去掉
  9921. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9922. if(highlightCont && highlightCont.contains(ci)){
  9923. continue;
  9924. }
  9925. domUtils.removeAttributes(ci,['class']);
  9926. }
  9927. //表情不处理
  9928. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9929. if(html){
  9930. var img = ci;
  9931. switch (opt.imageBlockLine){
  9932. case 'left':
  9933. case 'right':
  9934. case 'none':
  9935. var pN = img.parentNode,tmpNode,pre,next;
  9936. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9937. pN = pN.parentNode;
  9938. }
  9939. tmpNode = pN;
  9940. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9941. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9942. pre = tmpNode.previousSibling;
  9943. next = tmpNode.nextSibling;
  9944. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9945. pre.appendChild(tmpNode.firstChild);
  9946. while(next.firstChild){
  9947. pre.appendChild(next.firstChild);
  9948. }
  9949. domUtils.remove(tmpNode);
  9950. domUtils.remove(next);
  9951. }else{
  9952. domUtils.setStyle(tmpNode,'text-align','');
  9953. }
  9954. }
  9955. }
  9956. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9957. break;
  9958. case 'center':
  9959. if(me.queryCommandValue('imagefloat') != 'center'){
  9960. pN = img.parentNode;
  9961. domUtils.setStyle(img,'float','none');
  9962. tmpNode = img;
  9963. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  9964. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  9965. tmpNode = pN;
  9966. pN = pN.parentNode;
  9967. }
  9968. var pNode = me.document.createElement('p');
  9969. domUtils.setAttributes(pNode,{
  9970. style:'text-align:center'
  9971. });
  9972. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  9973. pNode.appendChild(tmpNode);
  9974. domUtils.setStyle(tmpNode,'float','');
  9975. }
  9976. }
  9977. } else {
  9978. var range = me.selection.getRange();
  9979. range.selectNode(ci).select();
  9980. me.execCommand('imagefloat', opt.imageBlockLine);
  9981. }
  9982. }
  9983. //去掉冗余的标签
  9984. if(opt.removeEmptyNode){
  9985. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  9986. domUtils.remove(ci);
  9987. }
  9988. }
  9989. }
  9990. if(opt.tobdc){
  9991. var root = UE.htmlparser(cont.innerHTML);
  9992. root.traversal(function(node){
  9993. if(node.type == 'text'){
  9994. node.data = ToDBC(node.data)
  9995. }
  9996. });
  9997. cont.innerHTML = root.toHtml()
  9998. }
  9999. if(opt.bdc2sb){
  10000. var root = UE.htmlparser(cont.innerHTML);
  10001. root.traversal(function(node){
  10002. if(node.type == 'text'){
  10003. node.data = DBC2SB(node.data)
  10004. }
  10005. });
  10006. cont.innerHTML = root.toHtml()
  10007. }
  10008. if(html){
  10009. html.html = cont.innerHTML;
  10010. }
  10011. }
  10012. if(opt.pasteFilter){
  10013. me.addListener('beforepaste',autotype);
  10014. }
  10015. function DBC2SB(str) {
  10016. var result = '';
  10017. for (var i = 0; i < str.length; i++) {
  10018. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10019. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10020. {
  10021. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10022. } else if (code == 12288)//空格
  10023. {
  10024. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10025. } else {
  10026. result += str.charAt(i);
  10027. }
  10028. }
  10029. return result;
  10030. }
  10031. function ToDBC(txtstring) {
  10032. txtstring = utils.html(txtstring);
  10033. var tmp = "";
  10034. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10035. for (var i = 0; i < txtstring.length; i++) {
  10036. if (txtstring.charCodeAt(i) == 32) {
  10037. tmp = tmp + String.fromCharCode(12288);
  10038. }
  10039. else if (txtstring.charCodeAt(i) < 127) {
  10040. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10041. }
  10042. else {
  10043. tmp += txtstring.charAt(i);
  10044. }
  10045. }
  10046. return tmp;
  10047. }
  10048. function readLocalOpts() {
  10049. var cookieOpt = me.getPreferences('autotypeset');
  10050. utils.extend(me.options.autotypeset, cookieOpt);
  10051. }
  10052. me.commands['autotypeset'] = {
  10053. execCommand:function () {
  10054. me.removeListener('beforepaste',autotype);
  10055. if(opt.pasteFilter){
  10056. me.addListener('beforepaste',autotype);
  10057. }
  10058. autotype.call(me)
  10059. }
  10060. };
  10061. };
  10062. // plugins/autosubmit.js
  10063. /**
  10064. * 快捷键提交
  10065. * @file
  10066. * @since 1.2.6.1
  10067. */
  10068. /**
  10069. * 提交表单
  10070. * @command autosubmit
  10071. * @method execCommand
  10072. * @param { String } cmd 命令字符串
  10073. * @example
  10074. * ```javascript
  10075. * editor.execCommand( 'autosubmit' );
  10076. * ```
  10077. */
  10078. UE.plugin.register('autosubmit',function(){
  10079. return {
  10080. shortcutkey:{
  10081. "autosubmit":"ctrl+13" //手动提交
  10082. },
  10083. commands:{
  10084. 'autosubmit':{
  10085. execCommand:function () {
  10086. var me=this,
  10087. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10088. if (form){
  10089. if(me.fireEvent("beforesubmit")===false){
  10090. return;
  10091. }
  10092. me.sync();
  10093. form.submit();
  10094. }
  10095. }
  10096. }
  10097. }
  10098. }
  10099. });
  10100. // plugins/background.js
  10101. /**
  10102. * 背景插件,为UEditor提供设置背景功能
  10103. * @file
  10104. * @since 1.2.6.1
  10105. */
  10106. UE.plugin.register('background', function () {
  10107. var me = this,
  10108. cssRuleId = 'editor_background',
  10109. isSetColored,
  10110. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10111. function stringToObj(str) {
  10112. var obj = {}, styles = str.split(';');
  10113. utils.each(styles, function (v) {
  10114. var index = v.indexOf(':'),
  10115. key = utils.trim(v.substr(0, index)).toLowerCase();
  10116. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10117. });
  10118. return obj;
  10119. }
  10120. function setBackground(obj) {
  10121. if (obj) {
  10122. var styles = [];
  10123. for (var name in obj) {
  10124. if (obj.hasOwnProperty(name)) {
  10125. styles.push(name + ":" + obj[name] + '; ');
  10126. }
  10127. }
  10128. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10129. } else {
  10130. utils.cssRule(cssRuleId, '', me.document)
  10131. }
  10132. }
  10133. //重写editor.hasContent方法
  10134. var orgFn = me.hasContents;
  10135. me.hasContents = function(){
  10136. if(me.queryCommandValue('background')){
  10137. return true
  10138. }
  10139. return orgFn.apply(me,arguments);
  10140. };
  10141. return {
  10142. bindEvents: {
  10143. 'getAllHtml': function (type, headHtml) {
  10144. var body = this.body,
  10145. su = domUtils.getComputedStyle(body, "background-image"),
  10146. url = "";
  10147. if (su.indexOf(me.options.imagePath) > 0) {
  10148. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10149. } else {
  10150. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10151. }
  10152. var html = '<style type="text/css">body{';
  10153. var bgObj = {
  10154. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10155. 'background-image': url ? 'url(' + url + ')' : '',
  10156. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10157. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10158. 'height': domUtils.getComputedStyle(body, "height")
  10159. };
  10160. for (var name in bgObj) {
  10161. if (bgObj.hasOwnProperty(name)) {
  10162. html += name + ":" + bgObj[name] + "; ";
  10163. }
  10164. }
  10165. html += '}</style> ';
  10166. headHtml.push(html);
  10167. },
  10168. 'aftersetcontent': function () {
  10169. if(isSetColored == false) setBackground();
  10170. }
  10171. },
  10172. inputRule: function (root) {
  10173. isSetColored = false;
  10174. utils.each(root.getNodesByTagName('p'), function (p) {
  10175. var styles = p.getAttr('data-background');
  10176. if (styles) {
  10177. isSetColored = true;
  10178. setBackground(stringToObj(styles));
  10179. p.parentNode.removeChild(p);
  10180. }
  10181. })
  10182. },
  10183. outputRule: function (root) {
  10184. var me = this,
  10185. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10186. if (styles) {
  10187. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10188. }
  10189. },
  10190. commands: {
  10191. 'background': {
  10192. execCommand: function (cmd, obj) {
  10193. setBackground(obj);
  10194. },
  10195. queryCommandValue: function () {
  10196. var me = this,
  10197. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10198. return styles ? stringToObj(styles[1]) : null;
  10199. },
  10200. notNeedUndo: true
  10201. }
  10202. }
  10203. }
  10204. });
  10205. // plugins/image.js
  10206. /**
  10207. * 图片插入、排版插件
  10208. * @file
  10209. * @since 1.2.6.1
  10210. */
  10211. /**
  10212. * 图片对齐方式
  10213. * @command imagefloat
  10214. * @method execCommand
  10215. * @remind 值center为独占一行居中
  10216. * @param { String } cmd 命令字符串
  10217. * @param { String } align 对齐方式,可传left、right、none、center
  10218. * @remaind center表示图片独占一行
  10219. * @example
  10220. * ```javascript
  10221. * editor.execCommand( 'imagefloat', 'center' );
  10222. * ```
  10223. */
  10224. /**
  10225. * 如果选区所在位置是图片区域
  10226. * @command imagefloat
  10227. * @method queryCommandValue
  10228. * @param { String } cmd 命令字符串
  10229. * @return { String } 返回图片对齐方式
  10230. * @example
  10231. * ```javascript
  10232. * editor.queryCommandValue( 'imagefloat' );
  10233. * ```
  10234. */
  10235. UE.commands['imagefloat'] = {
  10236. execCommand:function (cmd, align) {
  10237. var me = this,
  10238. range = me.selection.getRange();
  10239. if (!range.collapsed) {
  10240. var img = range.getClosedNode();
  10241. if (img && img.tagName == 'IMG') {
  10242. switch (align) {
  10243. case 'left':
  10244. case 'right':
  10245. case 'none':
  10246. var pN = img.parentNode, tmpNode, pre, next;
  10247. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10248. pN = pN.parentNode;
  10249. }
  10250. tmpNode = pN;
  10251. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10252. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10253. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10254. }) == 1) {
  10255. pre = tmpNode.previousSibling;
  10256. next = tmpNode.nextSibling;
  10257. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10258. pre.appendChild(tmpNode.firstChild);
  10259. while (next.firstChild) {
  10260. pre.appendChild(next.firstChild);
  10261. }
  10262. domUtils.remove(tmpNode);
  10263. domUtils.remove(next);
  10264. } else {
  10265. domUtils.setStyle(tmpNode, 'text-align', '');
  10266. }
  10267. }
  10268. range.selectNode(img).select();
  10269. }
  10270. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10271. if(align == 'none'){
  10272. domUtils.removeAttributes(img,'align');
  10273. }
  10274. break;
  10275. case 'center':
  10276. if (me.queryCommandValue('imagefloat') != 'center') {
  10277. pN = img.parentNode;
  10278. domUtils.setStyle(img, 'float', '');
  10279. domUtils.removeAttributes(img,'align');
  10280. tmpNode = img;
  10281. while (pN && domUtils.getChildCount(pN, function (node) {
  10282. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10283. }) == 1
  10284. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10285. tmpNode = pN;
  10286. pN = pN.parentNode;
  10287. }
  10288. range.setStartBefore(tmpNode).setCursor(false);
  10289. pN = me.document.createElement('div');
  10290. pN.appendChild(tmpNode);
  10291. domUtils.setStyle(tmpNode, 'float', '');
  10292. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10293. tmpNode = me.document.getElementById('_img_parent_tmp');
  10294. tmpNode.removeAttribute('id');
  10295. tmpNode = tmpNode.firstChild;
  10296. range.selectNode(tmpNode).select();
  10297. //去掉后边多余的元素
  10298. next = tmpNode.parentNode.nextSibling;
  10299. if (next && domUtils.isEmptyNode(next)) {
  10300. domUtils.remove(next);
  10301. }
  10302. }
  10303. break;
  10304. }
  10305. }
  10306. }
  10307. },
  10308. queryCommandValue:function () {
  10309. var range = this.selection.getRange(),
  10310. startNode, floatStyle;
  10311. if (range.collapsed) {
  10312. return 'none';
  10313. }
  10314. startNode = range.getClosedNode();
  10315. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10316. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10317. if (floatStyle == 'none') {
  10318. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10319. }
  10320. return {
  10321. left:1,
  10322. right:1,
  10323. center:1
  10324. }[floatStyle] ? floatStyle : 'none';
  10325. }
  10326. return 'none';
  10327. },
  10328. queryCommandState:function () {
  10329. var range = this.selection.getRange(),
  10330. startNode;
  10331. if (range.collapsed) return -1;
  10332. startNode = range.getClosedNode();
  10333. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10334. return 0;
  10335. }
  10336. return -1;
  10337. }
  10338. };
  10339. /**
  10340. * 插入图片
  10341. * @command insertimage
  10342. * @method execCommand
  10343. * @param { String } cmd 命令字符串
  10344. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10345. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10346. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10347. * @example
  10348. * ```javascript
  10349. * editor.execCommand( 'insertimage', {
  10350. * src:'a/b/c.jpg',
  10351. * width:'100',
  10352. * height:'100'
  10353. * } );
  10354. * ```
  10355. * @example
  10356. * ```javascript
  10357. * editor.execCommand( 'insertimage', [{
  10358. * src:'a/b/c.jpg',
  10359. * width:'100',
  10360. * height:'100'
  10361. * },{
  10362. * src:'a/b/d.jpg',
  10363. * width:'100',
  10364. * height:'100'
  10365. * }] );
  10366. * ```
  10367. */
  10368. UE.commands['insertimage'] = {
  10369. execCommand:function (cmd, opt) {
  10370. opt = utils.isArray(opt) ? opt : [opt];
  10371. if (!opt.length) {
  10372. return;
  10373. }
  10374. var me = this,
  10375. range = me.selection.getRange(),
  10376. img = range.getClosedNode();
  10377. if(me.fireEvent('beforeinsertimage', opt) === true){
  10378. return;
  10379. }
  10380. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10381. var first = opt.shift();
  10382. var floatStyle = first['floatStyle'];
  10383. delete first['floatStyle'];
  10384. //// img.style.border = (first.border||0) +"px solid #000";
  10385. //// img.style.margin = (first.margin||0) +"px";
  10386. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10387. domUtils.setAttributes(img, first);
  10388. me.execCommand('imagefloat', floatStyle);
  10389. if (opt.length > 0) {
  10390. range.setStartAfter(img).setCursor(false, true);
  10391. me.execCommand('insertimage', opt);
  10392. }
  10393. } else {
  10394. var html = [], str = '', ci;
  10395. ci = opt[0];
  10396. if (opt.length == 1) {
  10397. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10398. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10399. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10400. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10401. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10402. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10403. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10404. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10405. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10406. if (ci['floatStyle'] == 'center') {
  10407. str = '<p style="text-align: center">' + str + '</p>';
  10408. }
  10409. html.push(str);
  10410. } else {
  10411. for (var i = 0; ci = opt[i++];) {
  10412. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10413. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10414. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10415. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10416. (ci.border || '') + '" ' +
  10417. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10418. html.push(str);
  10419. }
  10420. }
  10421. me.execCommand('insertHtml', html.join(''));
  10422. }
  10423. me.fireEvent('afterinsertimage', opt)
  10424. }
  10425. };
  10426. // plugins/justify.js
  10427. /**
  10428. * 段落格式
  10429. * @file
  10430. * @since 1.2.6.1
  10431. */
  10432. /**
  10433. * 段落对齐方式
  10434. * @command justify
  10435. * @method execCommand
  10436. * @param { String } cmd 命令字符串
  10437. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10438. * @example
  10439. * ```javascript
  10440. * editor.execCommand( 'justify', 'center' );
  10441. * ```
  10442. */
  10443. /**
  10444. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10445. * @command justify
  10446. * @method queryCommandValue
  10447. * @param { String } cmd 命令字符串
  10448. * @return { String } 返回段落对齐方式
  10449. * @example
  10450. * ```javascript
  10451. * editor.queryCommandValue( 'justify' );
  10452. * ```
  10453. */
  10454. UE.plugins['justify']=function(){
  10455. var me=this,
  10456. block = domUtils.isBlockElm,
  10457. defaultValue = {
  10458. left:1,
  10459. right:1,
  10460. center:1,
  10461. justify:1
  10462. },
  10463. doJustify = function (range, style) {
  10464. var bookmark = range.createBookmark(),
  10465. filterFn = function (node) {
  10466. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10467. };
  10468. range.enlarge(true);
  10469. var bookmark2 = range.createBookmark(),
  10470. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10471. tmpRange = range.cloneRange(),
  10472. tmpNode;
  10473. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10474. if (current.nodeType == 3 || !block(current)) {
  10475. tmpRange.setStartBefore(current);
  10476. while (current && current !== bookmark2.end && !block(current)) {
  10477. tmpNode = current;
  10478. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10479. return !block(node);
  10480. });
  10481. }
  10482. tmpRange.setEndAfter(tmpNode);
  10483. var common = tmpRange.getCommonAncestor();
  10484. if (!domUtils.isBody(common) && block(common)) {
  10485. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10486. current = common;
  10487. } else {
  10488. var p = range.document.createElement('p');
  10489. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10490. var frag = tmpRange.extractContents();
  10491. p.appendChild(frag);
  10492. tmpRange.insertNode(p);
  10493. current = p;
  10494. }
  10495. current = domUtils.getNextDomNode(current, false, filterFn);
  10496. } else {
  10497. current = domUtils.getNextDomNode(current, true, filterFn);
  10498. }
  10499. }
  10500. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10501. };
  10502. UE.commands['justify'] = {
  10503. execCommand:function (cmdName, align) {
  10504. var range = this.selection.getRange(),
  10505. txt;
  10506. //闭合时单独处理
  10507. if (range.collapsed) {
  10508. txt = this.document.createTextNode('p');
  10509. range.insertNode(txt);
  10510. }
  10511. doJustify(range, align);
  10512. if (txt) {
  10513. range.setStartBefore(txt).collapse(true);
  10514. domUtils.remove(txt);
  10515. }
  10516. range.select();
  10517. return true;
  10518. },
  10519. queryCommandValue:function () {
  10520. var startNode = this.selection.getStart(),
  10521. value = domUtils.getComputedStyle(startNode, 'text-align');
  10522. return defaultValue[value] ? value : 'left';
  10523. },
  10524. queryCommandState:function () {
  10525. var start = this.selection.getStart(),
  10526. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10527. return cell? -1:0;
  10528. }
  10529. };
  10530. };
  10531. // plugins/font.js
  10532. /**
  10533. * 字体颜色,背景色,字号,字体,下划线,删除线
  10534. * @file
  10535. * @since 1.2.6.1
  10536. */
  10537. /**
  10538. * 字体颜色
  10539. * @command forecolor
  10540. * @method execCommand
  10541. * @param { String } cmd 命令字符串
  10542. * @param { String } value 色值(必须十六进制)
  10543. * @example
  10544. * ```javascript
  10545. * editor.execCommand( 'forecolor', '#000' );
  10546. * ```
  10547. */
  10548. /**
  10549. * 返回选区字体颜色
  10550. * @command forecolor
  10551. * @method queryCommandValue
  10552. * @param { String } cmd 命令字符串
  10553. * @return { String } 返回字体颜色
  10554. * @example
  10555. * ```javascript
  10556. * editor.queryCommandValue( 'forecolor' );
  10557. * ```
  10558. */
  10559. /**
  10560. * 字体背景颜色
  10561. * @command backcolor
  10562. * @method execCommand
  10563. * @param { String } cmd 命令字符串
  10564. * @param { String } value 色值(必须十六进制)
  10565. * @example
  10566. * ```javascript
  10567. * editor.execCommand( 'backcolor', '#000' );
  10568. * ```
  10569. */
  10570. /**
  10571. * 返回选区字体颜色
  10572. * @command backcolor
  10573. * @method queryCommandValue
  10574. * @param { String } cmd 命令字符串
  10575. * @return { String } 返回字体背景颜色
  10576. * @example
  10577. * ```javascript
  10578. * editor.queryCommandValue( 'backcolor' );
  10579. * ```
  10580. */
  10581. /**
  10582. * 字体大小
  10583. * @command fontsize
  10584. * @method execCommand
  10585. * @param { String } cmd 命令字符串
  10586. * @param { String } value 字体大小
  10587. * @example
  10588. * ```javascript
  10589. * editor.execCommand( 'fontsize', '14px' );
  10590. * ```
  10591. */
  10592. /**
  10593. * 返回选区字体大小
  10594. * @command fontsize
  10595. * @method queryCommandValue
  10596. * @param { String } cmd 命令字符串
  10597. * @return { String } 返回字体大小
  10598. * @example
  10599. * ```javascript
  10600. * editor.queryCommandValue( 'fontsize' );
  10601. * ```
  10602. */
  10603. /**
  10604. * 字体样式
  10605. * @command fontfamily
  10606. * @method execCommand
  10607. * @param { String } cmd 命令字符串
  10608. * @param { String } value 字体样式
  10609. * @example
  10610. * ```javascript
  10611. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10612. * ```
  10613. */
  10614. /**
  10615. * 返回选区字体样式
  10616. * @command fontfamily
  10617. * @method queryCommandValue
  10618. * @param { String } cmd 命令字符串
  10619. * @return { String } 返回字体样式
  10620. * @example
  10621. * ```javascript
  10622. * editor.queryCommandValue( 'fontfamily' );
  10623. * ```
  10624. */
  10625. /**
  10626. * 字体下划线,与删除线互斥
  10627. * @command underline
  10628. * @method execCommand
  10629. * @param { String } cmd 命令字符串
  10630. * @example
  10631. * ```javascript
  10632. * editor.execCommand( 'underline' );
  10633. * ```
  10634. */
  10635. /**
  10636. * 字体删除线,与下划线互斥
  10637. * @command strikethrough
  10638. * @method execCommand
  10639. * @param { String } cmd 命令字符串
  10640. * @example
  10641. * ```javascript
  10642. * editor.execCommand( 'strikethrough' );
  10643. * ```
  10644. */
  10645. /**
  10646. * 字体边框
  10647. * @command fontborder
  10648. * @method execCommand
  10649. * @param { String } cmd 命令字符串
  10650. * @example
  10651. * ```javascript
  10652. * editor.execCommand( 'fontborder' );
  10653. * ```
  10654. */
  10655. UE.plugins['font'] = function () {
  10656. var me = this,
  10657. fonts = {
  10658. 'forecolor': 'color',
  10659. 'backcolor': 'background-color',
  10660. 'fontsize': 'font-size',
  10661. 'fontfamily': 'font-family',
  10662. 'underline': 'text-decoration',
  10663. 'strikethrough': 'text-decoration',
  10664. 'fontborder': 'border'
  10665. },
  10666. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10667. needSetChild = {
  10668. 'forecolor': 'color',
  10669. 'backcolor': 'background-color',
  10670. 'fontsize': 'font-size',
  10671. 'fontfamily': 'font-family'
  10672. };
  10673. me.setOpt({
  10674. 'fontfamily': [
  10675. { name: 'songti', val: '宋体,SimSun'},
  10676. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10677. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10678. { name: 'heiti', val: '黑体, SimHei'},
  10679. { name: 'lishu', val: '隶书, SimLi'},
  10680. { name: 'andaleMono', val: 'andale mono'},
  10681. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10682. { name: 'arialBlack', val: 'arial black,avant garde'},
  10683. { name: 'comicSansMs', val: 'comic sans ms'},
  10684. { name: 'impact', val: 'impact,chicago'},
  10685. { name: 'timesNewRoman', val: 'times new roman'}
  10686. ],
  10687. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10688. });
  10689. function mergeWithParent(node){
  10690. var parent;
  10691. while(parent = node.parentNode){
  10692. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10693. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10694. }) == 1) {
  10695. parent.style.cssText += node.style.cssText;
  10696. domUtils.remove(node,true);
  10697. node = parent;
  10698. }else{
  10699. break;
  10700. }
  10701. }
  10702. }
  10703. function mergeChild(rng,cmdName,value){
  10704. if(needSetChild[cmdName]){
  10705. rng.adjustmentBoundary();
  10706. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10707. var start = rng.startContainer.childNodes[rng.startOffset];
  10708. if(start && domUtils.isTagNode(start,'span')){
  10709. var bk = rng.createBookmark();
  10710. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10711. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10712. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10713. return;
  10714. }
  10715. domUtils.removeStyle(span,needSetChild[cmdName]);
  10716. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10717. domUtils.remove(span,true)
  10718. }
  10719. });
  10720. rng.moveToBookmark(bk)
  10721. }
  10722. }
  10723. }
  10724. }
  10725. function mergesibling(rng,cmdName,value) {
  10726. var collapsed = rng.collapsed,
  10727. bk = rng.createBookmark(), common;
  10728. if (collapsed) {
  10729. common = bk.start.parentNode;
  10730. while (dtd.$inline[common.tagName]) {
  10731. common = common.parentNode;
  10732. }
  10733. } else {
  10734. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10735. }
  10736. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10737. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10738. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10739. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10740. domUtils.remove(span, true);
  10741. }else{
  10742. domUtils.removeStyle(span,'border');
  10743. }
  10744. return
  10745. }
  10746. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10747. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10748. }
  10749. if(!(cmdName=='fontborder' && value=='none')){
  10750. var next = span.nextSibling;
  10751. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10752. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10753. span.appendChild(next);
  10754. next = span.nextSibling;
  10755. continue;
  10756. }
  10757. if (next.style.cssText == span.style.cssText) {
  10758. domUtils.moveChild(next, span);
  10759. domUtils.remove(next);
  10760. }
  10761. if (span.nextSibling === next)
  10762. break;
  10763. next = span.nextSibling;
  10764. }
  10765. }
  10766. mergeWithParent(span);
  10767. if(browser.ie && browser.version > 8 ){
  10768. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10769. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10770. if(parent && !/background-color/.test(span.style.cssText)){
  10771. span.style.backgroundColor = parent.style.backgroundColor;
  10772. }
  10773. }
  10774. });
  10775. rng.moveToBookmark(bk);
  10776. mergeChild(rng,cmdName,value)
  10777. }
  10778. me.addInputRule(function (root) {
  10779. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10780. if (node.tagName == 'font') {
  10781. var cssStyle = [];
  10782. for (var p in node.attrs) {
  10783. switch (p) {
  10784. case 'size':
  10785. cssStyle.push('font-size:' +
  10786. ({
  10787. '1':'10',
  10788. '2':'12',
  10789. '3':'16',
  10790. '4':'18',
  10791. '5':'24',
  10792. '6':'32',
  10793. '7':'48'
  10794. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10795. break;
  10796. case 'color':
  10797. cssStyle.push('color:' + node.attrs[p]);
  10798. break;
  10799. case 'face':
  10800. cssStyle.push('font-family:' + node.attrs[p]);
  10801. break;
  10802. case 'style':
  10803. cssStyle.push(node.attrs[p]);
  10804. }
  10805. }
  10806. node.attrs = {
  10807. 'style': cssStyle.join(';')
  10808. };
  10809. } else {
  10810. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10811. node.attrs = {
  10812. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10813. }
  10814. }
  10815. node.tagName = 'span';
  10816. });
  10817. // utils.each(root.getNodesByTagName('span'), function (node) {
  10818. // var val;
  10819. // if(val = node.getAttr('class')){
  10820. // if(/fontstrikethrough/.test(val)){
  10821. // node.setStyle('text-decoration','line-through');
  10822. // if(node.attrs['class']){
  10823. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10824. // }else{
  10825. // node.setAttr('class')
  10826. // }
  10827. // }
  10828. // if(/fontborder/.test(val)){
  10829. // node.setStyle('border','1px solid #000');
  10830. // if(node.attrs['class']){
  10831. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10832. // }else{
  10833. // node.setAttr('class')
  10834. // }
  10835. // }
  10836. // }
  10837. // });
  10838. });
  10839. // me.addOutputRule(function(root){
  10840. // utils.each(root.getNodesByTagName('span'), function (node) {
  10841. // var val;
  10842. // if(val = node.getStyle('text-decoration')){
  10843. // if(/line-through/.test(val)){
  10844. // if(node.attrs['class']){
  10845. // node.attrs['class'] += ' fontstrikethrough';
  10846. // }else{
  10847. // node.setAttr('class','fontstrikethrough')
  10848. // }
  10849. // }
  10850. //
  10851. // node.setStyle('text-decoration')
  10852. // }
  10853. // if(val = node.getStyle('border')){
  10854. // if(/1px/.test(val) && /solid/.test(val)){
  10855. // if(node.attrs['class']){
  10856. // node.attrs['class'] += ' fontborder';
  10857. //
  10858. // }else{
  10859. // node.setAttr('class','fontborder')
  10860. // }
  10861. // }
  10862. // node.setStyle('border')
  10863. //
  10864. // }
  10865. // });
  10866. // });
  10867. for (var p in fonts) {
  10868. (function (cmd, style) {
  10869. UE.commands[cmd] = {
  10870. execCommand: function (cmdName, value) {
  10871. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10872. cmdName == 'fontborder' ? '1px solid #000' :
  10873. 'line-through');
  10874. var me = this,
  10875. range = this.selection.getRange(),
  10876. text;
  10877. if (value == 'default') {
  10878. if (range.collapsed) {
  10879. text = me.document.createTextNode('font');
  10880. range.insertNode(text).select();
  10881. }
  10882. me.execCommand('removeFormat', 'span,a', style);
  10883. if (text) {
  10884. range.setStartBefore(text).collapse(true);
  10885. domUtils.remove(text);
  10886. }
  10887. mergesibling(range,cmdName,value);
  10888. range.select()
  10889. } else {
  10890. if (!range.collapsed) {
  10891. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10892. me.execCommand('removeFormat', 'span,a', style);
  10893. }
  10894. range = me.selection.getRange();
  10895. range.applyInlineStyle('span', {'style': style + ':' + value});
  10896. mergesibling(range, cmdName,value);
  10897. range.select();
  10898. } else {
  10899. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10900. text = me.document.createTextNode('font');
  10901. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10902. //for ie hack when enter
  10903. range.insertNode(text);
  10904. if (needCmd[cmd]) {
  10905. range.selectNode(text).select();
  10906. me.execCommand('removeFormat', 'span,a', style, null);
  10907. span = domUtils.findParentByTagName(text, 'span', true);
  10908. range.setStartBefore(text);
  10909. }
  10910. span && (span.style.cssText += ';' + style + ':' + value);
  10911. range.collapse(true).select();
  10912. } else {
  10913. range.insertNode(text);
  10914. range.selectNode(text).select();
  10915. span = range.document.createElement('span');
  10916. if (needCmd[cmd]) {
  10917. //a标签内的不处理跳过
  10918. if (domUtils.findParentByTagName(text, 'a', true)) {
  10919. range.setStartBefore(text).setCursor();
  10920. domUtils.remove(text);
  10921. return;
  10922. }
  10923. me.execCommand('removeFormat', 'span,a', style);
  10924. }
  10925. span.style.cssText = style + ':' + value;
  10926. text.parentNode.insertBefore(span, text);
  10927. //修复,span套span 但样式不继承的问题
  10928. if (!browser.ie || browser.ie && browser.version == 9) {
  10929. var spanParent = span.parentNode;
  10930. while (!domUtils.isBlockElm(spanParent)) {
  10931. if (spanParent.tagName == 'SPAN') {
  10932. //opera合并style不会加入";"
  10933. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10934. }
  10935. spanParent = spanParent.parentNode;
  10936. }
  10937. }
  10938. if (opera) {
  10939. setTimeout(function () {
  10940. range.setStart(span, 0).collapse(true);
  10941. mergesibling(range, cmdName,value);
  10942. range.select();
  10943. });
  10944. } else {
  10945. range.setStart(span, 0).collapse(true);
  10946. mergesibling(range,cmdName,value);
  10947. range.select();
  10948. }
  10949. //trace:981
  10950. //domUtils.mergeToParent(span)
  10951. }
  10952. domUtils.remove(text);
  10953. }
  10954. }
  10955. return true;
  10956. },
  10957. queryCommandValue: function (cmdName) {
  10958. var startNode = this.selection.getStart();
  10959. //trace:946
  10960. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  10961. var tmpNode = startNode, value;
  10962. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  10963. if (tmpNode.nodeType == 1) {
  10964. value = domUtils.getComputedStyle(tmpNode, style);
  10965. if (value != 'none') {
  10966. return value;
  10967. }
  10968. }
  10969. tmpNode = tmpNode.parentNode;
  10970. }
  10971. return 'none';
  10972. }
  10973. if (cmdName == 'fontborder') {
  10974. var tmp = startNode, val;
  10975. while (tmp && dtd.$inline[tmp.tagName]) {
  10976. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  10977. if (/1px/.test(val) && /solid/.test(val)) {
  10978. return val;
  10979. }
  10980. }
  10981. tmp = tmp.parentNode;
  10982. }
  10983. return ''
  10984. }
  10985. if( cmdName == 'FontSize' ) {
  10986. var styleVal = domUtils.getComputedStyle(startNode, style),
  10987. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  10988. if( tmp ) {
  10989. return Math.floor( tmp[1] ) + tmp[2];
  10990. }
  10991. return styleVal;
  10992. }
  10993. return domUtils.getComputedStyle(startNode, style);
  10994. },
  10995. queryCommandState: function (cmdName) {
  10996. if (!needCmd[cmdName])
  10997. return 0;
  10998. var val = this.queryCommandValue(cmdName);
  10999. if (cmdName == 'fontborder') {
  11000. return /1px/.test(val) && /solid/.test(val)
  11001. } else {
  11002. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11003. }
  11004. }
  11005. };
  11006. })(p, fonts[p]);
  11007. }
  11008. };
  11009. // plugins/link.js
  11010. /**
  11011. * 超链接
  11012. * @file
  11013. * @since 1.2.6.1
  11014. */
  11015. /**
  11016. * 插入超链接
  11017. * @command link
  11018. * @method execCommand
  11019. * @param { String } cmd 命令字符串
  11020. * @param { Object } options 设置自定义属性,例如:url、title、target
  11021. * @example
  11022. * ```javascript
  11023. * editor.execCommand( 'link', '{
  11024. * url:'ueditor.baidu.com',
  11025. * title:'ueditor',
  11026. * target:'_blank'
  11027. * }' );
  11028. * ```
  11029. */
  11030. /**
  11031. * 返回当前选中的第一个超链接节点
  11032. * @command link
  11033. * @method queryCommandValue
  11034. * @param { String } cmd 命令字符串
  11035. * @return { Element } 超链接节点
  11036. * @example
  11037. * ```javascript
  11038. * editor.queryCommandValue( 'link' );
  11039. * ```
  11040. */
  11041. /**
  11042. * 取消超链接
  11043. * @command unlink
  11044. * @method execCommand
  11045. * @param { String } cmd 命令字符串
  11046. * @example
  11047. * ```javascript
  11048. * editor.execCommand( 'unlink');
  11049. * ```
  11050. */
  11051. UE.plugins['link'] = function(){
  11052. function optimize( range ) {
  11053. var start = range.startContainer,end = range.endContainer;
  11054. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11055. range.setStartBefore( start );
  11056. }
  11057. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11058. range.setEndAfter( end );
  11059. }
  11060. }
  11061. UE.commands['unlink'] = {
  11062. execCommand : function() {
  11063. var range = this.selection.getRange(),
  11064. bookmark;
  11065. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11066. return;
  11067. }
  11068. bookmark = range.createBookmark();
  11069. optimize( range );
  11070. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11071. },
  11072. queryCommandState : function(){
  11073. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11074. }
  11075. };
  11076. function doLink(range,opt,me){
  11077. var rngClone = range.cloneRange(),
  11078. link = me.queryCommandValue('link');
  11079. optimize( range = range.adjustmentBoundary() );
  11080. var start = range.startContainer;
  11081. if(start.nodeType == 1 && link){
  11082. start = start.childNodes[range.startOffset];
  11083. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11084. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11085. }
  11086. }
  11087. if( !rngClone.collapsed || link){
  11088. range.removeInlineStyle( 'a' );
  11089. rngClone = range.cloneRange();
  11090. }
  11091. if ( rngClone.collapsed ) {
  11092. var a = range.document.createElement( 'a'),
  11093. text = '';
  11094. if(opt.textValue){
  11095. text = utils.html(opt.textValue);
  11096. delete opt.textValue;
  11097. }else{
  11098. text = utils.html(opt.href);
  11099. }
  11100. domUtils.setAttributes( a, opt );
  11101. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11102. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11103. range.setStartAfter(start).collapse(true);
  11104. }
  11105. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11106. range.insertNode(a).selectNode( a );
  11107. } else {
  11108. range.applyInlineStyle( 'a', opt );
  11109. }
  11110. }
  11111. UE.commands['link'] = {
  11112. execCommand : function( cmdName, opt ) {
  11113. var range;
  11114. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11115. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11116. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11117. doLink(range=this.selection.getRange(),opt,this);
  11118. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11119. range.collapse().select(true);
  11120. },
  11121. queryCommandValue : function() {
  11122. var range = this.selection.getRange(),
  11123. node;
  11124. if ( range.collapsed ) {
  11125. // node = this.selection.getStart();
  11126. //在ie下getstart()取值偏上了
  11127. node = range.startContainer;
  11128. node = node.nodeType == 1 ? node : node.parentNode;
  11129. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11130. return node;
  11131. }
  11132. } else {
  11133. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11134. range.shrinkBoundary();
  11135. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11136. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11137. common = range.getCommonAncestor();
  11138. node = domUtils.findParentByTagName( common, 'a', true );
  11139. if ( !node && common.nodeType == 1){
  11140. var as = common.getElementsByTagName( 'a' ),
  11141. ps,pe;
  11142. for ( var i = 0,ci; ci = as[i++]; ) {
  11143. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11144. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11145. &&
  11146. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11147. ) {
  11148. node = ci;
  11149. break;
  11150. }
  11151. }
  11152. }
  11153. return node;
  11154. }
  11155. },
  11156. queryCommandState : function() {
  11157. //判断如果是视频的话连接不可用
  11158. //fix 853
  11159. var img = this.selection.getRange().getClosedNode(),
  11160. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11161. return flag ? -1 : 0;
  11162. }
  11163. };
  11164. };
  11165. // plugins/iframe.js
  11166. ///import core
  11167. ///import plugins\inserthtml.js
  11168. ///commands 插入框架
  11169. ///commandsName InsertFrame
  11170. ///commandsTitle 插入Iframe
  11171. ///commandsDialog dialogs\insertframe
  11172. UE.plugins['insertframe'] = function() {
  11173. var me =this;
  11174. function deleteIframe(){
  11175. me._iframe && delete me._iframe;
  11176. }
  11177. me.addListener("selectionchange",function(){
  11178. deleteIframe();
  11179. });
  11180. };
  11181. // plugins/scrawl.js
  11182. ///import core
  11183. ///commands 涂鸦
  11184. ///commandsName Scrawl
  11185. ///commandsTitle 涂鸦
  11186. ///commandsDialog dialogs\scrawl
  11187. UE.commands['scrawl'] = {
  11188. queryCommandState : function(){
  11189. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11190. }
  11191. };
  11192. // plugins/removeformat.js
  11193. /**
  11194. * 清除格式
  11195. * @file
  11196. * @since 1.2.6.1
  11197. */
  11198. /**
  11199. * 清除文字样式
  11200. * @command removeformat
  11201. * @method execCommand
  11202. * @param { String } cmd 命令字符串
  11203. * @param {String} tags 以逗号隔开的标签。如:strong
  11204. * @param {String} style 样式如:color
  11205. * @param {String} attrs 属性如:width
  11206. * @example
  11207. * ```javascript
  11208. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11209. * ```
  11210. */
  11211. UE.plugins['removeformat'] = function(){
  11212. var me = this;
  11213. me.setOpt({
  11214. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11215. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11216. });
  11217. me.commands['removeformat'] = {
  11218. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11219. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11220. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11221. range = new dom.Range( this.document ),
  11222. bookmark,node,parent,
  11223. filter = function( node ) {
  11224. return node.nodeType == 1;
  11225. };
  11226. function isRedundantSpan (node) {
  11227. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11228. return 0;
  11229. }
  11230. if (browser.ie) {
  11231. //ie 下判断实效,所以只能简单用style来判断
  11232. //return node.style.cssText == '' ? 1 : 0;
  11233. var attrs = node.attributes;
  11234. if ( attrs.length ) {
  11235. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11236. if ( attrs[i].specified ) {
  11237. return 0;
  11238. }
  11239. }
  11240. return 1;
  11241. }
  11242. }
  11243. return !node.attributes.length;
  11244. }
  11245. function doRemove( range ) {
  11246. var bookmark1 = range.createBookmark();
  11247. if ( range.collapsed ) {
  11248. range.enlarge( true );
  11249. }
  11250. //不能把a标签切了
  11251. if(!notIncludeA){
  11252. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11253. if(aNode){
  11254. range.setStartBefore(aNode);
  11255. }
  11256. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11257. if(aNode){
  11258. range.setEndAfter(aNode);
  11259. }
  11260. }
  11261. bookmark = range.createBookmark();
  11262. node = bookmark.start;
  11263. //切开始
  11264. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11265. domUtils.breakParent( node, parent );
  11266. domUtils.clearEmptySibling( node );
  11267. }
  11268. if ( bookmark.end ) {
  11269. //切结束
  11270. node = bookmark.end;
  11271. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11272. domUtils.breakParent( node, parent );
  11273. domUtils.clearEmptySibling( node );
  11274. }
  11275. //开始去除样式
  11276. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11277. next;
  11278. while ( current ) {
  11279. if ( current == bookmark.end ) {
  11280. break;
  11281. }
  11282. next = domUtils.getNextDomNode( current, true, filter );
  11283. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11284. if ( tagReg.test( current.tagName ) ) {
  11285. if ( style ) {
  11286. domUtils.removeStyle( current, style );
  11287. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11288. domUtils.remove( current, true );
  11289. }
  11290. } else {
  11291. domUtils.remove( current, true );
  11292. }
  11293. } else {
  11294. //trace:939 不能把list上的样式去掉
  11295. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11296. domUtils.removeAttributes( current, removeFormatAttributes );
  11297. if ( isRedundantSpan( current ) ){
  11298. domUtils.remove( current, true );
  11299. }
  11300. }
  11301. }
  11302. }
  11303. current = next;
  11304. }
  11305. }
  11306. //trace:1035
  11307. //trace:1096 不能把td上的样式去掉,比如边框
  11308. var pN = bookmark.start.parentNode;
  11309. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11310. domUtils.removeAttributes( pN,removeFormatAttributes );
  11311. }
  11312. pN = bookmark.end.parentNode;
  11313. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11314. domUtils.removeAttributes( pN,removeFormatAttributes );
  11315. }
  11316. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11317. //清除冗余的代码 <b><bookmark></b>
  11318. var node = range.startContainer,
  11319. tmp,
  11320. collapsed = range.collapsed;
  11321. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11322. tmp = node.parentNode;
  11323. range.setStartBefore(node);
  11324. //trace:937
  11325. //更新结束边界
  11326. if(range.startContainer === range.endContainer){
  11327. range.endOffset--;
  11328. }
  11329. domUtils.remove(node);
  11330. node = tmp;
  11331. }
  11332. if(!collapsed){
  11333. node = range.endContainer;
  11334. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11335. tmp = node.parentNode;
  11336. range.setEndBefore(node);
  11337. domUtils.remove(node);
  11338. node = tmp;
  11339. }
  11340. }
  11341. }
  11342. range = this.selection.getRange();
  11343. doRemove( range );
  11344. range.select();
  11345. }
  11346. };
  11347. };
  11348. // plugins/blockquote.js
  11349. /**
  11350. * 添加引用
  11351. * @file
  11352. * @since 1.2.6.1
  11353. */
  11354. /**
  11355. * 添加引用
  11356. * @command blockquote
  11357. * @method execCommand
  11358. * @param { String } cmd 命令字符串
  11359. * @example
  11360. * ```javascript
  11361. * editor.execCommand( 'blockquote' );
  11362. * ```
  11363. */
  11364. /**
  11365. * 添加引用
  11366. * @command blockquote
  11367. * @method execCommand
  11368. * @param { String } cmd 命令字符串
  11369. * @param { Object } attrs 节点属性
  11370. * @example
  11371. * ```javascript
  11372. * editor.execCommand( 'blockquote',{
  11373. * style: "color: red;"
  11374. * } );
  11375. * ```
  11376. */
  11377. UE.plugins['blockquote'] = function(){
  11378. var me = this;
  11379. function getObj(editor){
  11380. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11381. }
  11382. me.commands['blockquote'] = {
  11383. execCommand : function( cmdName, attrs ) {
  11384. var range = this.selection.getRange(),
  11385. obj = getObj(this),
  11386. blockquote = dtd.blockquote,
  11387. bookmark = range.createBookmark();
  11388. if ( obj ) {
  11389. var start = range.startContainer,
  11390. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11391. end = range.endContainer,
  11392. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11393. //处理一下li
  11394. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11395. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11396. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11397. domUtils.remove(obj,true);
  11398. }else{
  11399. domUtils.breakParent(startBlock,obj);
  11400. }
  11401. if(startBlock !== endBlock){
  11402. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11403. if(obj){
  11404. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11405. obj.parentNode && domUtils.remove(obj,true);
  11406. }else{
  11407. domUtils.breakParent(endBlock,obj);
  11408. }
  11409. }
  11410. }
  11411. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11412. for(var i=0,bi;bi=blockquotes[i++];){
  11413. if(!bi.childNodes.length){
  11414. domUtils.remove(bi);
  11415. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11416. domUtils.remove(bi,true);
  11417. }
  11418. }
  11419. } else {
  11420. var tmpRange = range.cloneRange(),
  11421. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11422. preNode = node,
  11423. doEnd = 1;
  11424. //调整开始
  11425. while ( 1 ) {
  11426. if ( domUtils.isBody(node) ) {
  11427. if ( preNode !== node ) {
  11428. if ( range.collapsed ) {
  11429. tmpRange.selectNode( preNode );
  11430. doEnd = 0;
  11431. } else {
  11432. tmpRange.setStartBefore( preNode );
  11433. }
  11434. }else{
  11435. tmpRange.setStart(node,0);
  11436. }
  11437. break;
  11438. }
  11439. if ( !blockquote[node.tagName] ) {
  11440. if ( range.collapsed ) {
  11441. tmpRange.selectNode( preNode );
  11442. } else{
  11443. tmpRange.setStartBefore( preNode);
  11444. }
  11445. break;
  11446. }
  11447. preNode = node;
  11448. node = node.parentNode;
  11449. }
  11450. //调整结束
  11451. if ( doEnd ) {
  11452. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11453. while ( 1 ) {
  11454. if ( domUtils.isBody( node ) ) {
  11455. if ( preNode !== node ) {
  11456. tmpRange.setEndAfter( preNode );
  11457. } else {
  11458. tmpRange.setEnd( node, node.childNodes.length );
  11459. }
  11460. break;
  11461. }
  11462. if ( !blockquote[node.tagName] ) {
  11463. tmpRange.setEndAfter( preNode );
  11464. break;
  11465. }
  11466. preNode = node;
  11467. node = node.parentNode;
  11468. }
  11469. }
  11470. node = range.document.createElement( 'blockquote' );
  11471. domUtils.setAttributes( node, attrs );
  11472. node.appendChild( tmpRange.extractContents() );
  11473. tmpRange.insertNode( node );
  11474. //去除重复的
  11475. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11476. for(var i=0,ci;ci=childs[i++];){
  11477. if(ci.parentNode){
  11478. domUtils.remove(ci,true);
  11479. }
  11480. }
  11481. }
  11482. range.moveToBookmark( bookmark ).select();
  11483. },
  11484. queryCommandState : function() {
  11485. return getObj(this) ? 1 : 0;
  11486. }
  11487. };
  11488. };
  11489. // plugins/convertcase.js
  11490. /**
  11491. * 大小写转换
  11492. * @file
  11493. * @since 1.2.6.1
  11494. */
  11495. /**
  11496. * 把选区内文本变大写,与“tolowercase”命令互斥
  11497. * @command touppercase
  11498. * @method execCommand
  11499. * @param { String } cmd 命令字符串
  11500. * @example
  11501. * ```javascript
  11502. * editor.execCommand( 'touppercase' );
  11503. * ```
  11504. */
  11505. /**
  11506. * 把选区内文本变小写,与“touppercase”命令互斥
  11507. * @command tolowercase
  11508. * @method execCommand
  11509. * @param { String } cmd 命令字符串
  11510. * @example
  11511. * ```javascript
  11512. * editor.execCommand( 'tolowercase' );
  11513. * ```
  11514. */
  11515. UE.commands['touppercase'] =
  11516. UE.commands['tolowercase'] = {
  11517. execCommand:function (cmd) {
  11518. var me = this;
  11519. var rng = me.selection.getRange();
  11520. if(rng.collapsed){
  11521. return rng;
  11522. }
  11523. var bk = rng.createBookmark(),
  11524. bkEnd = bk.end,
  11525. filterFn = function( node ) {
  11526. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11527. },
  11528. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11529. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11530. if ( curNode.nodeType == 3 ) {
  11531. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11532. }
  11533. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11534. if(curNode === bkEnd){
  11535. break;
  11536. }
  11537. }
  11538. rng.moveToBookmark(bk).select();
  11539. }
  11540. };
  11541. // plugins/indent.js
  11542. /**
  11543. * 首行缩进
  11544. * @file
  11545. * @since 1.2.6.1
  11546. */
  11547. /**
  11548. * 缩进
  11549. * @command indent
  11550. * @method execCommand
  11551. * @param { String } cmd 命令字符串
  11552. * @example
  11553. * ```javascript
  11554. * editor.execCommand( 'indent' );
  11555. * ```
  11556. */
  11557. UE.commands['indent'] = {
  11558. execCommand : function() {
  11559. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11560. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11561. },
  11562. queryCommandState : function() {
  11563. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11564. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11565. }
  11566. };
  11567. // plugins/print.js
  11568. /**
  11569. * 打印
  11570. * @file
  11571. * @since 1.2.6.1
  11572. */
  11573. /**
  11574. * 打印
  11575. * @command print
  11576. * @method execCommand
  11577. * @param { String } cmd 命令字符串
  11578. * @example
  11579. * ```javascript
  11580. * editor.execCommand( 'print' );
  11581. * ```
  11582. */
  11583. UE.commands['print'] = {
  11584. execCommand : function(){
  11585. this.window.print();
  11586. },
  11587. notNeedUndo : 1
  11588. };
  11589. // plugins/preview.js
  11590. /**
  11591. * 预览
  11592. * @file
  11593. * @since 1.2.6.1
  11594. */
  11595. /**
  11596. * 预览
  11597. * @command preview
  11598. * @method execCommand
  11599. * @param { String } cmd 命令字符串
  11600. * @example
  11601. * ```javascript
  11602. * editor.execCommand( 'preview' );
  11603. * ```
  11604. */
  11605. UE.commands['preview'] = {
  11606. execCommand : function(){
  11607. var w = window.open('', '_blank', ''),
  11608. d = w.document;
  11609. d.open();
  11610. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11611. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11612. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11613. d.close();
  11614. },
  11615. notNeedUndo : 1
  11616. };
  11617. // plugins/selectall.js
  11618. /**
  11619. * 全选
  11620. * @file
  11621. * @since 1.2.6.1
  11622. */
  11623. /**
  11624. * 选中所有内容
  11625. * @command selectall
  11626. * @method execCommand
  11627. * @param { String } cmd 命令字符串
  11628. * @example
  11629. * ```javascript
  11630. * editor.execCommand( 'selectall' );
  11631. * ```
  11632. */
  11633. UE.plugins['selectall'] = function(){
  11634. var me = this;
  11635. me.commands['selectall'] = {
  11636. execCommand : function(){
  11637. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11638. var me = this,body = me.body,
  11639. range = me.selection.getRange();
  11640. range.selectNodeContents(body);
  11641. if(domUtils.isEmptyBlock(body)){
  11642. //opera不能自动合并到元素的里边,要手动处理一下
  11643. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11644. range.setStartAtFirst(body.firstChild);
  11645. }
  11646. range.collapse(true);
  11647. }
  11648. range.select(true);
  11649. },
  11650. notNeedUndo : 1
  11651. };
  11652. //快捷键
  11653. me.addshortcutkey({
  11654. "selectAll" : "ctrl+65"
  11655. });
  11656. };
  11657. // plugins/paragraph.js
  11658. /**
  11659. * 段落样式
  11660. * @file
  11661. * @since 1.2.6.1
  11662. */
  11663. /**
  11664. * 段落格式
  11665. * @command paragraph
  11666. * @method execCommand
  11667. * @param { String } cmd 命令字符串
  11668. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11669. * @param {Object} attrs 标签的属性
  11670. * @example
  11671. * ```javascript
  11672. * editor.execCommand( 'Paragraph','h1','{
  11673. * class:'test'
  11674. * }' );
  11675. * ```
  11676. */
  11677. /**
  11678. * 返回选区内节点标签名
  11679. * @command paragraph
  11680. * @method queryCommandValue
  11681. * @param { String } cmd 命令字符串
  11682. * @return { String } 节点标签名
  11683. * @example
  11684. * ```javascript
  11685. * editor.queryCommandValue( 'Paragraph' );
  11686. * ```
  11687. */
  11688. UE.plugins['paragraph'] = function() {
  11689. var me = this,
  11690. block = domUtils.isBlockElm,
  11691. notExchange = ['TD','LI','PRE'],
  11692. doParagraph = function(range,style,attrs,sourceCmdName){
  11693. var bookmark = range.createBookmark(),
  11694. filterFn = function( node ) {
  11695. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11696. },
  11697. para;
  11698. range.enlarge( true );
  11699. var bookmark2 = range.createBookmark(),
  11700. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11701. tmpRange = range.cloneRange(),
  11702. tmpNode;
  11703. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11704. if ( current.nodeType == 3 || !block( current ) ) {
  11705. tmpRange.setStartBefore( current );
  11706. while ( current && current !== bookmark2.end && !block( current ) ) {
  11707. tmpNode = current;
  11708. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11709. return !block( node );
  11710. } );
  11711. }
  11712. tmpRange.setEndAfter( tmpNode );
  11713. para = range.document.createElement( style );
  11714. if(attrs){
  11715. domUtils.setAttributes(para,attrs);
  11716. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11717. para.style.cssText = attrs.style;
  11718. }
  11719. }
  11720. para.appendChild( tmpRange.extractContents() );
  11721. //需要内容占位
  11722. if(domUtils.isEmptyNode(para)){
  11723. domUtils.fillChar(range.document,para);
  11724. }
  11725. tmpRange.insertNode( para );
  11726. var parent = para.parentNode;
  11727. //如果para上一级是一个block元素且不是body,td就删除它
  11728. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11729. //存储dir,style
  11730. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11731. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11732. //trace:1070
  11733. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11734. //trace:1030
  11735. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11736. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11737. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11738. }
  11739. //trace:1706 选择的就是h1-6要删除
  11740. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11741. domUtils.setAttributes(parent,attrs);
  11742. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11743. parent.style.cssText = attrs.style;
  11744. }
  11745. domUtils.remove(para,true);
  11746. para = parent;
  11747. }else{
  11748. domUtils.remove( para.parentNode, true );
  11749. }
  11750. }
  11751. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11752. current = parent;
  11753. }else{
  11754. current = para;
  11755. }
  11756. current = domUtils.getNextDomNode( current, false, filterFn );
  11757. } else {
  11758. current = domUtils.getNextDomNode( current, true, filterFn );
  11759. }
  11760. }
  11761. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11762. };
  11763. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11764. me.commands['paragraph'] = {
  11765. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11766. var range = this.selection.getRange();
  11767. //闭合时单独处理
  11768. if(range.collapsed){
  11769. var txt = this.document.createTextNode('p');
  11770. range.insertNode(txt);
  11771. //去掉冗余的fillchar
  11772. if(browser.ie){
  11773. var node = txt.previousSibling;
  11774. if(node && domUtils.isWhitespace(node)){
  11775. domUtils.remove(node);
  11776. }
  11777. node = txt.nextSibling;
  11778. if(node && domUtils.isWhitespace(node)){
  11779. domUtils.remove(node);
  11780. }
  11781. }
  11782. }
  11783. range = doParagraph(range,style,attrs,sourceCmdName);
  11784. if(txt){
  11785. range.setStartBefore(txt).collapse(true);
  11786. pN = txt.parentNode;
  11787. domUtils.remove(txt);
  11788. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11789. domUtils.fillNode(this.document,pN);
  11790. }
  11791. }
  11792. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11793. var child = range.startContainer.childNodes[range.startOffset];
  11794. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11795. range.setStart(child,0).collapse(true);
  11796. }
  11797. }
  11798. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11799. range.select();
  11800. return true;
  11801. },
  11802. queryCommandValue : function() {
  11803. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11804. return node ? node.tagName.toLowerCase() : '';
  11805. }
  11806. };
  11807. };
  11808. // plugins/directionality.js
  11809. /**
  11810. * 设置文字输入的方向的插件
  11811. * @file
  11812. * @since 1.2.6.1
  11813. */
  11814. (function() {
  11815. var block = domUtils.isBlockElm ,
  11816. getObj = function(editor){
  11817. // var startNode = editor.selection.getStart(),
  11818. // parents;
  11819. // if ( startNode ) {
  11820. // //查找所有的是block的父亲节点
  11821. // parents = domUtils.findParents( startNode, true, block, true );
  11822. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11823. // if ( ci.getAttribute( 'dir' ) ) {
  11824. // return ci;
  11825. // }
  11826. // }
  11827. // }
  11828. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  11829. },
  11830. doDirectionality = function(range,editor,forward){
  11831. var bookmark,
  11832. filterFn = function( node ) {
  11833. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11834. },
  11835. obj = getObj( editor );
  11836. if ( obj && range.collapsed ) {
  11837. obj.setAttribute( 'dir', forward );
  11838. return range;
  11839. }
  11840. bookmark = range.createBookmark();
  11841. range.enlarge( true );
  11842. var bookmark2 = range.createBookmark(),
  11843. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11844. tmpRange = range.cloneRange(),
  11845. tmpNode;
  11846. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11847. if ( current.nodeType == 3 || !block( current ) ) {
  11848. tmpRange.setStartBefore( current );
  11849. while ( current && current !== bookmark2.end && !block( current ) ) {
  11850. tmpNode = current;
  11851. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11852. return !block( node );
  11853. } );
  11854. }
  11855. tmpRange.setEndAfter( tmpNode );
  11856. var common = tmpRange.getCommonAncestor();
  11857. if ( !domUtils.isBody( common ) && block( common ) ) {
  11858. //遍历到了block节点
  11859. common.setAttribute( 'dir', forward );
  11860. current = common;
  11861. } else {
  11862. //没有遍历到,添加一个block节点
  11863. var p = range.document.createElement( 'p' );
  11864. p.setAttribute( 'dir', forward );
  11865. var frag = tmpRange.extractContents();
  11866. p.appendChild( frag );
  11867. tmpRange.insertNode( p );
  11868. current = p;
  11869. }
  11870. current = domUtils.getNextDomNode( current, false, filterFn );
  11871. } else {
  11872. current = domUtils.getNextDomNode( current, true, filterFn );
  11873. }
  11874. }
  11875. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11876. };
  11877. /**
  11878. * 文字输入方向
  11879. * @command directionality
  11880. * @method execCommand
  11881. * @param { String } cmdName 命令字符串
  11882. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11883. * @example
  11884. * ```javascript
  11885. * editor.execCommand( 'directionality', 'ltr');
  11886. * ```
  11887. */
  11888. /**
  11889. * 查询当前选区的文字输入方向
  11890. * @command directionality
  11891. * @method queryCommandValue
  11892. * @param { String } cmdName 命令字符串
  11893. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11894. * @example
  11895. * ```javascript
  11896. * editor.queryCommandValue( 'directionality');
  11897. * ```
  11898. */
  11899. UE.commands['directionality'] = {
  11900. execCommand : function( cmdName,forward ) {
  11901. var range = this.selection.getRange();
  11902. //闭合时单独处理
  11903. if(range.collapsed){
  11904. var txt = this.document.createTextNode('d');
  11905. range.insertNode(txt);
  11906. }
  11907. doDirectionality(range,this,forward);
  11908. if(txt){
  11909. range.setStartBefore(txt).collapse(true);
  11910. domUtils.remove(txt);
  11911. }
  11912. range.select();
  11913. return true;
  11914. },
  11915. queryCommandValue : function() {
  11916. var node = getObj(this);
  11917. return node ? node.getAttribute('dir') : 'ltr';
  11918. }
  11919. };
  11920. })();
  11921. // plugins/horizontal.js
  11922. /**
  11923. * 插入分割线插件
  11924. * @file
  11925. * @since 1.2.6.1
  11926. */
  11927. /**
  11928. * 插入分割线
  11929. * @command horizontal
  11930. * @method execCommand
  11931. * @param { String } cmdName 命令字符串
  11932. * @example
  11933. * ```javascript
  11934. * editor.execCommand( 'horizontal' );
  11935. * ```
  11936. */
  11937. UE.plugins['horizontal'] = function(){
  11938. var me = this;
  11939. me.commands['horizontal'] = {
  11940. execCommand : function( cmdName ) {
  11941. var me = this;
  11942. if(me.queryCommandState(cmdName)!==-1){
  11943. me.execCommand('insertHtml','<hr>');
  11944. var range = me.selection.getRange(),
  11945. start = range.startContainer;
  11946. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  11947. var tmp;
  11948. if(tmp = start.childNodes[range.startOffset - 1]){
  11949. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  11950. if(me.options.enterTag == 'p'){
  11951. tmp = me.document.createElement('p');
  11952. range.insertNode(tmp);
  11953. range.setStart(tmp,0).setCursor();
  11954. }else{
  11955. tmp = me.document.createElement('br');
  11956. range.insertNode(tmp);
  11957. range.setStartBefore(tmp).setCursor();
  11958. }
  11959. }
  11960. }
  11961. }
  11962. return true;
  11963. }
  11964. },
  11965. //边界在table里不能加分隔线
  11966. queryCommandState : function() {
  11967. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  11968. }
  11969. };
  11970. // me.addListener('delkeyup',function(){
  11971. // var rng = this.selection.getRange();
  11972. // if(browser.ie && browser.version > 8){
  11973. // rng.txtToElmBoundary(true);
  11974. // if(domUtils.isStartInblock(rng)){
  11975. // var tmpNode = rng.startContainer;
  11976. // var pre = tmpNode.previousSibling;
  11977. // if(pre && domUtils.isTagNode(pre,'hr')){
  11978. // domUtils.remove(pre);
  11979. // rng.select();
  11980. // return;
  11981. // }
  11982. // }
  11983. // }
  11984. // if(domUtils.isBody(rng.startContainer)){
  11985. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  11986. // if(hr && hr.nodeName == 'HR'){
  11987. // var next = hr.nextSibling;
  11988. // if(next){
  11989. // rng.setStart(next,0)
  11990. // }else if(hr.previousSibling){
  11991. // rng.setStartAtLast(hr.previousSibling)
  11992. // }else{
  11993. // var p = this.document.createElement('p');
  11994. // hr.parentNode.insertBefore(p,hr);
  11995. // domUtils.fillNode(this.document,p);
  11996. // rng.setStart(p,0);
  11997. // }
  11998. // domUtils.remove(hr);
  11999. // rng.setCursor(false,true);
  12000. // }
  12001. // }
  12002. // })
  12003. me.addListener('delkeydown',function(name,evt){
  12004. var rng = this.selection.getRange();
  12005. rng.txtToElmBoundary(true);
  12006. if(domUtils.isStartInblock(rng)){
  12007. var tmpNode = rng.startContainer;
  12008. var pre = tmpNode.previousSibling;
  12009. if(pre && domUtils.isTagNode(pre,'hr')){
  12010. domUtils.remove(pre);
  12011. rng.select();
  12012. domUtils.preventDefault(evt);
  12013. return true;
  12014. }
  12015. }
  12016. })
  12017. };
  12018. // plugins/time.js
  12019. /**
  12020. * 插入时间和日期
  12021. * @file
  12022. * @since 1.2.6.1
  12023. */
  12024. /**
  12025. * 插入时间,默认格式:12:59:59
  12026. * @command time
  12027. * @method execCommand
  12028. * @param { String } cmd 命令字符串
  12029. * @example
  12030. * ```javascript
  12031. * editor.execCommand( 'time');
  12032. * ```
  12033. */
  12034. /**
  12035. * 插入日期,默认格式:2013-08-30
  12036. * @command date
  12037. * @method execCommand
  12038. * @param { String } cmd 命令字符串
  12039. * @example
  12040. * ```javascript
  12041. * editor.execCommand( 'date');
  12042. * ```
  12043. */
  12044. UE.commands['time'] = UE.commands["date"] = {
  12045. execCommand : function(cmd, format){
  12046. var date = new Date;
  12047. function formatTime(date, format) {
  12048. var hh = ('0' + date.getHours()).slice(-2),
  12049. ii = ('0' + date.getMinutes()).slice(-2),
  12050. ss = ('0' + date.getSeconds()).slice(-2);
  12051. format = format || 'hh:ii:ss';
  12052. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12053. }
  12054. function formatDate(date, format) {
  12055. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12056. yy = yyyy.slice(-2),
  12057. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12058. dd = ('0' + date.getDate()).slice(-2);
  12059. format = format || 'yyyy-mm-dd';
  12060. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12061. }
  12062. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12063. }
  12064. };
  12065. // plugins/rowspacing.js
  12066. /**
  12067. * 段前段后间距插件
  12068. * @file
  12069. * @since 1.2.6.1
  12070. */
  12071. /**
  12072. * 设置段间距
  12073. * @command rowspacing
  12074. * @method execCommand
  12075. * @param { String } cmd 命令字符串
  12076. * @param { String } value 段间距的值,以px为单位
  12077. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12078. * @example
  12079. * ```javascript
  12080. * editor.execCommand( 'rowspacing', '10', 'top' );
  12081. * ```
  12082. */
  12083. UE.plugins['rowspacing'] = function(){
  12084. var me = this;
  12085. me.setOpt({
  12086. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12087. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12088. });
  12089. me.commands['rowspacing'] = {
  12090. execCommand : function( cmdName,value,dir ) {
  12091. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12092. return true;
  12093. },
  12094. queryCommandValue : function(cmdName,dir) {
  12095. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12096. value;
  12097. //trace:1026
  12098. if(pN){
  12099. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12100. return !value ? 0 : value;
  12101. }
  12102. return 0;
  12103. }
  12104. };
  12105. };
  12106. // plugins/lineheight.js
  12107. /**
  12108. * 设置行内间距
  12109. * @file
  12110. * @since 1.2.6.1
  12111. */
  12112. UE.plugins['lineheight'] = function(){
  12113. var me = this;
  12114. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12115. /**
  12116. * 行距
  12117. * @command lineheight
  12118. * @method execCommand
  12119. * @param { String } cmdName 命令字符串
  12120. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12121. * @example
  12122. * ```javascript
  12123. * editor.execCommand( 'lineheight', 1.5);
  12124. * ```
  12125. */
  12126. /**
  12127. * 查询当前选区内容的行高大小
  12128. * @command lineheight
  12129. * @method queryCommandValue
  12130. * @param { String } cmd 命令字符串
  12131. * @return { String } 返回当前行高大小
  12132. * @example
  12133. * ```javascript
  12134. * editor.queryCommandValue( 'lineheight' );
  12135. * ```
  12136. */
  12137. me.commands['lineheight'] = {
  12138. execCommand : function( cmdName,value ) {
  12139. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12140. return true;
  12141. },
  12142. queryCommandValue : function() {
  12143. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12144. if(pN){
  12145. var value = domUtils.getComputedStyle(pN,'line-height');
  12146. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12147. }
  12148. }
  12149. };
  12150. };
  12151. // plugins/insertcode.js
  12152. /**
  12153. * 插入代码插件
  12154. * @file
  12155. * @since 1.2.6.1
  12156. */
  12157. UE.plugins['insertcode'] = function() {
  12158. var me = this;
  12159. me.ready(function(){
  12160. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12161. me.document)
  12162. });
  12163. me.setOpt('insertcode',{
  12164. 'as3':'ActionScript3',
  12165. 'bash':'Bash/Shell',
  12166. 'cpp':'C/C++',
  12167. 'css':'Css',
  12168. 'cf':'CodeFunction',
  12169. 'c#':'C#',
  12170. 'delphi':'Delphi',
  12171. 'diff':'Diff',
  12172. 'erlang':'Erlang',
  12173. 'groovy':'Groovy',
  12174. 'html':'Html',
  12175. 'java':'Java',
  12176. 'jfx':'JavaFx',
  12177. 'js':'Javascript',
  12178. 'pl':'Perl',
  12179. 'php':'Php',
  12180. 'plain':'Plain Text',
  12181. 'ps':'PowerShell',
  12182. 'python':'Python',
  12183. 'ruby':'Ruby',
  12184. 'scala':'Scala',
  12185. 'sql':'Sql',
  12186. 'vb':'Vb',
  12187. 'xml':'Xml'
  12188. });
  12189. /**
  12190. * 插入代码
  12191. * @command insertcode
  12192. * @method execCommand
  12193. * @param { String } cmd 命令字符串
  12194. * @param { String } lang 插入代码的语言
  12195. * @example
  12196. * ```javascript
  12197. * editor.execCommand( 'insertcode', 'javascript' );
  12198. * ```
  12199. */
  12200. /**
  12201. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12202. * @command insertcode
  12203. * @method queryCommandValue
  12204. * @param { String } cmd 命令字符串
  12205. * @return { String } 返回代码的语言
  12206. * @example
  12207. * ```javascript
  12208. * editor.queryCommandValue( 'insertcode' );
  12209. * ```
  12210. */
  12211. me.commands['insertcode'] = {
  12212. execCommand : function(cmd,lang){
  12213. var me = this,
  12214. rng = me.selection.getRange(),
  12215. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12216. if(pre){
  12217. pre.className = 'brush:'+lang+';toolbar:false;';
  12218. }else{
  12219. var code = '';
  12220. if(rng.collapsed){
  12221. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12222. }else{
  12223. var frag = rng.extractContents();
  12224. var div = me.document.createElement('div');
  12225. div.appendChild(frag);
  12226. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12227. if(browser.ie && browser.ie11below && browser.version > 8){
  12228. if(node.type =='element'){
  12229. if(node.tagName == 'br'){
  12230. code += '\n'
  12231. }else if(!dtd.$empty[node.tagName]){
  12232. utils.each(node.children,function(cn){
  12233. if(cn.type =='element'){
  12234. if(cn.tagName == 'br'){
  12235. code += '\n'
  12236. }else if(!dtd.$empty[node.tagName]){
  12237. code += cn.innerText();
  12238. }
  12239. }else{
  12240. code += cn.data
  12241. }
  12242. })
  12243. if(!/\n$/.test(code)){
  12244. code += '\n';
  12245. }
  12246. }
  12247. }else{
  12248. code += node.data + '\n'
  12249. }
  12250. if(!node.nextSibling() && /\n$/.test(code)){
  12251. code = code.replace(/\n$/,'');
  12252. }
  12253. }else{
  12254. if(browser.ie && browser.ie11below){
  12255. if(node.type =='element'){
  12256. if(node.tagName == 'br'){
  12257. code += '<br>'
  12258. }else if(!dtd.$empty[node.tagName]){
  12259. utils.each(node.children,function(cn){
  12260. if(cn.type =='element'){
  12261. if(cn.tagName == 'br'){
  12262. code += '<br>'
  12263. }else if(!dtd.$empty[node.tagName]){
  12264. code += cn.innerText();
  12265. }
  12266. }else{
  12267. code += cn.data
  12268. }
  12269. });
  12270. if(!/br>$/.test(code)){
  12271. code += '<br>';
  12272. }
  12273. }
  12274. }else{
  12275. code += node.data + '<br>'
  12276. }
  12277. if(!node.nextSibling() && /<br>$/.test(code)){
  12278. code = code.replace(/<br>$/,'');
  12279. }
  12280. }else{
  12281. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12282. if(!/br\/?\s*>$/.test(code)){
  12283. if(!node.nextSibling())
  12284. return;
  12285. code += '<br>'
  12286. }
  12287. }
  12288. }
  12289. });
  12290. }
  12291. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12292. pre = me.document.getElementById('coder');
  12293. domUtils.removeAttributes(pre,'id');
  12294. var tmpNode = pre.previousSibling;
  12295. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12296. domUtils.remove(tmpNode)
  12297. }
  12298. var rng = me.selection.getRange();
  12299. if(domUtils.isEmptyBlock(pre)){
  12300. rng.setStart(pre,0).setCursor(false,true)
  12301. }else{
  12302. rng.selectNodeContents(pre).select()
  12303. }
  12304. }
  12305. },
  12306. queryCommandValue : function(){
  12307. var path = this.selection.getStartElementPath();
  12308. var lang = '';
  12309. utils.each(path,function(node){
  12310. if(node.nodeName =='PRE'){
  12311. var match = node.className.match(/brush:([^;]+)/);
  12312. lang = match && match[1] ? match[1] : '';
  12313. return false;
  12314. }
  12315. });
  12316. return lang;
  12317. }
  12318. };
  12319. me.addInputRule(function(root){
  12320. utils.each(root.getNodesByTagName('pre'),function(pre){
  12321. var brs = pre.getNodesByTagName('br');
  12322. if(brs.length){
  12323. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12324. var txt = UE.uNode.createText('\n');
  12325. br.parentNode.insertBefore(txt,br);
  12326. br.parentNode.removeChild(br);
  12327. });
  12328. return;
  12329. }
  12330. if(browser.ie && browser.ie11below && browser.version > 8)
  12331. return;
  12332. var code = pre.innerText().split(/\n/);
  12333. pre.innerHTML('');
  12334. utils.each(code,function(c){
  12335. if(c.length){
  12336. pre.appendChild(UE.uNode.createText(c));
  12337. }
  12338. pre.appendChild(UE.uNode.createElement('br'))
  12339. })
  12340. })
  12341. });
  12342. me.addOutputRule(function(root){
  12343. utils.each(root.getNodesByTagName('pre'),function(pre){
  12344. var code = '';
  12345. utils.each(pre.children,function(n){
  12346. if(n.type == 'text'){
  12347. //在ie下文本内容有可能末尾带有\n要去掉
  12348. //trace:3396
  12349. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12350. }else{
  12351. if(n.tagName == 'br'){
  12352. code += '\n'
  12353. }else{
  12354. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12355. }
  12356. }
  12357. });
  12358. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12359. })
  12360. });
  12361. //不需要判断highlight的command列表
  12362. me.notNeedCodeQuery ={
  12363. help:1,
  12364. undo:1,
  12365. redo:1,
  12366. source:1,
  12367. print:1,
  12368. searchreplace:1,
  12369. fullscreen:1,
  12370. preview:1,
  12371. insertparagraph:1,
  12372. elementpath:1,
  12373. insertcode:1,
  12374. inserthtml:1,
  12375. selectall:1
  12376. };
  12377. //将queyCommamndState重置
  12378. var orgQuery = me.queryCommandState;
  12379. me.queryCommandState = function(cmd){
  12380. var me = this;
  12381. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12382. return -1;
  12383. }
  12384. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12385. };
  12386. me.addListener('beforeenterkeydown',function(){
  12387. var rng = me.selection.getRange();
  12388. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12389. if(pre){
  12390. me.fireEvent('saveScene');
  12391. if(!rng.collapsed){
  12392. rng.deleteContents();
  12393. }
  12394. if(!browser.ie || browser.ie9above){
  12395. var tmpNode = me.document.createElement('br'),pre;
  12396. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12397. var next = tmpNode.nextSibling;
  12398. if(!next && (!browser.ie || browser.version > 10)){
  12399. rng.insertNode(tmpNode.cloneNode(false));
  12400. }else{
  12401. rng.setStartAfter(tmpNode);
  12402. }
  12403. pre = tmpNode.previousSibling;
  12404. var tmp;
  12405. while(pre ){
  12406. tmp = pre;
  12407. pre = pre.previousSibling;
  12408. if(!pre || pre.nodeName == 'BR'){
  12409. pre = tmp;
  12410. break;
  12411. }
  12412. }
  12413. if(pre){
  12414. var str = '';
  12415. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12416. str += pre.nodeValue;
  12417. pre = pre.nextSibling;
  12418. }
  12419. if(pre.nodeName != 'BR'){
  12420. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12421. if(match && match[1]){
  12422. str += match[1]
  12423. }
  12424. }
  12425. if(str){
  12426. str = me.document.createTextNode(str);
  12427. rng.insertNode(str).setStartAfter(str);
  12428. }
  12429. }
  12430. rng.collapse(true).select(true);
  12431. }else{
  12432. if(browser.version > 8){
  12433. var txt = me.document.createTextNode('\n');
  12434. var start = rng.startContainer;
  12435. if(rng.startOffset == 0){
  12436. var preNode = start.previousSibling;
  12437. if(preNode){
  12438. rng.insertNode(txt);
  12439. var fillchar = me.document.createTextNode(' ');
  12440. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12441. }
  12442. }else{
  12443. rng.insertNode(txt).setStartAfter(txt);
  12444. var fillchar = me.document.createTextNode(' ');
  12445. start = rng.startContainer.childNodes[rng.startOffset];
  12446. if(start && !/^\n/.test(start.nodeValue)){
  12447. rng.setStartBefore(txt)
  12448. }
  12449. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12450. }
  12451. }else{
  12452. var tmpNode = me.document.createElement('br');
  12453. rng.insertNode(tmpNode);
  12454. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12455. rng.setStartAfter(tmpNode);
  12456. pre = tmpNode.previousSibling;
  12457. var tmp;
  12458. while(pre ){
  12459. tmp = pre;
  12460. pre = pre.previousSibling;
  12461. if(!pre || pre.nodeName == 'BR'){
  12462. pre = tmp;
  12463. break;
  12464. }
  12465. }
  12466. if(pre){
  12467. var str = '';
  12468. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12469. str += pre.nodeValue;
  12470. pre = pre.nextSibling;
  12471. }
  12472. if(pre.nodeName != 'BR'){
  12473. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12474. if(match && match[1]){
  12475. str += match[1]
  12476. }
  12477. }
  12478. str = me.document.createTextNode(str);
  12479. rng.insertNode(str).setStartAfter(str);
  12480. }
  12481. rng.collapse(true).select();
  12482. }
  12483. }
  12484. me.fireEvent('saveScene');
  12485. return true;
  12486. }
  12487. });
  12488. me.addListener('tabkeydown',function(cmd,evt){
  12489. var rng = me.selection.getRange();
  12490. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12491. if(pre){
  12492. me.fireEvent('saveScene');
  12493. if(evt.shiftKey){
  12494. }else{
  12495. if(!rng.collapsed){
  12496. var bk = rng.createBookmark();
  12497. var start = bk.start.previousSibling;
  12498. while(start){
  12499. if(pre.firstChild === start && !domUtils.isBr(start)){
  12500. pre.insertBefore(me.document.createTextNode(' '),start);
  12501. break;
  12502. }
  12503. if(domUtils.isBr(start)){
  12504. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12505. break;
  12506. }
  12507. start = start.previousSibling;
  12508. }
  12509. var end = bk.end;
  12510. start = bk.start.nextSibling;
  12511. if(pre.firstChild === bk.start){
  12512. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12513. }
  12514. while(start && start !== end){
  12515. if(domUtils.isBr(start) && start.nextSibling){
  12516. if(start.nextSibling === end){
  12517. break;
  12518. }
  12519. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12520. }
  12521. start = start.nextSibling;
  12522. }
  12523. rng.moveToBookmark(bk).select();
  12524. }else{
  12525. var tmpNode = me.document.createTextNode(' ');
  12526. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12527. }
  12528. }
  12529. me.fireEvent('saveScene');
  12530. return true;
  12531. }
  12532. });
  12533. me.addListener('beforeinserthtml',function(evtName,html){
  12534. var me = this,
  12535. rng = me.selection.getRange(),
  12536. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12537. if(pre){
  12538. if(!rng.collapsed){
  12539. rng.deleteContents()
  12540. }
  12541. var htmlstr = '';
  12542. if(browser.ie && browser.version > 8){
  12543. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12544. if(node.type =='element'){
  12545. if(node.tagName == 'br'){
  12546. htmlstr += '\n'
  12547. }else if(!dtd.$empty[node.tagName]){
  12548. utils.each(node.children,function(cn){
  12549. if(cn.type =='element'){
  12550. if(cn.tagName == 'br'){
  12551. htmlstr += '\n'
  12552. }else if(!dtd.$empty[node.tagName]){
  12553. htmlstr += cn.innerText();
  12554. }
  12555. }else{
  12556. htmlstr += cn.data
  12557. }
  12558. })
  12559. if(!/\n$/.test(htmlstr)){
  12560. htmlstr += '\n';
  12561. }
  12562. }
  12563. }else{
  12564. htmlstr += node.data + '\n'
  12565. }
  12566. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12567. htmlstr = htmlstr.replace(/\n$/,'');
  12568. }
  12569. });
  12570. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12571. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12572. }else{
  12573. var frag = me.document.createDocumentFragment();
  12574. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12575. if(node.type =='element'){
  12576. if(node.tagName == 'br'){
  12577. frag.appendChild(me.document.createElement('br'))
  12578. }else if(!dtd.$empty[node.tagName]){
  12579. utils.each(node.children,function(cn){
  12580. if(cn.type =='element'){
  12581. if(cn.tagName == 'br'){
  12582. frag.appendChild(me.document.createElement('br'))
  12583. }else if(!dtd.$empty[node.tagName]){
  12584. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12585. }
  12586. }else{
  12587. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12588. }
  12589. })
  12590. if(frag.lastChild.nodeName != 'BR'){
  12591. frag.appendChild(me.document.createElement('br'))
  12592. }
  12593. }
  12594. }else{
  12595. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12596. }
  12597. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12598. frag.removeChild(frag.lastChild)
  12599. }
  12600. });
  12601. rng.insertNode(frag).select();
  12602. }
  12603. return true;
  12604. }
  12605. });
  12606. //方向键的处理
  12607. me.addListener('keydown',function(cmd,evt){
  12608. var me = this,keyCode = evt.keyCode || evt.which;
  12609. if(keyCode == 40){
  12610. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12611. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12612. var last = pre.lastChild
  12613. while(last && last.nodeName == 'BR'){
  12614. last = last.previousSibling;
  12615. }
  12616. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12617. me.execCommand('insertparagraph');
  12618. domUtils.preventDefault(evt)
  12619. }
  12620. }
  12621. }
  12622. });
  12623. //trace:3395
  12624. me.addListener('delkeydown',function(type,evt){
  12625. var rng = this.selection.getRange();
  12626. rng.txtToElmBoundary(true);
  12627. var start = rng.startContainer;
  12628. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12629. var p = me.document.createElement('p');
  12630. domUtils.fillNode(me.document,p);
  12631. start.parentNode.insertBefore(p,start);
  12632. domUtils.remove(start);
  12633. rng.setStart(p,0).setCursor(false,true);
  12634. domUtils.preventDefault(evt);
  12635. return true;
  12636. }
  12637. })
  12638. };
  12639. // plugins/cleardoc.js
  12640. /**
  12641. * 清空文档插件
  12642. * @file
  12643. * @since 1.2.6.1
  12644. */
  12645. /**
  12646. * 清空文档
  12647. * @command cleardoc
  12648. * @method execCommand
  12649. * @param { String } cmd 命令字符串
  12650. * @example
  12651. * ```javascript
  12652. * //editor 是编辑器实例
  12653. * editor.execCommand('cleardoc');
  12654. * ```
  12655. */
  12656. UE.commands['cleardoc'] = {
  12657. execCommand : function( cmdName) {
  12658. var me = this,
  12659. enterTag = me.options.enterTag,
  12660. range = me.selection.getRange();
  12661. if(enterTag == "br"){
  12662. me.body.innerHTML = "<br/>";
  12663. range.setStart(me.body,0).setCursor();
  12664. }else{
  12665. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12666. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12667. }
  12668. setTimeout(function(){
  12669. me.fireEvent("clearDoc");
  12670. },0);
  12671. }
  12672. };
  12673. // plugins/anchor.js
  12674. /**
  12675. * 锚点插件,为UEditor提供插入锚点支持
  12676. * @file
  12677. * @since 1.2.6.1
  12678. */
  12679. UE.plugin.register('anchor', function (){
  12680. return {
  12681. bindEvents:{
  12682. 'ready':function(){
  12683. utils.cssRule('anchor',
  12684. '.anchorclass{background: url(\''
  12685. + this.options.themePath
  12686. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12687. this.document);
  12688. }
  12689. },
  12690. outputRule: function(root){
  12691. utils.each(root.getNodesByTagName('img'),function(a){
  12692. var val;
  12693. if(val = a.getAttr('anchorname')){
  12694. a.tagName = 'a';
  12695. a.setAttr({
  12696. anchorname : '',
  12697. name : val,
  12698. 'class' : ''
  12699. })
  12700. }
  12701. })
  12702. },
  12703. inputRule:function(root){
  12704. utils.each(root.getNodesByTagName('a'),function(a){
  12705. var val;
  12706. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12707. a.tagName = 'img';
  12708. a.setAttr({
  12709. anchorname :a.getAttr('name'),
  12710. 'class' : 'anchorclass'
  12711. });
  12712. a.setAttr('name')
  12713. }
  12714. })
  12715. },
  12716. commands:{
  12717. /**
  12718. * 插入锚点
  12719. * @command anchor
  12720. * @method execCommand
  12721. * @param { String } cmd 命令字符串
  12722. * @param { String } name 锚点名称字符串
  12723. * @example
  12724. * ```javascript
  12725. * //editor 是编辑器实例
  12726. * editor.execCommand('anchor', 'anchor1');
  12727. * ```
  12728. */
  12729. 'anchor':{
  12730. execCommand:function (cmd, name) {
  12731. var range = this.selection.getRange(),img = range.getClosedNode();
  12732. if (img && img.getAttribute('anchorname')) {
  12733. if (name) {
  12734. img.setAttribute('anchorname', name);
  12735. } else {
  12736. range.setStartBefore(img).setCursor();
  12737. domUtils.remove(img);
  12738. }
  12739. } else {
  12740. if (name) {
  12741. //只在选区的开始插入
  12742. var anchor = this.document.createElement('img');
  12743. range.collapse(true);
  12744. domUtils.setAttributes(anchor,{
  12745. 'anchorname':name,
  12746. 'class':'anchorclass'
  12747. });
  12748. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12749. }
  12750. }
  12751. }
  12752. }
  12753. }
  12754. }
  12755. });
  12756. // plugins/wordcount.js
  12757. ///import core
  12758. ///commands 字数统计
  12759. ///commandsName WordCount,wordCount
  12760. ///commandsTitle 字数统计
  12761. /*
  12762. * Created by JetBrains WebStorm.
  12763. * User: taoqili
  12764. * Date: 11-9-7
  12765. * Time: 下午8:18
  12766. * To change this template use File | Settings | File Templates.
  12767. */
  12768. UE.plugins['wordcount'] = function(){
  12769. var me = this;
  12770. me.setOpt('wordCount',true);
  12771. me.addListener('contentchange',function(){
  12772. me.fireEvent('wordcount');
  12773. });
  12774. var timer;
  12775. me.addListener('ready',function(){
  12776. var me = this;
  12777. domUtils.on(me.body,"keyup",function(evt){
  12778. var code = evt.keyCode||evt.which,
  12779. //忽略的按键,ctr,alt,shift,方向键
  12780. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12781. if(code in ignores) return;
  12782. clearTimeout(timer);
  12783. timer = setTimeout(function(){
  12784. me.fireEvent('wordcount');
  12785. },200)
  12786. })
  12787. });
  12788. };
  12789. // plugins/pagebreak.js
  12790. /**
  12791. * 分页功能插件
  12792. * @file
  12793. * @since 1.2.6.1
  12794. */
  12795. UE.plugins['pagebreak'] = function () {
  12796. var me = this,
  12797. notBreakTags = ['td'];
  12798. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12799. function fillNode(node){
  12800. if(domUtils.isEmptyBlock(node)){
  12801. var firstChild = node.firstChild,tmpNode;
  12802. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12803. tmpNode = firstChild;
  12804. firstChild = firstChild.firstChild;
  12805. }
  12806. !tmpNode && (tmpNode = node);
  12807. domUtils.fillNode(me.document,tmpNode);
  12808. }
  12809. }
  12810. //分页符样式添加
  12811. me.ready(function(){
  12812. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12813. });
  12814. function isHr(node){
  12815. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12816. }
  12817. me.addInputRule(function(root){
  12818. root.traversal(function(node){
  12819. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12820. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12821. node.parentNode.insertBefore(hr,node);
  12822. node.parentNode.removeChild(node)
  12823. }
  12824. })
  12825. });
  12826. me.addOutputRule(function(node){
  12827. utils.each(node.getNodesByTagName('hr'),function(n){
  12828. if(n.getAttr('class') == 'pagebreak'){
  12829. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12830. n.parentNode.insertBefore(txt,n);
  12831. n.parentNode.removeChild(n);
  12832. }
  12833. })
  12834. });
  12835. /**
  12836. * 插入分页符
  12837. * @command pagebreak
  12838. * @method execCommand
  12839. * @param { String } cmd 命令字符串
  12840. * @remind 在表格中插入分页符会把表格切分成两部分
  12841. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12842. * 以便于提交数据到服务器端后处理分页。
  12843. * @example
  12844. * ```javascript
  12845. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12846. * ```
  12847. */
  12848. me.commands['pagebreak'] = {
  12849. execCommand:function () {
  12850. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12851. domUtils.setAttributes(hr,{
  12852. 'class' : 'pagebreak',
  12853. noshade:"noshade",
  12854. size:"5"
  12855. });
  12856. domUtils.unSelectable(hr);
  12857. //table单独处理
  12858. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12859. parents = [], pN;
  12860. if (node) {
  12861. switch (node.tagName) {
  12862. case 'TD':
  12863. pN = node.parentNode;
  12864. if (!pN.previousSibling) {
  12865. var table = domUtils.findParentByTagName(pN, 'table');
  12866. // var tableWrapDiv = table.parentNode;
  12867. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12868. // && tableWrapDiv.tagName == 'DIV'
  12869. // && tableWrapDiv.getAttribute('dropdrag')
  12870. // ){
  12871. // domUtils.remove(tableWrapDiv,true);
  12872. // }
  12873. table.parentNode.insertBefore(hr, table);
  12874. parents = domUtils.findParents(hr, true);
  12875. } else {
  12876. pN.parentNode.insertBefore(hr, pN);
  12877. parents = domUtils.findParents(hr);
  12878. }
  12879. pN = parents[1];
  12880. if (hr !== pN) {
  12881. domUtils.breakParent(hr, pN);
  12882. }
  12883. //table要重写绑定一下拖拽
  12884. me.fireEvent('afteradjusttable',me.document);
  12885. }
  12886. } else {
  12887. if (!range.collapsed) {
  12888. range.deleteContents();
  12889. var start = range.startContainer;
  12890. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12891. range.setStartBefore(start).collapse(true);
  12892. domUtils.remove(start);
  12893. start = range.startContainer;
  12894. }
  12895. }
  12896. range.insertNode(hr);
  12897. var pN = hr.parentNode, nextNode;
  12898. while (!domUtils.isBody(pN)) {
  12899. domUtils.breakParent(hr, pN);
  12900. nextNode = hr.nextSibling;
  12901. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12902. domUtils.remove(nextNode);
  12903. }
  12904. pN = hr.parentNode;
  12905. }
  12906. nextNode = hr.nextSibling;
  12907. var pre = hr.previousSibling;
  12908. if(isHr(pre)){
  12909. domUtils.remove(pre);
  12910. }else{
  12911. pre && fillNode(pre);
  12912. }
  12913. if(!nextNode){
  12914. var p = me.document.createElement('p');
  12915. hr.parentNode.appendChild(p);
  12916. domUtils.fillNode(me.document,p);
  12917. range.setStart(p,0).collapse(true);
  12918. }else{
  12919. if(isHr(nextNode)){
  12920. domUtils.remove(nextNode);
  12921. }else{
  12922. fillNode(nextNode);
  12923. }
  12924. range.setEndAfter(hr).collapse(false);
  12925. }
  12926. range.select(true);
  12927. }
  12928. }
  12929. };
  12930. };
  12931. // plugins/wordimage.js
  12932. ///import core
  12933. ///commands 本地图片引导上传
  12934. ///commandsName WordImage
  12935. ///commandsTitle 本地图片引导上传
  12936. ///commandsDialog dialogs\wordimage
  12937. UE.plugin.register('wordimage',function(){
  12938. var me = this,
  12939. images = [];
  12940. return {
  12941. commands : {
  12942. 'wordimage':{
  12943. execCommand:function () {
  12944. var images = domUtils.getElementsByTagName(me.body, "img");
  12945. var urlList = [];
  12946. for (var i = 0, ci; ci = images[i++];) {
  12947. var url = ci.getAttribute("word_img");
  12948. url && urlList.push(url);
  12949. }
  12950. return urlList;
  12951. },
  12952. queryCommandState:function () {
  12953. images = domUtils.getElementsByTagName(me.body, "img");
  12954. for (var i = 0, ci; ci = images[i++];) {
  12955. if (ci.getAttribute("word_img")) {
  12956. return 1;
  12957. }
  12958. }
  12959. return -1;
  12960. },
  12961. notNeedUndo:true
  12962. }
  12963. },
  12964. inputRule : function (root) {
  12965. utils.each(root.getNodesByTagName('img'), function (img) {
  12966. var attrs = img.attrs,
  12967. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  12968. opt = me.options,
  12969. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  12970. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  12971. img.setAttr({
  12972. width:attrs.width,
  12973. height:attrs.height,
  12974. alt:attrs.alt,
  12975. word_img: attrs.src,
  12976. src:src,
  12977. 'style':'background:url(' + ( flag ? opt.themePath + opt.theme + '/images/word.gif' : opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'
  12978. })
  12979. }
  12980. })
  12981. }
  12982. }
  12983. });
  12984. // plugins/dragdrop.js
  12985. UE.plugins['dragdrop'] = function (){
  12986. var me = this;
  12987. me.ready(function(){
  12988. domUtils.on(this.body,'dragend',function(){
  12989. var rng = me.selection.getRange();
  12990. var node = rng.getClosedNode()||me.selection.getStart();
  12991. if(node && node.tagName == 'IMG'){
  12992. var pre = node.previousSibling,next;
  12993. while(next = node.nextSibling){
  12994. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  12995. domUtils.remove(next)
  12996. }else{
  12997. break;
  12998. }
  12999. }
  13000. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13001. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13002. pre.appendChild(node);
  13003. domUtils.moveChild(next,pre);
  13004. domUtils.remove(next);
  13005. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13006. next.insertBefore(node,next.firstChild);
  13007. }
  13008. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13009. domUtils.remove(pre)
  13010. }
  13011. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13012. domUtils.remove(next)
  13013. }
  13014. rng.selectNode(node).select();
  13015. me.fireEvent('saveScene');
  13016. }
  13017. }
  13018. })
  13019. });
  13020. me.addListener('keyup', function(type, evt) {
  13021. var keyCode = evt.keyCode || evt.which;
  13022. if (keyCode == 13) {
  13023. var rng = me.selection.getRange(),node;
  13024. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13025. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13026. domUtils.removeStyle(node,'text-align')
  13027. }
  13028. }
  13029. }
  13030. })
  13031. };
  13032. // plugins/undo.js
  13033. /**
  13034. * undo redo
  13035. * @file
  13036. * @since 1.2.6.1
  13037. */
  13038. /**
  13039. * 撤销上一次执行的命令
  13040. * @command undo
  13041. * @method execCommand
  13042. * @param { String } cmd 命令字符串
  13043. * @example
  13044. * ```javascript
  13045. * editor.execCommand( 'undo' );
  13046. * ```
  13047. */
  13048. /**
  13049. * 重做上一次执行的命令
  13050. * @command redo
  13051. * @method execCommand
  13052. * @param { String } cmd 命令字符串
  13053. * @example
  13054. * ```javascript
  13055. * editor.execCommand( 'redo' );
  13056. * ```
  13057. */
  13058. UE.plugins['undo'] = function () {
  13059. var saveSceneTimer;
  13060. var me = this,
  13061. maxUndoCount = me.options.maxUndoCount || 20,
  13062. maxInputCount = me.options.maxInputCount || 20,
  13063. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13064. var noNeedFillCharTags = {
  13065. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13066. };
  13067. var orgState = me.options.autoClearEmptyNode;
  13068. function compareAddr(indexA, indexB) {
  13069. if (indexA.length != indexB.length)
  13070. return 0;
  13071. for (var i = 0, l = indexA.length; i < l; i++) {
  13072. if (indexA[i] != indexB[i])
  13073. return 0
  13074. }
  13075. return 1;
  13076. }
  13077. function compareRangeAddress(rngAddrA, rngAddrB) {
  13078. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13079. return 0;
  13080. }
  13081. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13082. return 0;
  13083. }
  13084. return 1;
  13085. }
  13086. function UndoManager() {
  13087. this.list = [];
  13088. this.index = 0;
  13089. this.hasUndo = false;
  13090. this.hasRedo = false;
  13091. this.undo = function () {
  13092. if (this.hasUndo) {
  13093. if (!this.list[this.index - 1] && this.list.length == 1) {
  13094. this.reset();
  13095. return;
  13096. }
  13097. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13098. this.index--;
  13099. if (this.index == 0) {
  13100. return this.restore(0);
  13101. }
  13102. }
  13103. this.restore(--this.index);
  13104. }
  13105. };
  13106. this.redo = function () {
  13107. if (this.hasRedo) {
  13108. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13109. this.index++;
  13110. if (this.index == this.list.length - 1) {
  13111. return this.restore(this.index);
  13112. }
  13113. }
  13114. this.restore(++this.index);
  13115. }
  13116. };
  13117. this.restore = function () {
  13118. var me = this.editor;
  13119. var scene = this.list[this.index];
  13120. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13121. me.options.autoClearEmptyNode = false;
  13122. me.filterInputRule(root);
  13123. me.options.autoClearEmptyNode = orgState;
  13124. //trace:873
  13125. //去掉展位符
  13126. me.document.body.innerHTML = root.toHtml();
  13127. me.fireEvent('afterscencerestore');
  13128. //处理undo后空格不展位的问题
  13129. if (browser.ie) {
  13130. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13131. if(domUtils.isEmptyNode(node)){
  13132. domUtils.fillNode(me.document, node);
  13133. }
  13134. })
  13135. }
  13136. try{
  13137. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13138. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13139. }catch(e){}
  13140. this.update();
  13141. this.clearKey();
  13142. //不能把自己reset了
  13143. me.fireEvent('reset', true);
  13144. };
  13145. this.getScene = function () {
  13146. var me = this.editor;
  13147. var rng = me.selection.getRange(),
  13148. rngAddress = rng.createAddress(false,true);
  13149. me.fireEvent('beforegetscene');
  13150. var root = UE.htmlparser(me.body.innerHTML);
  13151. me.options.autoClearEmptyNode = false;
  13152. me.filterOutputRule(root);
  13153. me.options.autoClearEmptyNode = orgState;
  13154. var cont = root.toHtml();
  13155. //trace:3461
  13156. //这个会引起回退时导致空格丢失的情况
  13157. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13158. me.fireEvent('aftergetscene');
  13159. return {
  13160. address:rngAddress,
  13161. content:cont
  13162. }
  13163. };
  13164. this.save = function (notCompareRange,notSetCursor) {
  13165. clearTimeout(saveSceneTimer);
  13166. var currentScene = this.getScene(notSetCursor),
  13167. lastScene = this.list[this.index];
  13168. if(lastScene && lastScene.content != currentScene.content){
  13169. me.trigger('contentchange')
  13170. }
  13171. //内容相同位置相同不存
  13172. if (lastScene && lastScene.content == currentScene.content &&
  13173. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13174. ) {
  13175. return;
  13176. }
  13177. this.list = this.list.slice(0, this.index + 1);
  13178. this.list.push(currentScene);
  13179. //如果大于最大数量了,就把最前的剔除
  13180. if (this.list.length > maxUndoCount) {
  13181. this.list.shift();
  13182. }
  13183. this.index = this.list.length - 1;
  13184. this.clearKey();
  13185. //跟新undo/redo状态
  13186. this.update();
  13187. };
  13188. this.update = function () {
  13189. this.hasRedo = !!this.list[this.index + 1];
  13190. this.hasUndo = !!this.list[this.index - 1];
  13191. };
  13192. this.reset = function () {
  13193. this.list = [];
  13194. this.index = 0;
  13195. this.hasUndo = false;
  13196. this.hasRedo = false;
  13197. this.clearKey();
  13198. };
  13199. this.clearKey = function () {
  13200. keycont = 0;
  13201. lastKeyCode = null;
  13202. };
  13203. }
  13204. me.undoManger = new UndoManager();
  13205. me.undoManger.editor = me;
  13206. function saveScene() {
  13207. this.undoManger.save();
  13208. }
  13209. me.addListener('saveScene', function () {
  13210. var args = Array.prototype.splice.call(arguments,1);
  13211. this.undoManger.save.apply(this.undoManger,args);
  13212. });
  13213. // me.addListener('beforeexeccommand', saveScene);
  13214. // me.addListener('afterexeccommand', saveScene);
  13215. me.addListener('reset', function (type, exclude) {
  13216. if (!exclude) {
  13217. this.undoManger.reset();
  13218. }
  13219. });
  13220. me.commands['redo'] = me.commands['undo'] = {
  13221. execCommand:function (cmdName) {
  13222. this.undoManger[cmdName]();
  13223. },
  13224. queryCommandState:function (cmdName) {
  13225. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13226. },
  13227. notNeedUndo:1
  13228. };
  13229. var keys = {
  13230. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13231. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13232. 37:1, 38:1, 39:1, 40:1
  13233. },
  13234. keycont = 0,
  13235. lastKeyCode;
  13236. //输入法状态下不计算字符数
  13237. var inputType = false;
  13238. me.addListener('ready', function () {
  13239. domUtils.on(this.body, 'compositionstart', function () {
  13240. inputType = true;
  13241. });
  13242. domUtils.on(this.body, 'compositionend', function () {
  13243. inputType = false;
  13244. })
  13245. });
  13246. //快捷键
  13247. me.addshortcutkey({
  13248. "Undo":"ctrl+90", //undo
  13249. "Redo":"ctrl+89" //redo
  13250. });
  13251. var isCollapsed = true;
  13252. me.addListener('keydown', function (type, evt) {
  13253. var me = this;
  13254. var keyCode = evt.keyCode || evt.which;
  13255. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13256. if (inputType)
  13257. return;
  13258. if(!me.selection.getRange().collapsed){
  13259. me.undoManger.save(false,true);
  13260. isCollapsed = false;
  13261. return;
  13262. }
  13263. if (me.undoManger.list.length == 0) {
  13264. me.undoManger.save(true);
  13265. }
  13266. clearTimeout(saveSceneTimer);
  13267. function save(cont){
  13268. cont.undoManger.save(false,true);
  13269. cont.fireEvent('selectionchange');
  13270. }
  13271. saveSceneTimer = setTimeout(function(){
  13272. if(inputType){
  13273. var interalTimer = setInterval(function(){
  13274. if(!inputType){
  13275. save(me);
  13276. clearInterval(interalTimer)
  13277. }
  13278. },300)
  13279. return;
  13280. }
  13281. save(me);
  13282. },200);
  13283. lastKeyCode = keyCode;
  13284. keycont++;
  13285. if (keycont >= maxInputCount ) {
  13286. save(me)
  13287. }
  13288. }
  13289. });
  13290. me.addListener('keyup', function (type, evt) {
  13291. var keyCode = evt.keyCode || evt.which;
  13292. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13293. if (inputType)
  13294. return;
  13295. if(!isCollapsed){
  13296. this.undoManger.save(false,true);
  13297. isCollapsed = true;
  13298. }
  13299. }
  13300. });
  13301. //扩展实例,添加关闭和开启命令undo
  13302. me.stopCmdUndo = function(){
  13303. me.__hasEnterExecCommand = true;
  13304. };
  13305. me.startCmdUndo = function(){
  13306. me.__hasEnterExecCommand = false;
  13307. }
  13308. };
  13309. // plugins/copy.js
  13310. UE.plugin.register('copy', function () {
  13311. var me = this;
  13312. function initZeroClipboard() {
  13313. ZeroClipboard.config({
  13314. debug: false,
  13315. moviePath: me.options.UEDITOR_HOME_URL + '/third-party/zeroclipboard/ZeroClipboard.swf'
  13316. });
  13317. var client = me.zeroclipboard = new ZeroClipboard();
  13318. // 复制内容
  13319. client.on('copy', function (e) {
  13320. var client = e.client,
  13321. rng = me.selection.getRange(),
  13322. div = document.createElement('div');
  13323. div.appendChild(rng.cloneContents());
  13324. client.setText(div.innerText || div.textContent);
  13325. client.setHtml(div.innerHTML);
  13326. rng.select();
  13327. });
  13328. // hover事件传递到target
  13329. client.on('mouseover mouseout', function (e) {
  13330. var target = e.target;
  13331. if (e.type == 'mouseover') {
  13332. domUtils.addClass(target, 'edui-state-hover');
  13333. } else if (e.type == 'mouseout') {
  13334. domUtils.removeClasses(target, 'edui-state-hover');
  13335. }
  13336. });
  13337. // flash加载不成功
  13338. client.on('wrongflash noflash', function () {
  13339. ZeroClipboard.destroy();
  13340. });
  13341. }
  13342. return {
  13343. bindEvents: {
  13344. 'ready': function () {
  13345. if (!browser.ie) {
  13346. if (window.ZeroClipboard) {
  13347. initZeroClipboard();
  13348. } else {
  13349. utils.loadFile(document, {
  13350. src: me.options.UEDITOR_HOME_URL + "/third-party/zeroclipboard/ZeroClipboard.js",
  13351. tag: "script",
  13352. type: "text/javascript",
  13353. defer: "defer"
  13354. }, function () {
  13355. initZeroClipboard();
  13356. });
  13357. }
  13358. }
  13359. }
  13360. },
  13361. commands: {
  13362. 'copy': {
  13363. execCommand: function (cmd) {
  13364. if (!me.document.execCommand('copy')) {
  13365. alert(me.getLang('copymsg'));
  13366. }
  13367. }
  13368. }
  13369. }
  13370. }
  13371. });
  13372. // plugins/paste.js
  13373. ///import core
  13374. ///import plugins/inserthtml.js
  13375. ///import plugins/undo.js
  13376. ///import plugins/serialize.js
  13377. ///commands 粘贴
  13378. ///commandsName PastePlain
  13379. ///commandsTitle 纯文本粘贴模式
  13380. /**
  13381. * @description 粘贴
  13382. * @author zhanyi
  13383. */
  13384. UE.plugins['paste'] = function () {
  13385. function getClipboardData(callback) {
  13386. var doc = this.document;
  13387. if (doc.getElementById('baidu_pastebin')) {
  13388. return;
  13389. }
  13390. var range = this.selection.getRange(),
  13391. bk = range.createBookmark(),
  13392. //创建剪贴的容器div
  13393. pastebin = doc.createElement('div');
  13394. pastebin.id = 'baidu_pastebin';
  13395. // Safari 要求div必须有内容,才能粘贴内容进来
  13396. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13397. doc.body.appendChild(pastebin);
  13398. //trace:717 隐藏的span不能得到top
  13399. //bk.start.innerHTML = '&nbsp;';
  13400. bk.start.style.display = '';
  13401. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13402. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13403. domUtils.getXY(bk.start).y + 'px';
  13404. range.selectNodeContents(pastebin).select(true);
  13405. setTimeout(function () {
  13406. if (browser.webkit) {
  13407. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13408. if (domUtils.isEmptyNode(pi)) {
  13409. domUtils.remove(pi);
  13410. } else {
  13411. pastebin = pi;
  13412. break;
  13413. }
  13414. }
  13415. }
  13416. try {
  13417. pastebin.parentNode.removeChild(pastebin);
  13418. } catch (e) {
  13419. }
  13420. range.moveToBookmark(bk).select(true);
  13421. callback(pastebin);
  13422. }, 0);
  13423. }
  13424. var me = this;
  13425. me.setOpt({
  13426. retainOnlyLabelPasted : false
  13427. });
  13428. var txtContent, htmlContent, address;
  13429. function getPureHtml(html){
  13430. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13431. tagName = tagName.toLowerCase();
  13432. if ({img: 1}[tagName]) {
  13433. return a;
  13434. }
  13435. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13436. if ({
  13437. 'src': 1,
  13438. 'href': 1,
  13439. 'name': 1
  13440. }[atr.toLowerCase()]) {
  13441. return atr + '=' + val + ' '
  13442. }
  13443. return ''
  13444. });
  13445. if ({
  13446. 'span': 1,
  13447. 'div': 1
  13448. }[tagName]) {
  13449. return ''
  13450. } else {
  13451. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13452. }
  13453. });
  13454. }
  13455. function filter(div) {
  13456. var html;
  13457. if (div.firstChild) {
  13458. //去掉cut中添加的边界值
  13459. var nodes = domUtils.getElementsByTagName(div, 'span');
  13460. for (var i = 0, ni; ni = nodes[i++];) {
  13461. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13462. domUtils.remove(ni);
  13463. }
  13464. }
  13465. if (browser.webkit) {
  13466. var brs = div.querySelectorAll('div br');
  13467. for (var i = 0, bi; bi = brs[i++];) {
  13468. var pN = bi.parentNode;
  13469. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13470. pN.innerHTML = '<p><br/></p>';
  13471. domUtils.remove(pN);
  13472. }
  13473. }
  13474. var divs = div.querySelectorAll('#baidu_pastebin');
  13475. for (var i = 0, di; di = divs[i++];) {
  13476. var tmpP = me.document.createElement('p');
  13477. di.parentNode.insertBefore(tmpP, di);
  13478. while (di.firstChild) {
  13479. tmpP.appendChild(di.firstChild);
  13480. }
  13481. domUtils.remove(di);
  13482. }
  13483. var metas = div.querySelectorAll('meta');
  13484. for (var i = 0, ci; ci = metas[i++];) {
  13485. domUtils.remove(ci);
  13486. }
  13487. var brs = div.querySelectorAll('br');
  13488. for (i = 0; ci = brs[i++];) {
  13489. if (/^apple-/i.test(ci.className)) {
  13490. domUtils.remove(ci);
  13491. }
  13492. }
  13493. }
  13494. if (browser.gecko) {
  13495. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13496. for (i = 0; ci = dirtyNodes[i++];) {
  13497. ci.removeAttribute('_moz_dirty');
  13498. }
  13499. }
  13500. if (!browser.ie) {
  13501. var spans = div.querySelectorAll('span.Apple-style-span');
  13502. for (var i = 0, ci; ci = spans[i++];) {
  13503. domUtils.remove(ci, true);
  13504. }
  13505. }
  13506. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13507. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13508. //过滤word粘贴过来的冗余属性
  13509. html = UE.filterWord(html);
  13510. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13511. var root = UE.htmlparser(html);
  13512. //如果给了过滤规则就先进行过滤
  13513. if (me.options.filterRules) {
  13514. UE.filterNode(root, me.options.filterRules);
  13515. }
  13516. //执行默认的处理
  13517. me.filterInputRule(root);
  13518. //针对chrome的处理
  13519. if (browser.webkit) {
  13520. var br = root.lastChild();
  13521. if (br && br.type == 'element' && br.tagName == 'br') {
  13522. root.removeChild(br)
  13523. }
  13524. utils.each(me.body.querySelectorAll('div'), function (node) {
  13525. if (domUtils.isEmptyBlock(node)) {
  13526. domUtils.remove(node,true)
  13527. }
  13528. })
  13529. }
  13530. html = {'html': root.toHtml()};
  13531. me.fireEvent('beforepaste', html, root);
  13532. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13533. if(!html.html){
  13534. return;
  13535. }
  13536. root = UE.htmlparser(html.html,true);
  13537. //如果开启了纯文本模式
  13538. if (me.queryCommandState('pasteplain') === 1) {
  13539. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13540. } else {
  13541. //文本模式
  13542. UE.filterNode(root, me.options.filterTxtRules);
  13543. txtContent = root.toHtml();
  13544. //完全模式
  13545. htmlContent = html.html;
  13546. address = me.selection.getRange().createAddress(true);
  13547. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13548. }
  13549. me.fireEvent("afterpaste", html);
  13550. }
  13551. }
  13552. me.addListener('pasteTransfer', function (cmd, plainType) {
  13553. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13554. var range = me.selection.getRange();
  13555. range.moveToAddress(address, true);
  13556. if (!range.collapsed) {
  13557. while (!domUtils.isBody(range.startContainer)
  13558. ) {
  13559. var start = range.startContainer;
  13560. if(start.nodeType == 1){
  13561. start = start.childNodes[range.startOffset];
  13562. if(!start){
  13563. range.setStartBefore(range.startContainer);
  13564. continue;
  13565. }
  13566. var pre = start.previousSibling;
  13567. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13568. range.setStartBefore(pre)
  13569. }
  13570. }
  13571. if(range.startOffset == 0){
  13572. range.setStartBefore(range.startContainer);
  13573. }else{
  13574. break;
  13575. }
  13576. }
  13577. while (!domUtils.isBody(range.endContainer)
  13578. ) {
  13579. var end = range.endContainer;
  13580. if(end.nodeType == 1){
  13581. end = end.childNodes[range.endOffset];
  13582. if(!end){
  13583. range.setEndAfter(range.endContainer);
  13584. continue;
  13585. }
  13586. var next = end.nextSibling;
  13587. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13588. range.setEndAfter(next)
  13589. }
  13590. }
  13591. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13592. range.setEndAfter(range.endContainer);
  13593. }else{
  13594. break;
  13595. }
  13596. }
  13597. }
  13598. range.deleteContents();
  13599. range.select(true);
  13600. me.__hasEnterExecCommand = true;
  13601. var html = htmlContent;
  13602. if (plainType === 2 ) {
  13603. html = getPureHtml(html);
  13604. } else if (plainType) {
  13605. html = txtContent;
  13606. }
  13607. me.execCommand('inserthtml', html, true);
  13608. me.__hasEnterExecCommand = false;
  13609. var rng = me.selection.getRange();
  13610. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13611. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13612. ) {
  13613. rng.setStartBefore(rng.startContainer);
  13614. }
  13615. var tmpAddress = rng.createAddress(true);
  13616. address.endAddress = tmpAddress.startAddress;
  13617. }
  13618. });
  13619. me.addListener('ready', function () {
  13620. domUtils.on(me.body, 'cut', function () {
  13621. var range = me.selection.getRange();
  13622. if (!range.collapsed && me.undoManger) {
  13623. me.undoManger.save();
  13624. }
  13625. });
  13626. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13627. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13628. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13629. return;
  13630. }
  13631. getClipboardData.call(me, function (div) {
  13632. filter(div);
  13633. });
  13634. });
  13635. });
  13636. me.commands['paste'] = {
  13637. execCommand: function (cmd) {
  13638. if (browser.ie) {
  13639. getClipboardData.call(me, function (div) {
  13640. filter(div);
  13641. });
  13642. me.document.execCommand('paste');
  13643. } else {
  13644. alert(me.getLang('pastemsg'));
  13645. }
  13646. }
  13647. }
  13648. };
  13649. // plugins/puretxtpaste.js
  13650. /**
  13651. * 纯文本粘贴插件
  13652. * @file
  13653. * @since 1.2.6.1
  13654. */
  13655. UE.plugins['pasteplain'] = function(){
  13656. var me = this;
  13657. me.setOpt({
  13658. 'pasteplain':false,
  13659. 'filterTxtRules' : function(){
  13660. function transP(node){
  13661. node.tagName = 'p';
  13662. node.setStyle();
  13663. }
  13664. function removeNode(node){
  13665. node.parentNode.removeChild(node,true)
  13666. }
  13667. return {
  13668. //直接删除及其字节点内容
  13669. '-' : 'script style object iframe embed input select',
  13670. 'p': {$:{}},
  13671. 'br':{$:{}},
  13672. div: function (node) {
  13673. var tmpNode, p = UE.uNode.createElement('p');
  13674. while (tmpNode = node.firstChild()) {
  13675. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13676. p.appendChild(tmpNode);
  13677. } else {
  13678. if (p.firstChild()) {
  13679. node.parentNode.insertBefore(p, node);
  13680. p = UE.uNode.createElement('p');
  13681. } else {
  13682. node.parentNode.insertBefore(tmpNode, node);
  13683. }
  13684. }
  13685. }
  13686. if (p.firstChild()) {
  13687. node.parentNode.insertBefore(p, node);
  13688. }
  13689. node.parentNode.removeChild(node);
  13690. },
  13691. ol: removeNode,
  13692. ul: removeNode,
  13693. dl:removeNode,
  13694. dt:removeNode,
  13695. dd:removeNode,
  13696. 'li':removeNode,
  13697. 'caption':transP,
  13698. 'th':transP,
  13699. 'tr':transP,
  13700. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13701. 'td':function(node){
  13702. //没有内容的td直接删掉
  13703. var txt = !!node.innerText();
  13704. if(txt){
  13705. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13706. }
  13707. node.parentNode.removeChild(node,node.innerText())
  13708. }
  13709. }
  13710. }()
  13711. });
  13712. //暂时这里支持一下老版本的属性
  13713. var pasteplain = me.options.pasteplain;
  13714. /**
  13715. * 启用或取消纯文本粘贴模式
  13716. * @command pasteplain
  13717. * @method execCommand
  13718. * @param { String } cmd 命令字符串
  13719. * @example
  13720. * ```javascript
  13721. * editor.queryCommandState( 'pasteplain' );
  13722. * ```
  13723. */
  13724. /**
  13725. * 查询当前是否处于纯文本粘贴模式
  13726. * @command pasteplain
  13727. * @method queryCommandState
  13728. * @param { String } cmd 命令字符串
  13729. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13730. * @example
  13731. * ```javascript
  13732. * editor.queryCommandState( 'pasteplain' );
  13733. * ```
  13734. */
  13735. me.commands['pasteplain'] = {
  13736. queryCommandState: function (){
  13737. return pasteplain ? 1 : 0;
  13738. },
  13739. execCommand: function (){
  13740. pasteplain = !pasteplain|0;
  13741. },
  13742. notNeedUndo : 1
  13743. };
  13744. };
  13745. // plugins/list.js
  13746. /**
  13747. * 有序列表,无序列表插件
  13748. * @file
  13749. * @since 1.2.6.1
  13750. */
  13751. UE.plugins['list'] = function () {
  13752. var me = this,
  13753. notExchange = {
  13754. 'TD':1,
  13755. 'PRE':1,
  13756. 'BLOCKQUOTE':1
  13757. };
  13758. var customStyle = {
  13759. 'cn' : 'cn-1-',
  13760. 'cn1' : 'cn-2-',
  13761. 'cn2' : 'cn-3-',
  13762. 'num': 'num-1-',
  13763. 'num1' : 'num-2-',
  13764. 'num2' : 'num-3-',
  13765. 'dash' : 'dash',
  13766. 'dot':'dot'
  13767. };
  13768. me.setOpt( {
  13769. 'autoTransWordToList':false,
  13770. 'insertorderedlist':{
  13771. 'num':'',
  13772. 'num1':'',
  13773. 'num2':'',
  13774. 'cn':'',
  13775. 'cn1':'',
  13776. 'cn2':'',
  13777. 'decimal':'',
  13778. 'lower-alpha':'',
  13779. 'lower-roman':'',
  13780. 'upper-alpha':'',
  13781. 'upper-roman':''
  13782. },
  13783. 'insertunorderedlist':{
  13784. 'circle':'',
  13785. 'disc':'',
  13786. 'square':'',
  13787. 'dash' : '',
  13788. 'dot':''
  13789. },
  13790. listDefaultPaddingLeft : '30',
  13791. listiconpath : 'http://bs.baidu.com/listicon/',
  13792. maxListLevel : -1,//-1不限制
  13793. disablePInList:false
  13794. } );
  13795. function listToArray(list){
  13796. var arr = [];
  13797. for(var p in list){
  13798. arr.push(p)
  13799. }
  13800. return arr;
  13801. }
  13802. var listStyle = {
  13803. 'OL':listToArray(me.options.insertorderedlist),
  13804. 'UL':listToArray(me.options.insertunorderedlist)
  13805. };
  13806. var liiconpath = me.options.listiconpath;
  13807. //根据用户配置,调整customStyle
  13808. for(var s in customStyle){
  13809. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13810. delete customStyle[s];
  13811. }
  13812. }
  13813. me.ready(function () {
  13814. var customCss = [];
  13815. for(var p in customStyle){
  13816. if(p == 'dash' || p == 'dot'){
  13817. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13818. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13819. }else{
  13820. for(var i= 0;i<99;i++){
  13821. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13822. }
  13823. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13824. }
  13825. switch(p){
  13826. case 'cn':
  13827. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13828. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13829. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13830. break;
  13831. case 'cn1':
  13832. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13833. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13834. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13835. break;
  13836. case 'cn2':
  13837. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13838. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13839. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13840. break;
  13841. case 'num':
  13842. case 'num1':
  13843. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13844. break;
  13845. case 'num2':
  13846. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13847. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13848. break;
  13849. case 'dash':
  13850. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13851. break;
  13852. case 'dot':
  13853. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13854. }
  13855. }
  13856. customCss.push('.list-paddingleft-1{padding-left:0}');
  13857. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13858. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13859. //如果不给宽度会在自定应样式里出现滚动条
  13860. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13861. });
  13862. //单独处理剪切的问题
  13863. me.ready(function(){
  13864. domUtils.on(me.body,'cut',function(){
  13865. setTimeout(function(){
  13866. var rng = me.selection.getRange(),li;
  13867. //trace:3416
  13868. if(!rng.collapsed){
  13869. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13870. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13871. var pn = li.parentNode,node;
  13872. if(node = pn.previousSibling){
  13873. domUtils.remove(pn);
  13874. rng.setStartAtLast(node).collapse(true);
  13875. rng.select(true);
  13876. }else if(node = pn.nextSibling){
  13877. domUtils.remove(pn);
  13878. rng.setStartAtFirst(node).collapse(true);
  13879. rng.select(true);
  13880. }else{
  13881. var tmpNode = me.document.createElement('p');
  13882. domUtils.fillNode(me.document,tmpNode);
  13883. pn.parentNode.insertBefore(tmpNode,pn);
  13884. domUtils.remove(pn);
  13885. rng.setStart(tmpNode,0).collapse(true);
  13886. rng.select(true);
  13887. }
  13888. }
  13889. }
  13890. }
  13891. })
  13892. })
  13893. });
  13894. function getStyle(node){
  13895. var cls = node.className;
  13896. if(domUtils.hasClass(node,/custom_/)){
  13897. return cls.match(/custom_(\w+)/)[1]
  13898. }
  13899. return domUtils.getStyle(node, 'list-style-type')
  13900. }
  13901. me.addListener('beforepaste',function(type,html){
  13902. var me = this,
  13903. rng = me.selection.getRange(),li;
  13904. var root = UE.htmlparser(html.html,true);
  13905. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13906. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13907. utils.each(root.getNodesByTagName(tagName),function(n){
  13908. n.tagName = list.tagName;
  13909. n.setAttr();
  13910. if(n.parentNode === root){
  13911. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13912. }else{
  13913. var className = n.parentNode.getAttr('class');
  13914. if(className && /custom_/.test(className)){
  13915. type = className.match(/custom_(\w+)/)[1]
  13916. }else{
  13917. type = n.parentNode.getStyle('list-style-type');
  13918. }
  13919. if(!type){
  13920. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13921. }
  13922. }
  13923. var index = utils.indexOf(listStyle[list.tagName], type);
  13924. if(n.parentNode !== root)
  13925. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13926. var currentStyle = listStyle[list.tagName][index];
  13927. if(customStyle[currentStyle]){
  13928. n.setAttr('class', 'custom_' + currentStyle)
  13929. }else{
  13930. n.setStyle('list-style-type',currentStyle)
  13931. }
  13932. })
  13933. }
  13934. html.html = root.toHtml();
  13935. });
  13936. //导出时,去掉p标签
  13937. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13938. utils.each(root.getNodesByTagName('li'),function(li){
  13939. var newChildrens = [],index=0;
  13940. utils.each(li.children,function(n){
  13941. if(n.tagName == 'p'){
  13942. var tmpNode;
  13943. while(tmpNode = n.children.pop()) {
  13944. newChildrens.splice(index,0,tmpNode);
  13945. tmpNode.parentNode = li;
  13946. lastNode = tmpNode;
  13947. }
  13948. tmpNode = newChildrens[newChildrens.length-1];
  13949. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  13950. var br = UE.uNode.createElement('br');
  13951. br.parentNode = li;
  13952. newChildrens.push(br);
  13953. }
  13954. index = newChildrens.length;
  13955. }
  13956. });
  13957. if(newChildrens.length){
  13958. li.children = newChildrens;
  13959. }
  13960. });
  13961. });
  13962. //进入编辑器的li要套p标签
  13963. me.addInputRule(function(root){
  13964. utils.each(root.getNodesByTagName('li'),function(li){
  13965. var tmpP = UE.uNode.createElement('p');
  13966. for(var i= 0,ci;ci=li.children[i];){
  13967. if(ci.type == 'text' || dtd.p[ci.tagName]){
  13968. tmpP.appendChild(ci);
  13969. }else{
  13970. if(tmpP.firstChild()){
  13971. li.insertBefore(tmpP,ci);
  13972. tmpP = UE.uNode.createElement('p');
  13973. i = i + 2;
  13974. }else{
  13975. i++;
  13976. }
  13977. }
  13978. }
  13979. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  13980. li.appendChild(tmpP);
  13981. }
  13982. //trace:3357
  13983. //p不能为空
  13984. if (!tmpP.firstChild()) {
  13985. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  13986. }
  13987. //去掉末尾的空白
  13988. var p = li.firstChild();
  13989. var lastChild = p.lastChild();
  13990. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  13991. p.removeChild(lastChild)
  13992. }
  13993. });
  13994. if(me.options.autoTransWordToList){
  13995. var orderlisttype = {
  13996. 'num1':/^\d+\)/,
  13997. 'decimal':/^\d+\./,
  13998. 'lower-alpha':/^[a-z]+\)/,
  13999. 'upper-alpha':/^[A-Z]+\./,
  14000. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14001. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14002. },
  14003. unorderlisttype = {
  14004. 'square':'n'
  14005. };
  14006. function checkListType(content,container){
  14007. var span = container.firstChild();
  14008. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14009. for(var p in unorderlisttype){
  14010. if(unorderlisttype[p] == span.data){
  14011. return p
  14012. }
  14013. }
  14014. return 'disc'
  14015. }
  14016. for(var p in orderlisttype){
  14017. if(orderlisttype[p].test(content)){
  14018. return p;
  14019. }
  14020. }
  14021. }
  14022. utils.each(root.getNodesByTagName('p'),function(node){
  14023. if(node.getAttr('class') != 'MsoListParagraph'){
  14024. return
  14025. }
  14026. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14027. node.setStyle('margin','');
  14028. node.setStyle('margin-left','');
  14029. node.setAttr('class','');
  14030. function appendLi(list,p,type){
  14031. if(list.tagName == 'ol'){
  14032. if(browser.ie){
  14033. var first = p.firstChild();
  14034. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14035. p.removeChild(first);
  14036. }
  14037. }else{
  14038. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14039. }
  14040. }else{
  14041. p.removeChild(p.firstChild())
  14042. }
  14043. var li = UE.uNode.createElement('li');
  14044. li.appendChild(p);
  14045. list.appendChild(li);
  14046. }
  14047. var tmp = node,type,cacheNode = node;
  14048. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14049. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14050. if(customStyle[type]){
  14051. list.setAttr('class','custom_'+type)
  14052. }else{
  14053. list.setStyle('list-style-type',type)
  14054. }
  14055. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14056. tmp = node.nextSibling();
  14057. if(!tmp){
  14058. node.parentNode.insertBefore(list,node)
  14059. }
  14060. appendLi(list,node,type);
  14061. node = tmp;
  14062. }
  14063. if(!list.parentNode && node && node.parentNode){
  14064. node.parentNode.insertBefore(list,node)
  14065. }
  14066. }
  14067. var span = cacheNode.firstChild();
  14068. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14069. span.parentNode.removeChild(span)
  14070. }
  14071. })
  14072. }
  14073. });
  14074. //调整索引标签
  14075. me.addListener('contentchange',function(){
  14076. adjustListStyle(me.document)
  14077. });
  14078. function adjustListStyle(doc,ignore){
  14079. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14080. if(!domUtils.inDoc(node,doc))
  14081. return;
  14082. var parent = node.parentNode;
  14083. if(parent.tagName == node.tagName){
  14084. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14085. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14086. if(nodeStyleType == parentStyleType){
  14087. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14088. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14089. setListStyle(node,listStyle[node.tagName][styleIndex])
  14090. }
  14091. }
  14092. var index = 0,type = 2;
  14093. if( domUtils.hasClass(node,/custom_/)){
  14094. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14095. type = 1;
  14096. }
  14097. }else{
  14098. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14099. type = 3;
  14100. }
  14101. }
  14102. var style = domUtils.getStyle(node, 'list-style-type');
  14103. style && (node.style.cssText = 'list-style-type:' + style);
  14104. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14105. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14106. li.style.cssText && (li.style.cssText = '');
  14107. if(!li.firstChild){
  14108. domUtils.remove(li);
  14109. return;
  14110. }
  14111. if(li.parentNode !== node){
  14112. return;
  14113. }
  14114. index++;
  14115. if(domUtils.hasClass(node,/custom_/) ){
  14116. var paddingLeft = 1,currentStyle = getStyle(node);
  14117. if(node.tagName == 'OL'){
  14118. if(currentStyle){
  14119. switch(currentStyle){
  14120. case 'cn' :
  14121. case 'cn1':
  14122. case 'cn2':
  14123. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14124. paddingLeft = 2
  14125. }else if(index > 20){
  14126. paddingLeft = 3
  14127. }
  14128. break;
  14129. case 'num2' :
  14130. if(index > 9){
  14131. paddingLeft = 2
  14132. }
  14133. }
  14134. }
  14135. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14136. }else{
  14137. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14138. }
  14139. }else{
  14140. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14141. }
  14142. var className = li.getAttribute('class');
  14143. if(className !== null && !className.replace(/\s/g,'')){
  14144. domUtils.removeAttributes(li,'class')
  14145. }
  14146. });
  14147. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14148. })
  14149. }
  14150. function adjustList(list, tag, style,ignoreEmpty) {
  14151. var nextList = list.nextSibling;
  14152. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14153. domUtils.moveChild(nextList, list);
  14154. if (nextList.childNodes.length == 0) {
  14155. domUtils.remove(nextList);
  14156. }
  14157. }
  14158. if(nextList && domUtils.isFillChar(nextList)){
  14159. domUtils.remove(nextList);
  14160. }
  14161. var preList = list.previousSibling;
  14162. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14163. domUtils.moveChild(list, preList);
  14164. }
  14165. if(preList && domUtils.isFillChar(preList)){
  14166. domUtils.remove(preList);
  14167. }
  14168. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14169. if(getStyle(list)){
  14170. adjustListStyle(list.ownerDocument,true)
  14171. }
  14172. }
  14173. function setListStyle(list,style){
  14174. if(customStyle[style]){
  14175. list.className = 'custom_' + style;
  14176. }
  14177. try{
  14178. domUtils.setStyle(list, 'list-style-type', style);
  14179. }catch(e){}
  14180. }
  14181. function clearEmptySibling(node) {
  14182. var tmpNode = node.previousSibling;
  14183. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14184. domUtils.remove(tmpNode);
  14185. }
  14186. tmpNode = node.nextSibling;
  14187. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14188. domUtils.remove(tmpNode);
  14189. }
  14190. }
  14191. me.addListener('keydown', function (type, evt) {
  14192. function preventAndSave() {
  14193. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14194. me.fireEvent('contentchange');
  14195. me.undoManger && me.undoManger.save();
  14196. }
  14197. function findList(node,filterFn){
  14198. while(node && !domUtils.isBody(node)){
  14199. if(filterFn(node)){
  14200. return null
  14201. }
  14202. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14203. return node;
  14204. }
  14205. node = node.parentNode;
  14206. }
  14207. return null;
  14208. }
  14209. var keyCode = evt.keyCode || evt.which;
  14210. if (keyCode == 13 && !evt.shiftKey) {//回车
  14211. var rng = me.selection.getRange(),
  14212. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14213. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14214. if(parent && parent.tagName != 'PRE' && !li){
  14215. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14216. if(/^\s*1\s*\.[^\d]/.test(html)){
  14217. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14218. rng.setStartAtLast(parent).collapse(true).select();
  14219. me.__hasEnterExecCommand = true;
  14220. me.execCommand('insertorderedlist');
  14221. me.__hasEnterExecCommand = false;
  14222. }
  14223. }
  14224. var range = me.selection.getRange(),
  14225. start = findList(range.startContainer,function (node) {
  14226. return node.tagName == 'TABLE';
  14227. }),
  14228. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14229. return node.tagName == 'TABLE';
  14230. });
  14231. if (start && end && start === end) {
  14232. if (!range.collapsed) {
  14233. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14234. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14235. if (start && end && start === end) {
  14236. range.deleteContents();
  14237. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14238. if (li && domUtils.isEmptyBlock(li)) {
  14239. pre = li.previousSibling;
  14240. next = li.nextSibling;
  14241. p = me.document.createElement('p');
  14242. domUtils.fillNode(me.document, p);
  14243. parentList = li.parentNode;
  14244. if (pre && next) {
  14245. range.setStart(next, 0).collapse(true).select(true);
  14246. domUtils.remove(li);
  14247. } else {
  14248. if (!pre && !next || !pre) {
  14249. parentList.parentNode.insertBefore(p, parentList);
  14250. } else {
  14251. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14252. }
  14253. domUtils.remove(li);
  14254. if (!parentList.firstChild) {
  14255. domUtils.remove(parentList);
  14256. }
  14257. range.setStart(p, 0).setCursor();
  14258. }
  14259. preventAndSave();
  14260. return;
  14261. }
  14262. } else {
  14263. var tmpRange = range.cloneRange(),
  14264. bk = tmpRange.collapse(false).createBookmark();
  14265. range.deleteContents();
  14266. tmpRange.moveToBookmark(bk);
  14267. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14268. clearEmptySibling(li);
  14269. tmpRange.select();
  14270. preventAndSave();
  14271. return;
  14272. }
  14273. }
  14274. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14275. if (li) {
  14276. if (domUtils.isEmptyBlock(li)) {
  14277. bk = range.createBookmark();
  14278. var parentList = li.parentNode;
  14279. if (li !== parentList.lastChild) {
  14280. domUtils.breakParent(li, parentList);
  14281. clearEmptySibling(li);
  14282. } else {
  14283. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14284. if (domUtils.isEmptyNode(parentList)) {
  14285. domUtils.remove(parentList);
  14286. }
  14287. }
  14288. //嵌套不处理
  14289. if (!dtd.$list[li.parentNode.tagName]) {
  14290. if (!domUtils.isBlockElm(li.firstChild)) {
  14291. p = me.document.createElement('p');
  14292. li.parentNode.insertBefore(p, li);
  14293. while (li.firstChild) {
  14294. p.appendChild(li.firstChild);
  14295. }
  14296. domUtils.remove(li);
  14297. } else {
  14298. domUtils.remove(li, true);
  14299. }
  14300. }
  14301. range.moveToBookmark(bk).select();
  14302. } else {
  14303. var first = li.firstChild;
  14304. if (!first || !domUtils.isBlockElm(first)) {
  14305. var p = me.document.createElement('p');
  14306. !li.firstChild && domUtils.fillNode(me.document, p);
  14307. while (li.firstChild) {
  14308. p.appendChild(li.firstChild);
  14309. }
  14310. li.appendChild(p);
  14311. first = p;
  14312. }
  14313. var span = me.document.createElement('span');
  14314. range.insertNode(span);
  14315. domUtils.breakParent(span, li);
  14316. var nextLi = span.nextSibling;
  14317. first = nextLi.firstChild;
  14318. if (!first) {
  14319. p = me.document.createElement('p');
  14320. domUtils.fillNode(me.document, p);
  14321. nextLi.appendChild(p);
  14322. first = p;
  14323. }
  14324. if (domUtils.isEmptyNode(first)) {
  14325. first.innerHTML = '';
  14326. domUtils.fillNode(me.document, first);
  14327. }
  14328. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14329. domUtils.remove(span);
  14330. var pre = nextLi.previousSibling;
  14331. if (pre && domUtils.isEmptyBlock(pre)) {
  14332. pre.innerHTML = '<p></p>';
  14333. domUtils.fillNode(me.document, pre.firstChild);
  14334. }
  14335. }
  14336. // }
  14337. preventAndSave();
  14338. }
  14339. }
  14340. }
  14341. if (keyCode == 8) {
  14342. //修中ie中li下的问题
  14343. range = me.selection.getRange();
  14344. if (range.collapsed && domUtils.isStartInblock(range)) {
  14345. tmpRange = range.cloneRange().trimBoundary();
  14346. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14347. //要在li的最左边,才能处理
  14348. if (li && domUtils.isStartInblock(tmpRange)) {
  14349. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14350. if (start && start !== li.firstChild) {
  14351. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14352. domUtils.breakParent(start,parentList);
  14353. clearEmptySibling(start);
  14354. me.fireEvent('contentchange');
  14355. range.setStart(start,0).setCursor(false,true);
  14356. me.fireEvent('saveScene');
  14357. domUtils.preventDefault(evt);
  14358. return;
  14359. }
  14360. if (li && (pre = li.previousSibling)) {
  14361. if (keyCode == 46 && li.childNodes.length) {
  14362. return;
  14363. }
  14364. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14365. if (dtd.$list[pre.tagName]) {
  14366. pre = pre.lastChild;
  14367. }
  14368. me.undoManger && me.undoManger.save();
  14369. first = li.firstChild;
  14370. if (domUtils.isBlockElm(first)) {
  14371. if (domUtils.isEmptyNode(first)) {
  14372. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14373. pre.appendChild(first);
  14374. range.setStart(first, 0).setCursor(false, true);
  14375. //first不是唯一的节点
  14376. while (li.firstChild) {
  14377. pre.appendChild(li.firstChild);
  14378. }
  14379. } else {
  14380. span = me.document.createElement('span');
  14381. range.insertNode(span);
  14382. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14383. if (domUtils.isEmptyBlock(pre)) {
  14384. pre.innerHTML = '';
  14385. }
  14386. domUtils.moveChild(li, pre);
  14387. range.setStartBefore(span).collapse(true).select(true);
  14388. domUtils.remove(span);
  14389. }
  14390. } else {
  14391. if (domUtils.isEmptyNode(li)) {
  14392. var p = me.document.createElement('p');
  14393. pre.appendChild(p);
  14394. range.setStart(p, 0).setCursor();
  14395. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14396. } else {
  14397. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14398. while (li.firstChild) {
  14399. pre.appendChild(li.firstChild);
  14400. }
  14401. }
  14402. }
  14403. domUtils.remove(li);
  14404. me.fireEvent('contentchange');
  14405. me.fireEvent('saveScene');
  14406. domUtils.preventDefault(evt);
  14407. return;
  14408. }
  14409. //trace:980
  14410. if (li && !li.previousSibling) {
  14411. var parentList = li.parentNode;
  14412. var bk = range.createBookmark();
  14413. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14414. parentList.parentNode.insertBefore(li,parentList);
  14415. if(domUtils.isEmptyNode(parentList)){
  14416. domUtils.remove(parentList)
  14417. }
  14418. }else{
  14419. while(li.firstChild){
  14420. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14421. }
  14422. domUtils.remove(li);
  14423. if(domUtils.isEmptyNode(parentList)){
  14424. domUtils.remove(parentList)
  14425. }
  14426. }
  14427. range.moveToBookmark(bk).setCursor(false,true);
  14428. me.fireEvent('contentchange');
  14429. me.fireEvent('saveScene');
  14430. domUtils.preventDefault(evt);
  14431. return;
  14432. }
  14433. }
  14434. }
  14435. }
  14436. });
  14437. me.addListener('keyup',function(type, evt){
  14438. var keyCode = evt.keyCode || evt.which;
  14439. if (keyCode == 8) {
  14440. var rng = me.selection.getRange(),list;
  14441. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14442. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14443. }
  14444. }
  14445. });
  14446. //处理tab键
  14447. me.addListener('tabkeydown',function(){
  14448. var range = me.selection.getRange();
  14449. //控制级数
  14450. function checkLevel(li){
  14451. if(me.options.maxListLevel != -1){
  14452. var level = li.parentNode,levelNum = 0;
  14453. while(/[ou]l/i.test(level.tagName)){
  14454. levelNum++;
  14455. level = level.parentNode;
  14456. }
  14457. if(levelNum >= me.options.maxListLevel){
  14458. return true;
  14459. }
  14460. }
  14461. }
  14462. //只以开始为准
  14463. //todo 后续改进
  14464. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14465. if(li){
  14466. var bk;
  14467. if(range.collapsed){
  14468. if(checkLevel(li))
  14469. return true;
  14470. var parentLi = li.parentNode,
  14471. list = me.document.createElement(parentLi.tagName),
  14472. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14473. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14474. var currentStyle = listStyle[list.tagName][index];
  14475. setListStyle(list,currentStyle);
  14476. if(domUtils.isStartInblock(range)){
  14477. me.fireEvent('saveScene');
  14478. bk = range.createBookmark();
  14479. parentLi.insertBefore(list, li);
  14480. list.appendChild(li);
  14481. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14482. me.fireEvent('contentchange');
  14483. range.moveToBookmark(bk).select(true);
  14484. return true;
  14485. }
  14486. }else{
  14487. me.fireEvent('saveScene');
  14488. bk = range.createBookmark();
  14489. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14490. if(domUtils.isTagNode(ci,'ol ul')){
  14491. closeList = ci;
  14492. break;
  14493. }
  14494. }
  14495. var current = li;
  14496. if(bk.end){
  14497. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14498. if(checkLevel(current)){
  14499. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14500. continue;
  14501. }
  14502. var parentLi = current.parentNode,
  14503. list = me.document.createElement(parentLi.tagName),
  14504. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14505. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14506. var currentStyle = listStyle[list.tagName][currentIndex];
  14507. setListStyle(list,currentStyle);
  14508. parentLi.insertBefore(list, current);
  14509. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14510. li = current.nextSibling;
  14511. list.appendChild(current);
  14512. if(!li || domUtils.isTagNode(li,'ol ul')){
  14513. if(li){
  14514. while(li = li.firstChild){
  14515. if(li.tagName == 'LI'){
  14516. break;
  14517. }
  14518. }
  14519. }else{
  14520. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14521. }
  14522. break;
  14523. }
  14524. current = li;
  14525. }
  14526. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14527. current = li;
  14528. }
  14529. }
  14530. me.fireEvent('contentchange');
  14531. range.moveToBookmark(bk).select();
  14532. return true;
  14533. }
  14534. }
  14535. });
  14536. function getLi(start){
  14537. while(start && !domUtils.isBody(start)){
  14538. if(start.nodeName == 'TABLE'){
  14539. return null;
  14540. }
  14541. if(start.nodeName == 'LI'){
  14542. return start
  14543. }
  14544. start = start.parentNode;
  14545. }
  14546. }
  14547. /**
  14548. * 有序列表,与“insertunorderedlist”命令互斥
  14549. * @command insertorderedlist
  14550. * @method execCommand
  14551. * @param { String } command 命令字符串
  14552. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14553. * @example
  14554. * ```javascript
  14555. * editor.execCommand( 'insertorderedlist','decimal');
  14556. * ```
  14557. */
  14558. /**
  14559. * 查询当前选区内容是否有序列表
  14560. * @command insertorderedlist
  14561. * @method queryCommandState
  14562. * @param { String } cmd 命令字符串
  14563. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14564. * @example
  14565. * ```javascript
  14566. * editor.queryCommandState( 'insertorderedlist' );
  14567. * ```
  14568. */
  14569. /**
  14570. * 查询当前选区内容是否有序列表
  14571. * @command insertorderedlist
  14572. * @method queryCommandValue
  14573. * @param { String } cmd 命令字符串
  14574. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14575. * @example
  14576. * ```javascript
  14577. * editor.queryCommandValue( 'insertorderedlist' );
  14578. * ```
  14579. */
  14580. /**
  14581. * 无序列表,与“insertorderedlist”命令互斥
  14582. * @command insertunorderedlist
  14583. * @method execCommand
  14584. * @param { String } command 命令字符串
  14585. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14586. * @example
  14587. * ```javascript
  14588. * editor.execCommand( 'insertunorderedlist','circle');
  14589. * ```
  14590. */
  14591. /**
  14592. * 查询当前是否有word文档粘贴进来的图片
  14593. * @command insertunorderedlist
  14594. * @method insertunorderedlist
  14595. * @param { String } command 命令字符串
  14596. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14597. * @example
  14598. * ```javascript
  14599. * editor.queryCommandState( 'insertunorderedlist' );
  14600. * ```
  14601. */
  14602. /**
  14603. * 查询当前选区内容是否有序列表
  14604. * @command insertunorderedlist
  14605. * @method queryCommandValue
  14606. * @param { String } command 命令字符串
  14607. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14608. * @example
  14609. * ```javascript
  14610. * editor.queryCommandValue( 'insertunorderedlist' );
  14611. * ```
  14612. */
  14613. me.commands['insertorderedlist'] =
  14614. me.commands['insertunorderedlist'] = {
  14615. execCommand:function (command, style) {
  14616. if (!style) {
  14617. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14618. }
  14619. var me = this,
  14620. range = this.selection.getRange(),
  14621. filterFn = function (node) {
  14622. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14623. },
  14624. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14625. frag = me.document.createDocumentFragment();
  14626. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14627. //range.shrinkBoundary();//.adjustmentBoundary();
  14628. range.adjustmentBoundary().shrinkBoundary();
  14629. var bko = range.createBookmark(true),
  14630. start = getLi(me.document.getElementById(bko.start)),
  14631. modifyStart = 0,
  14632. end = getLi(me.document.getElementById(bko.end)),
  14633. modifyEnd = 0,
  14634. startParent, endParent,
  14635. list, tmp;
  14636. if (start || end) {
  14637. start && (startParent = start.parentNode);
  14638. if (!bko.end) {
  14639. end = start;
  14640. }
  14641. end && (endParent = end.parentNode);
  14642. if (startParent === endParent) {
  14643. while (start !== end) {
  14644. tmp = start;
  14645. start = start.nextSibling;
  14646. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14647. var p = me.document.createElement('p');
  14648. while (tmp.firstChild) {
  14649. p.appendChild(tmp.firstChild);
  14650. }
  14651. tmp.appendChild(p);
  14652. }
  14653. frag.appendChild(tmp);
  14654. }
  14655. tmp = me.document.createElement('span');
  14656. startParent.insertBefore(tmp, end);
  14657. if (!domUtils.isBlockElm(end.firstChild)) {
  14658. p = me.document.createElement('p');
  14659. while (end.firstChild) {
  14660. p.appendChild(end.firstChild);
  14661. }
  14662. end.appendChild(p);
  14663. }
  14664. frag.appendChild(end);
  14665. domUtils.breakParent(tmp, startParent);
  14666. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14667. domUtils.remove(tmp.previousSibling);
  14668. }
  14669. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14670. domUtils.remove(tmp.nextSibling)
  14671. }
  14672. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14673. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14674. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14675. if(domUtils.isTagNode(ci,'ol ul')){
  14676. // 删除时,子列表不处理
  14677. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14678. // while(li.firstChild){
  14679. // tmpFrag.appendChild(li.firstChild);
  14680. // }
  14681. //
  14682. // });
  14683. tmpFrag.appendChild(ci);
  14684. }else{
  14685. while (ci.firstChild) {
  14686. tmpFrag.appendChild(ci.firstChild);
  14687. domUtils.remove(ci);
  14688. }
  14689. }
  14690. }
  14691. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14692. } else {
  14693. list = me.document.createElement(tag);
  14694. setListStyle(list,style);
  14695. list.appendChild(frag);
  14696. tmp.parentNode.insertBefore(list, tmp);
  14697. }
  14698. domUtils.remove(tmp);
  14699. list && adjustList(list, tag, style);
  14700. range.moveToBookmark(bko).select();
  14701. return;
  14702. }
  14703. //开始
  14704. if (start) {
  14705. while (start) {
  14706. tmp = start.nextSibling;
  14707. if (domUtils.isTagNode(start, 'ol ul')) {
  14708. frag.appendChild(start);
  14709. } else {
  14710. var tmpfrag = me.document.createDocumentFragment(),
  14711. hasBlock = 0;
  14712. while (start.firstChild) {
  14713. if (domUtils.isBlockElm(start.firstChild)) {
  14714. hasBlock = 1;
  14715. }
  14716. tmpfrag.appendChild(start.firstChild);
  14717. }
  14718. if (!hasBlock) {
  14719. var tmpP = me.document.createElement('p');
  14720. tmpP.appendChild(tmpfrag);
  14721. frag.appendChild(tmpP);
  14722. } else {
  14723. frag.appendChild(tmpfrag);
  14724. }
  14725. domUtils.remove(start);
  14726. }
  14727. start = tmp;
  14728. }
  14729. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14730. if (domUtils.isEmptyNode(startParent)) {
  14731. range.setStartBefore(startParent);
  14732. domUtils.remove(startParent);
  14733. } else {
  14734. range.setStartAfter(startParent);
  14735. }
  14736. modifyStart = 1;
  14737. }
  14738. if (end && domUtils.inDoc(endParent, me.document)) {
  14739. //结束
  14740. start = endParent.firstChild;
  14741. while (start && start !== end) {
  14742. tmp = start.nextSibling;
  14743. if (domUtils.isTagNode(start, 'ol ul')) {
  14744. frag.appendChild(start);
  14745. } else {
  14746. tmpfrag = me.document.createDocumentFragment();
  14747. hasBlock = 0;
  14748. while (start.firstChild) {
  14749. if (domUtils.isBlockElm(start.firstChild)) {
  14750. hasBlock = 1;
  14751. }
  14752. tmpfrag.appendChild(start.firstChild);
  14753. }
  14754. if (!hasBlock) {
  14755. tmpP = me.document.createElement('p');
  14756. tmpP.appendChild(tmpfrag);
  14757. frag.appendChild(tmpP);
  14758. } else {
  14759. frag.appendChild(tmpfrag);
  14760. }
  14761. domUtils.remove(start);
  14762. }
  14763. start = tmp;
  14764. }
  14765. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14766. 'tmpDiv':1
  14767. });
  14768. domUtils.moveChild(end, tmpDiv);
  14769. frag.appendChild(tmpDiv);
  14770. domUtils.remove(end);
  14771. endParent.parentNode.insertBefore(frag, endParent);
  14772. range.setEndBefore(endParent);
  14773. if (domUtils.isEmptyNode(endParent)) {
  14774. domUtils.remove(endParent);
  14775. }
  14776. modifyEnd = 1;
  14777. }
  14778. }
  14779. if (!modifyStart) {
  14780. range.setStartBefore(me.document.getElementById(bko.start));
  14781. }
  14782. if (bko.end && !modifyEnd) {
  14783. range.setEndAfter(me.document.getElementById(bko.end));
  14784. }
  14785. range.enlarge(true, function (node) {
  14786. return notExchange[node.tagName];
  14787. });
  14788. frag = me.document.createDocumentFragment();
  14789. var bk = range.createBookmark(),
  14790. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14791. tmpRange = range.cloneRange(),
  14792. tmpNode,
  14793. block = domUtils.isBlockElm;
  14794. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14795. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14796. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14797. while (current.firstChild) {
  14798. frag.appendChild(current.firstChild);
  14799. }
  14800. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14801. domUtils.remove(current);
  14802. current = tmpNode;
  14803. continue;
  14804. }
  14805. tmpNode = current;
  14806. tmpRange.setStartBefore(current);
  14807. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14808. tmpNode = current;
  14809. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14810. return !notExchange[node.tagName];
  14811. });
  14812. }
  14813. if (current && block(current)) {
  14814. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14815. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14816. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14817. tmpNode = tmp;
  14818. }
  14819. }
  14820. tmpRange.setEndAfter(tmpNode);
  14821. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14822. var li = range.document.createElement('li');
  14823. li.appendChild(tmpRange.extractContents());
  14824. if(domUtils.isEmptyNode(li)){
  14825. var tmpNode = range.document.createElement('p');
  14826. while(li.firstChild){
  14827. tmpNode.appendChild(li.firstChild)
  14828. }
  14829. li.appendChild(tmpNode);
  14830. }
  14831. frag.appendChild(li);
  14832. } else {
  14833. current = domUtils.getNextDomNode(current, true, filterFn);
  14834. }
  14835. }
  14836. range.moveToBookmark(bk).collapse(true);
  14837. list = me.document.createElement(tag);
  14838. setListStyle(list,style);
  14839. list.appendChild(frag);
  14840. range.insertNode(list);
  14841. //当前list上下看能否合并
  14842. adjustList(list, tag, style);
  14843. //去掉冗余的tmpDiv
  14844. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14845. if (ci.getAttribute('tmpDiv')) {
  14846. domUtils.remove(ci, true)
  14847. }
  14848. }
  14849. range.moveToBookmark(bko).select();
  14850. },
  14851. queryCommandState:function (command) {
  14852. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14853. var path = this.selection.getStartElementPath();
  14854. for(var i= 0,ci;ci = path[i++];){
  14855. if(ci.nodeName == 'TABLE'){
  14856. return 0
  14857. }
  14858. if(tag == ci.nodeName.toLowerCase()){
  14859. return 1
  14860. };
  14861. }
  14862. return 0;
  14863. },
  14864. queryCommandValue:function (command) {
  14865. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14866. var path = this.selection.getStartElementPath(),
  14867. node;
  14868. for(var i= 0,ci;ci = path[i++];){
  14869. if(ci.nodeName == 'TABLE'){
  14870. node = null;
  14871. break;
  14872. }
  14873. if(tag == ci.nodeName.toLowerCase()){
  14874. node = ci;
  14875. break;
  14876. };
  14877. }
  14878. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14879. }
  14880. };
  14881. };
  14882. // plugins/source.js
  14883. /**
  14884. * 源码编辑插件
  14885. * @file
  14886. * @since 1.2.6.1
  14887. */
  14888. (function (){
  14889. var sourceEditors = {
  14890. textarea: function (editor, holder){
  14891. var textarea = holder.ownerDocument.createElement('textarea');
  14892. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14893. // todo: IE下只有onresize属性可用... 很纠结
  14894. if (browser.ie && browser.version < 8) {
  14895. textarea.style.width = holder.offsetWidth + 'px';
  14896. textarea.style.height = holder.offsetHeight + 'px';
  14897. holder.onresize = function (){
  14898. textarea.style.width = holder.offsetWidth + 'px';
  14899. textarea.style.height = holder.offsetHeight + 'px';
  14900. };
  14901. }
  14902. holder.appendChild(textarea);
  14903. return {
  14904. setContent: function (content){
  14905. textarea.value = content;
  14906. },
  14907. getContent: function (){
  14908. return textarea.value;
  14909. },
  14910. select: function (){
  14911. var range;
  14912. if (browser.ie) {
  14913. range = textarea.createTextRange();
  14914. range.collapse(true);
  14915. range.select();
  14916. } else {
  14917. //todo: chrome下无法设置焦点
  14918. textarea.setSelectionRange(0, 0);
  14919. textarea.focus();
  14920. }
  14921. },
  14922. dispose: function (){
  14923. holder.removeChild(textarea);
  14924. // todo
  14925. holder.onresize = null;
  14926. textarea = null;
  14927. holder = null;
  14928. }
  14929. };
  14930. },
  14931. codemirror: function (editor, holder){
  14932. var codeEditor = window.CodeMirror(holder, {
  14933. mode: "text/html",
  14934. tabMode: "indent",
  14935. lineNumbers: true,
  14936. lineWrapping:true
  14937. });
  14938. var dom = codeEditor.getWrapperElement();
  14939. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14940. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14941. codeEditor.refresh();
  14942. return {
  14943. getCodeMirror:function(){
  14944. return codeEditor;
  14945. },
  14946. setContent: function (content){
  14947. codeEditor.setValue(content);
  14948. },
  14949. getContent: function (){
  14950. return codeEditor.getValue();
  14951. },
  14952. select: function (){
  14953. codeEditor.focus();
  14954. },
  14955. dispose: function (){
  14956. holder.removeChild(dom);
  14957. dom = null;
  14958. codeEditor = null;
  14959. }
  14960. };
  14961. }
  14962. };
  14963. UE.plugins['source'] = function (){
  14964. var me = this;
  14965. var opt = this.options;
  14966. var sourceMode = false;
  14967. var sourceEditor;
  14968. var orgSetContent;
  14969. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  14970. me.setOpt({
  14971. sourceEditorFirst:false
  14972. });
  14973. function createSourceEditor(holder){
  14974. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  14975. }
  14976. var bakCssText;
  14977. //解决在源码模式下getContent不能得到最新的内容问题
  14978. var oldGetContent,
  14979. bakAddress;
  14980. /**
  14981. * 切换源码模式和编辑模式
  14982. * @command source
  14983. * @method execCommand
  14984. * @param { String } cmd 命令字符串
  14985. * @example
  14986. * ```javascript
  14987. * editor.execCommand( 'source');
  14988. * ```
  14989. */
  14990. /**
  14991. * 查询当前编辑区域的状态是源码模式还是可视化模式
  14992. * @command source
  14993. * @method queryCommandState
  14994. * @param { String } cmd 命令字符串
  14995. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  14996. * @example
  14997. * ```javascript
  14998. * editor.queryCommandState( 'source' );
  14999. * ```
  15000. */
  15001. me.commands['source'] = {
  15002. execCommand: function (){
  15003. sourceMode = !sourceMode;
  15004. if (sourceMode) {
  15005. bakAddress = me.selection.getRange().createAddress(false,true);
  15006. me.undoManger && me.undoManger.save(true);
  15007. if(browser.gecko){
  15008. me.body.contentEditable = false;
  15009. }
  15010. bakCssText = me.iframe.style.cssText;
  15011. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15012. me.fireEvent('beforegetcontent');
  15013. var root = UE.htmlparser(me.body.innerHTML);
  15014. me.filterOutputRule(root);
  15015. root.traversal(function (node) {
  15016. if (node.type == 'element') {
  15017. switch (node.tagName) {
  15018. case 'td':
  15019. case 'th':
  15020. case 'caption':
  15021. if(node.children && node.children.length == 1){
  15022. if(node.firstChild().tagName == 'br' ){
  15023. node.removeChild(node.firstChild())
  15024. }
  15025. };
  15026. break;
  15027. case 'pre':
  15028. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15029. }
  15030. }
  15031. });
  15032. me.fireEvent('aftergetcontent');
  15033. var content = root.toHtml(true);
  15034. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15035. sourceEditor.setContent(content);
  15036. orgSetContent = me.setContent;
  15037. me.setContent = function(html){
  15038. //这里暂时不触发事件,防止报错
  15039. var root = UE.htmlparser(html);
  15040. me.filterInputRule(root);
  15041. html = root.toHtml();
  15042. sourceEditor.setContent(html);
  15043. };
  15044. setTimeout(function (){
  15045. sourceEditor.select();
  15046. me.addListener('fullscreenchanged', function(){
  15047. try{
  15048. sourceEditor.getCodeMirror().refresh()
  15049. }catch(e){}
  15050. });
  15051. });
  15052. //重置getContent,源码模式下取值也能是最新的数据
  15053. oldGetContent = me.getContent;
  15054. me.getContent = function (){
  15055. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15056. };
  15057. } else {
  15058. me.iframe.style.cssText = bakCssText;
  15059. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15060. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15061. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15062. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15063. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15064. }
  15065. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15066. });
  15067. me.setContent = orgSetContent;
  15068. me.setContent(cont);
  15069. sourceEditor.dispose();
  15070. sourceEditor = null;
  15071. //还原getContent方法
  15072. me.getContent = oldGetContent;
  15073. var first = me.body.firstChild;
  15074. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15075. if(!first){
  15076. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15077. first = me.body.firstChild;
  15078. }
  15079. //要在ifm为显示时ff才能取到selection,否则报错
  15080. //这里不能比较位置了
  15081. me.undoManger && me.undoManger.save(true);
  15082. if(browser.gecko){
  15083. var input = document.createElement('input');
  15084. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15085. document.body.appendChild(input);
  15086. me.body.contentEditable = false;
  15087. setTimeout(function(){
  15088. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15089. input.focus();
  15090. setTimeout(function(){
  15091. me.body.contentEditable = true;
  15092. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15093. domUtils.remove(input);
  15094. });
  15095. });
  15096. }else{
  15097. //ie下有可能报错,比如在代码顶头的情况
  15098. try{
  15099. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15100. }catch(e){}
  15101. }
  15102. }
  15103. this.fireEvent('sourcemodechanged', sourceMode);
  15104. },
  15105. queryCommandState: function (){
  15106. return sourceMode|0;
  15107. },
  15108. notNeedUndo : 1
  15109. };
  15110. var oldQueryCommandState = me.queryCommandState;
  15111. me.queryCommandState = function (cmdName){
  15112. cmdName = cmdName.toLowerCase();
  15113. if (sourceMode) {
  15114. //源码模式下可以开启的命令
  15115. return cmdName in {
  15116. 'source' : 1,
  15117. 'fullscreen' : 1
  15118. } ? 1 : -1
  15119. }
  15120. return oldQueryCommandState.apply(this, arguments);
  15121. };
  15122. if(opt.sourceEditor == "codemirror"){
  15123. me.addListener("ready",function(){
  15124. utils.loadFile(document,{
  15125. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15126. tag : "script",
  15127. type : "text/javascript",
  15128. defer : "defer"
  15129. },function(){
  15130. if(opt.sourceEditorFirst){
  15131. setTimeout(function(){
  15132. me.execCommand("source");
  15133. },0);
  15134. }
  15135. });
  15136. utils.loadFile(document,{
  15137. tag : "link",
  15138. rel : "stylesheet",
  15139. type : "text/css",
  15140. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15141. });
  15142. });
  15143. }
  15144. };
  15145. })();
  15146. // plugins/enterkey.js
  15147. ///import core
  15148. ///import plugins/undo.js
  15149. ///commands 设置回车标签p或br
  15150. ///commandsName EnterKey
  15151. ///commandsTitle 设置回车标签p或br
  15152. /**
  15153. * @description 处理回车
  15154. * @author zhanyi
  15155. */
  15156. UE.plugins['enterkey'] = function() {
  15157. var hTag,
  15158. me = this,
  15159. tag = me.options.enterTag;
  15160. me.addListener('keyup', function(type, evt) {
  15161. var keyCode = evt.keyCode || evt.which;
  15162. if (keyCode == 13) {
  15163. var range = me.selection.getRange(),
  15164. start = range.startContainer,
  15165. doSave;
  15166. //修正在h1-h6里边回车后不能嵌套p的问题
  15167. if (!browser.ie) {
  15168. if (/h\d/i.test(hTag)) {
  15169. if (browser.gecko) {
  15170. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15171. if (!h) {
  15172. me.document.execCommand('formatBlock', false, '<p>');
  15173. doSave = 1;
  15174. }
  15175. } else {
  15176. //chrome remove div
  15177. if (start.nodeType == 1) {
  15178. var tmp = me.document.createTextNode(''),div;
  15179. range.insertNode(tmp);
  15180. div = domUtils.findParentByTagName(tmp, 'div', true);
  15181. if (div) {
  15182. var p = me.document.createElement('p');
  15183. while (div.firstChild) {
  15184. p.appendChild(div.firstChild);
  15185. }
  15186. div.parentNode.insertBefore(p, div);
  15187. domUtils.remove(div);
  15188. range.setStartBefore(tmp).setCursor();
  15189. doSave = 1;
  15190. }
  15191. domUtils.remove(tmp);
  15192. }
  15193. }
  15194. if (me.undoManger && doSave) {
  15195. me.undoManger.save();
  15196. }
  15197. }
  15198. //没有站位符,会出现多行的问题
  15199. browser.opera && range.select();
  15200. }else{
  15201. me.fireEvent('saveScene',true,true)
  15202. }
  15203. }
  15204. });
  15205. me.addListener('keydown', function(type, evt) {
  15206. var keyCode = evt.keyCode || evt.which;
  15207. if (keyCode == 13) {//回车
  15208. if(me.fireEvent('beforeenterkeydown')){
  15209. domUtils.preventDefault(evt);
  15210. return;
  15211. }
  15212. me.fireEvent('saveScene',true,true);
  15213. hTag = '';
  15214. var range = me.selection.getRange();
  15215. if (!range.collapsed) {
  15216. //跨td不能删
  15217. var start = range.startContainer,
  15218. end = range.endContainer,
  15219. startTd = domUtils.findParentByTagName(start, 'td', true),
  15220. endTd = domUtils.findParentByTagName(end, 'td', true);
  15221. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15222. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15223. return;
  15224. }
  15225. }
  15226. if (tag == 'p') {
  15227. if (!browser.ie) {
  15228. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15229. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15230. //trace:2431
  15231. if (!start && !browser.opera) {
  15232. me.document.execCommand('formatBlock', false, '<p>');
  15233. if (browser.gecko) {
  15234. range = me.selection.getRange();
  15235. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15236. start && domUtils.removeDirtyAttr(start);
  15237. }
  15238. } else {
  15239. hTag = start.tagName;
  15240. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15241. }
  15242. }
  15243. } else {
  15244. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15245. if (!range.collapsed) {
  15246. range.deleteContents();
  15247. start = range.startContainer;
  15248. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15249. while (start.nodeType == 1) {
  15250. if (dtd.$empty[start.tagName]) {
  15251. range.setStartBefore(start).setCursor();
  15252. if (me.undoManger) {
  15253. me.undoManger.save();
  15254. }
  15255. return false;
  15256. }
  15257. if (!start.firstChild) {
  15258. var br = range.document.createElement('br');
  15259. start.appendChild(br);
  15260. range.setStart(start, 0).setCursor();
  15261. if (me.undoManger) {
  15262. me.undoManger.save();
  15263. }
  15264. return false;
  15265. }
  15266. start = start.firstChild;
  15267. }
  15268. if (start === range.startContainer.childNodes[range.startOffset]) {
  15269. br = range.document.createElement('br');
  15270. range.insertNode(br).setCursor();
  15271. } else {
  15272. range.setStart(start, 0).setCursor();
  15273. }
  15274. } else {
  15275. br = range.document.createElement('br');
  15276. range.insertNode(br).setStartAfter(br).setCursor();
  15277. }
  15278. } else {
  15279. br = range.document.createElement('br');
  15280. range.insertNode(br);
  15281. var parent = br.parentNode;
  15282. if (parent.lastChild === br) {
  15283. br.parentNode.insertBefore(br.cloneNode(true), br);
  15284. range.setStartBefore(br);
  15285. } else {
  15286. range.setStartAfter(br);
  15287. }
  15288. range.setCursor();
  15289. }
  15290. }
  15291. }
  15292. });
  15293. };
  15294. // plugins/keystrokes.js
  15295. /* 处理特殊键的兼容性问题 */
  15296. UE.plugins['keystrokes'] = function() {
  15297. var me = this;
  15298. var collapsed = true;
  15299. me.addListener('keydown', function(type, evt) {
  15300. var keyCode = evt.keyCode || evt.which,
  15301. rng = me.selection.getRange();
  15302. //处理全选的情况
  15303. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15304. || keyCode >= 48 && keyCode <= 57 ||
  15305. keyCode >= 96 && keyCode <= 111 || {
  15306. 13:1,
  15307. 8:1,
  15308. 46:1
  15309. }[keyCode])
  15310. ){
  15311. var tmpNode = rng.startContainer;
  15312. if(domUtils.isFillChar(tmpNode)){
  15313. rng.setStartBefore(tmpNode)
  15314. }
  15315. tmpNode = rng.endContainer;
  15316. if(domUtils.isFillChar(tmpNode)){
  15317. rng.setEndAfter(tmpNode)
  15318. }
  15319. rng.txtToElmBoundary();
  15320. //结束边界可能放到了br的前边,要把br包含进来
  15321. // x[xxx]<br/>
  15322. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15323. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15324. if(tmpNode && domUtils.isBr(tmpNode)){
  15325. rng.setEndAfter(tmpNode);
  15326. }
  15327. }
  15328. if(rng.startOffset == 0){
  15329. tmpNode = rng.startContainer;
  15330. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15331. tmpNode = rng.endContainer;
  15332. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15333. me.fireEvent('saveScene');
  15334. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15335. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15336. me._selectionChange();
  15337. return;
  15338. }
  15339. }
  15340. }
  15341. }
  15342. //处理backspace
  15343. if (keyCode == keymap.Backspace) {
  15344. rng = me.selection.getRange();
  15345. collapsed = rng.collapsed;
  15346. if(me.fireEvent('delkeydown',evt)){
  15347. return;
  15348. }
  15349. var start,end;
  15350. //避免按两次删除才能生效的问题
  15351. if(rng.collapsed && rng.inFillChar()){
  15352. start = rng.startContainer;
  15353. if(domUtils.isFillChar(start)){
  15354. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15355. domUtils.remove(start)
  15356. }else{
  15357. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15358. rng.startOffset--;
  15359. rng.collapse(true).select(true)
  15360. }
  15361. }
  15362. //解决选中control元素不能删除的问题
  15363. if (start = rng.getClosedNode()) {
  15364. me.fireEvent('saveScene');
  15365. rng.setStartBefore(start);
  15366. domUtils.remove(start);
  15367. rng.setCursor();
  15368. me.fireEvent('saveScene');
  15369. domUtils.preventDefault(evt);
  15370. return;
  15371. }
  15372. //阻止在table上的删除
  15373. if (!browser.ie) {
  15374. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15375. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15376. if (start && !end || !start && end || start !== end) {
  15377. evt.preventDefault();
  15378. return;
  15379. }
  15380. }
  15381. }
  15382. //处理tab键的逻辑
  15383. if (keyCode == keymap.Tab) {
  15384. //不处理以下标签
  15385. var excludeTagNameForTabKey = {
  15386. 'ol' : 1,
  15387. 'ul' : 1,
  15388. 'table':1
  15389. };
  15390. //处理组件里的tab按下事件
  15391. if(me.fireEvent('tabkeydown',evt)){
  15392. domUtils.preventDefault(evt);
  15393. return;
  15394. }
  15395. var range = me.selection.getRange();
  15396. me.fireEvent('saveScene');
  15397. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15398. txt += tabNode;
  15399. }
  15400. var span = me.document.createElement('span');
  15401. span.innerHTML = txt + domUtils.fillChar;
  15402. if (range.collapsed) {
  15403. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15404. } else {
  15405. var filterFn = function(node) {
  15406. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15407. };
  15408. //普通的情况
  15409. start = domUtils.findParent(range.startContainer, filterFn,true);
  15410. end = domUtils.findParent(range.endContainer, filterFn,true);
  15411. if (start && end && start === end) {
  15412. range.deleteContents();
  15413. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15414. } else {
  15415. var bookmark = range.createBookmark();
  15416. range.enlarge(true);
  15417. var bookmark2 = range.createBookmark(),
  15418. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15419. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15420. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15421. current = domUtils.getNextDomNode(current, false, filterFn);
  15422. }
  15423. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15424. }
  15425. }
  15426. domUtils.preventDefault(evt)
  15427. }
  15428. //trace:1634
  15429. //ff的del键在容器空的时候,也会删除
  15430. if(browser.gecko && keyCode == 46){
  15431. range = me.selection.getRange();
  15432. if(range.collapsed){
  15433. start = range.startContainer;
  15434. if(domUtils.isEmptyBlock(start)){
  15435. var parent = start.parentNode;
  15436. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15437. start = parent;
  15438. parent = parent.parentNode;
  15439. }
  15440. if(start === parent.lastChild)
  15441. evt.preventDefault();
  15442. return;
  15443. }
  15444. }
  15445. }
  15446. });
  15447. me.addListener('keyup', function(type, evt) {
  15448. var keyCode = evt.keyCode || evt.which,
  15449. rng,me = this;
  15450. if(keyCode == keymap.Backspace){
  15451. if(me.fireEvent('delkeyup')){
  15452. return;
  15453. }
  15454. rng = me.selection.getRange();
  15455. if(rng.collapsed){
  15456. var tmpNode,
  15457. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15458. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15459. if(domUtils.isEmptyBlock(tmpNode)){
  15460. var pre = tmpNode.previousSibling;
  15461. if(pre && pre.nodeName != 'TABLE'){
  15462. domUtils.remove(tmpNode);
  15463. rng.setStartAtLast(pre).setCursor(false,true);
  15464. return;
  15465. }else{
  15466. var next = tmpNode.nextSibling;
  15467. if(next && next.nodeName != 'TABLE'){
  15468. domUtils.remove(tmpNode);
  15469. rng.setStartAtFirst(next).setCursor(false,true);
  15470. return;
  15471. }
  15472. }
  15473. }
  15474. }
  15475. //处理当删除到body时,要重新给p标签展位
  15476. if(domUtils.isBody(rng.startContainer)){
  15477. var tmpNode = domUtils.createElement(me.document,'p',{
  15478. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15479. });
  15480. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15481. }
  15482. }
  15483. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15484. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15485. if(browser.ie){
  15486. var span = rng.document.createElement('span');
  15487. rng.insertNode(span).setStartBefore(span).collapse(true);
  15488. rng.select();
  15489. domUtils.remove(span)
  15490. }else{
  15491. rng.select()
  15492. }
  15493. }
  15494. }
  15495. })
  15496. };
  15497. // plugins/fiximgclick.js
  15498. ///import core
  15499. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15500. ///commandsName FixImgClick
  15501. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15502. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15503. UE.plugins['fiximgclick'] = (function () {
  15504. var elementUpdated = false;
  15505. function Scale() {
  15506. this.editor = null;
  15507. this.resizer = null;
  15508. this.cover = null;
  15509. this.doc = document;
  15510. this.prePos = {x: 0, y: 0};
  15511. this.startPos = {x: 0, y: 0};
  15512. }
  15513. (function () {
  15514. var rect = [
  15515. //[left, top, width, height]
  15516. [0, 0, -1, -1],
  15517. [0, 0, 0, -1],
  15518. [0, 0, 1, -1],
  15519. [0, 0, -1, 0],
  15520. [0, 0, 1, 0],
  15521. [0, 0, -1, 1],
  15522. [0, 0, 0, 1],
  15523. [0, 0, 1, 1]
  15524. ];
  15525. Scale.prototype = {
  15526. init: function (editor) {
  15527. var me = this;
  15528. me.editor = editor;
  15529. me.startPos = this.prePos = {x: 0, y: 0};
  15530. me.dragId = -1;
  15531. var hands = [],
  15532. cover = me.cover = document.createElement('div'),
  15533. resizer = me.resizer = document.createElement('div');
  15534. cover.id = me.editor.ui.id + '_imagescale_cover';
  15535. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15536. domUtils.on(cover, 'mousedown click', function () {
  15537. me.hide();
  15538. });
  15539. for (i = 0; i < 8; i++) {
  15540. hands.push('<span class="edui-editor-scale-hand' + i + '"></span>');
  15541. }
  15542. resizer.id = me.editor.ui.id + '_imagescale';
  15543. resizer.className = 'edui-editor-scale';
  15544. resizer.innerHTML = hands.join('');
  15545. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15546. me.editor.ui.getDom().appendChild(cover);
  15547. me.editor.ui.getDom().appendChild(resizer);
  15548. me.initStyle();
  15549. me.initEvents();
  15550. },
  15551. initStyle: function () {
  15552. utils.cssRule('imagescale', '.edui-editor-scale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15553. '.edui-editor-scale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15554. + '.edui-editor-scale .edui-editor-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15555. + '.edui-editor-scale .edui-editor-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15556. + '.edui-editor-scale .edui-editor-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15557. + '.edui-editor-scale .edui-editor-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15558. + '.edui-editor-scale .edui-editor-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15559. + '.edui-editor-scale .edui-editor-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15560. + '.edui-editor-scale .edui-editor-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15561. + '.edui-editor-scale .edui-editor-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15562. },
  15563. initEvents: function () {
  15564. var me = this;
  15565. me.startPos.x = me.startPos.y = 0;
  15566. me.isDraging = false;
  15567. },
  15568. _eventHandler: function (e) {
  15569. var me = this;
  15570. switch (e.type) {
  15571. case 'mousedown':
  15572. var hand = e.target || e.srcElement, hand;
  15573. if (hand.className.indexOf('edui-editor-scale-hand') != -1 && me.dragId == -1) {
  15574. me.dragId = hand.className.slice(-1);
  15575. me.startPos.x = me.prePos.x = e.clientX;
  15576. me.startPos.y = me.prePos.y = e.clientY;
  15577. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15578. }
  15579. break;
  15580. case 'mousemove':
  15581. if (me.dragId != -1) {
  15582. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15583. me.prePos.x = e.clientX;
  15584. me.prePos.y = e.clientY;
  15585. elementUpdated = true;
  15586. me.updateTargetElement();
  15587. }
  15588. break;
  15589. case 'mouseup':
  15590. if (me.dragId != -1) {
  15591. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15592. me.updateTargetElement();
  15593. if (me.target.parentNode) me.attachTo(me.target);
  15594. me.dragId = -1;
  15595. }
  15596. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15597. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15598. if(elementUpdated){
  15599. elementUpdated = false;
  15600. me.editor.fireEvent('contentchange');
  15601. }
  15602. break;
  15603. default:
  15604. break;
  15605. }
  15606. },
  15607. updateTargetElement: function () {
  15608. var me = this;
  15609. domUtils.setStyles(me.target, {
  15610. 'width': me.resizer.style.width,
  15611. 'height': me.resizer.style.height
  15612. });
  15613. me.target.width = parseInt(me.resizer.style.width);
  15614. me.target.height = parseInt(me.resizer.style.height);
  15615. me.attachTo(me.target);
  15616. },
  15617. updateContainerStyle: function (dir, offset) {
  15618. var me = this,
  15619. dom = me.resizer, tmp;
  15620. if (rect[dir][0] != 0) {
  15621. tmp = parseInt(dom.style.left) + offset.x;
  15622. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15623. }
  15624. if (rect[dir][1] != 0) {
  15625. tmp = parseInt(dom.style.top) + offset.y;
  15626. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15627. }
  15628. if (rect[dir][2] != 0) {
  15629. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15630. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15631. }
  15632. if (rect[dir][3] != 0) {
  15633. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15634. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15635. }
  15636. },
  15637. _validScaledProp: function (prop, value) {
  15638. var ele = this.resizer,
  15639. wrap = document;
  15640. value = isNaN(value) ? 0 : value;
  15641. switch (prop) {
  15642. case 'left':
  15643. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15644. case 'top':
  15645. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15646. case 'width':
  15647. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15648. case 'height':
  15649. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15650. }
  15651. },
  15652. hideCover: function () {
  15653. this.cover.style.display = 'none';
  15654. },
  15655. showCover: function () {
  15656. var me = this,
  15657. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15658. iframePos = domUtils.getXY(me.editor.iframe);
  15659. domUtils.setStyles(me.cover, {
  15660. 'width': me.editor.iframe.offsetWidth + 'px',
  15661. 'height': me.editor.iframe.offsetHeight + 'px',
  15662. 'top': iframePos.y - editorPos.y + 'px',
  15663. 'left': iframePos.x - editorPos.x + 'px',
  15664. 'position': 'absolute',
  15665. 'display': ''
  15666. })
  15667. },
  15668. show: function (targetObj) {
  15669. var me = this;
  15670. me.resizer.style.display = 'block';
  15671. if(targetObj) me.attachTo(targetObj);
  15672. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15673. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15674. me.showCover();
  15675. me.editor.fireEvent('afterscaleshow', me);
  15676. me.editor.fireEvent('saveScene');
  15677. },
  15678. hide: function () {
  15679. var me = this;
  15680. me.hideCover();
  15681. me.resizer.style.display = 'none';
  15682. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15683. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15684. me.editor.fireEvent('afterscalehide', me);
  15685. },
  15686. proxy: function( fn, context ) {
  15687. return function(e) {
  15688. return fn.apply( context || this, arguments);
  15689. };
  15690. },
  15691. attachTo: function (targetObj) {
  15692. var me = this,
  15693. target = me.target = targetObj,
  15694. resizer = this.resizer,
  15695. imgPos = domUtils.getXY(target),
  15696. iframePos = domUtils.getXY(me.editor.iframe),
  15697. editorPos = domUtils.getXY(resizer.parentNode);
  15698. domUtils.setStyles(resizer, {
  15699. 'width': target.width + 'px',
  15700. 'height': target.height + 'px',
  15701. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15702. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15703. });
  15704. }
  15705. }
  15706. })();
  15707. return function () {
  15708. var me = this,
  15709. imageScale;
  15710. me.setOpt('imageScaleEnabled', true);
  15711. if ( !browser.ie && me.options.imageScaleEnabled) {
  15712. me.addListener('click', function (type, e) {
  15713. var range = me.selection.getRange(),
  15714. img = range.getClosedNode();
  15715. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15716. if (img.className.indexOf("edui-faked-music") != -1 ||
  15717. img.getAttribute("anchorname") ||
  15718. domUtils.hasClass(img, 'loadingclass') ||
  15719. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15720. if (!imageScale) {
  15721. imageScale = new Scale();
  15722. imageScale.init(me);
  15723. me.ui.getDom().appendChild(imageScale.resizer);
  15724. var _keyDownHandler = function (e) {
  15725. imageScale.hide();
  15726. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15727. }, _mouseDownHandler = function (e) {
  15728. var ele = e.target || e.srcElement;
  15729. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-scale') == -1)) {
  15730. _keyDownHandler(e);
  15731. }
  15732. }, timer;
  15733. me.addListener('afterscaleshow', function (e) {
  15734. me.addListener('beforekeydown', _keyDownHandler);
  15735. me.addListener('beforemousedown', _mouseDownHandler);
  15736. domUtils.on(document, 'keydown', _keyDownHandler);
  15737. domUtils.on(document,'mousedown', _mouseDownHandler);
  15738. me.selection.getNative().removeAllRanges();
  15739. });
  15740. me.addListener('afterscalehide', function (e) {
  15741. me.removeListener('beforekeydown', _keyDownHandler);
  15742. me.removeListener('beforemousedown', _mouseDownHandler);
  15743. domUtils.un(document, 'keydown', _keyDownHandler);
  15744. domUtils.un(document,'mousedown', _mouseDownHandler);
  15745. var target = imageScale.target;
  15746. if (target.parentNode) {
  15747. me.selection.getRange().selectNode(target).select();
  15748. }
  15749. });
  15750. //TODO 有iframe的情况,mousedown不能往下传。。
  15751. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15752. me.selection.getNative().removeAllRanges();
  15753. var ele = e.target || e.srcElement;
  15754. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  15755. timer = setTimeout(function () {
  15756. imageScale.hide();
  15757. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15758. }, 200);
  15759. }
  15760. });
  15761. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15762. var ele = e.target || e.srcElement;
  15763. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  15764. clearTimeout(timer);
  15765. }
  15766. });
  15767. }
  15768. imageScale.show(img);
  15769. } else {
  15770. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15771. }
  15772. });
  15773. }
  15774. if (browser.webkit) {
  15775. me.addListener('click', function (type, e) {
  15776. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15777. var range = new dom.Range(me.document);
  15778. range.selectNode(e.target).select();
  15779. }
  15780. });
  15781. }
  15782. }
  15783. })();
  15784. // plugins/autolink.js
  15785. ///import core
  15786. ///commands 为非ie浏览器自动添加a标签
  15787. ///commandsName AutoLink
  15788. ///commandsTitle 自动增加链接
  15789. /**
  15790. * @description 为非ie浏览器自动添加a标签
  15791. * @author zhanyi
  15792. */
  15793. UE.plugin.register('autolink',function(){
  15794. var cont = 0;
  15795. return !browser.ie ? {
  15796. bindEvents:{
  15797. 'reset' : function(){
  15798. cont = 0;
  15799. },
  15800. 'keydown':function(type, evt) {
  15801. var me = this;
  15802. var keyCode = evt.keyCode || evt.which;
  15803. if (keyCode == 32 || keyCode == 13) {
  15804. var sel = me.selection.getNative(),
  15805. range = sel.getRangeAt(0).cloneRange(),
  15806. offset,
  15807. charCode;
  15808. var start = range.startContainer;
  15809. while (start.nodeType == 1 && range.startOffset > 0) {
  15810. start = range.startContainer.childNodes[range.startOffset - 1];
  15811. if (!start){
  15812. break;
  15813. }
  15814. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15815. range.collapse(true);
  15816. start = range.startContainer;
  15817. }
  15818. do{
  15819. if (range.startOffset == 0) {
  15820. start = range.startContainer.previousSibling;
  15821. while (start && start.nodeType == 1) {
  15822. start = start.lastChild;
  15823. }
  15824. if (!start || domUtils.isFillChar(start)){
  15825. break;
  15826. }
  15827. offset = start.nodeValue.length;
  15828. } else {
  15829. start = range.startContainer;
  15830. offset = range.startOffset;
  15831. }
  15832. range.setStart(start, offset - 1);
  15833. charCode = range.toString().charCodeAt(0);
  15834. } while (charCode != 160 && charCode != 32);
  15835. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15836. while(range.toString().length){
  15837. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15838. break;
  15839. }
  15840. try{
  15841. range.setStart(range.startContainer,range.startOffset+1);
  15842. }catch(e){
  15843. //trace:2121
  15844. var start = range.startContainer;
  15845. while(!(next = start.nextSibling)){
  15846. if(domUtils.isBody(start)){
  15847. return;
  15848. }
  15849. start = start.parentNode;
  15850. }
  15851. range.setStart(next,0);
  15852. }
  15853. }
  15854. //range的开始边界已经在a标签里的不再处理
  15855. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15856. return;
  15857. }
  15858. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15859. me.undoManger && me.undoManger.save();
  15860. a.appendChild(range.extractContents());
  15861. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15862. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15863. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15864. a.setAttribute('_src',utils.html(href));
  15865. a.href = utils.html(href);
  15866. range.insertNode(a);
  15867. a.parentNode.insertBefore(text, a.nextSibling);
  15868. range.setStart(text, 0);
  15869. range.collapse(true);
  15870. sel.removeAllRanges();
  15871. sel.addRange(range);
  15872. me.undoManger && me.undoManger.save();
  15873. }
  15874. }
  15875. }
  15876. }
  15877. }:{}
  15878. },function(){
  15879. var keyCodes = {
  15880. 37:1, 38:1, 39:1, 40:1,
  15881. 13:1,32:1
  15882. };
  15883. function checkIsCludeLink(node){
  15884. if(node.nodeType == 3){
  15885. return null
  15886. }
  15887. if(node.nodeName == 'A'){
  15888. return node;
  15889. }
  15890. var lastChild = node.lastChild;
  15891. while(lastChild){
  15892. if(lastChild.nodeName == 'A'){
  15893. return lastChild;
  15894. }
  15895. if(lastChild.nodeType == 3){
  15896. if(domUtils.isWhitespace(lastChild)){
  15897. lastChild = lastChild.previousSibling;
  15898. continue;
  15899. }
  15900. return null
  15901. }
  15902. lastChild = lastChild.lastChild;
  15903. }
  15904. }
  15905. browser.ie && this.addListener('keyup',function(cmd,evt){
  15906. var me = this,keyCode = evt.keyCode;
  15907. if(keyCodes[keyCode]){
  15908. var rng = me.selection.getRange();
  15909. var start = rng.startContainer;
  15910. if(keyCode == 13){
  15911. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15912. start = start.parentNode;
  15913. }
  15914. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15915. var pre = start.previousSibling;
  15916. if(pre && pre.nodeType == 1){
  15917. var pre = checkIsCludeLink(pre);
  15918. if(pre && !pre.getAttribute('_href')){
  15919. domUtils.remove(pre,true);
  15920. }
  15921. }
  15922. }
  15923. }else if(keyCode == 32 ){
  15924. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15925. start = start.previousSibling;
  15926. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15927. domUtils.remove(start,true);
  15928. }
  15929. }
  15930. }else {
  15931. start = domUtils.findParentByTagName(start,'a',true);
  15932. if(start && !start.getAttribute('_href')){
  15933. var bk = rng.createBookmark();
  15934. domUtils.remove(start,true);
  15935. rng.moveToBookmark(bk).select(true)
  15936. }
  15937. }
  15938. }
  15939. });
  15940. }
  15941. );
  15942. // plugins/autoheight.js
  15943. ///import core
  15944. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  15945. ///commandsName AutoHeight,autoHeightEnabled
  15946. ///commandsTitle 自动增高
  15947. /**
  15948. * @description 自动伸展
  15949. * @author zhanyi
  15950. */
  15951. UE.plugins['autoheight'] = function () {
  15952. var me = this;
  15953. //提供开关,就算加载也可以关闭
  15954. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  15955. if (!me.autoHeightEnabled) {
  15956. return;
  15957. }
  15958. var bakOverflow,
  15959. lastHeight = 0,
  15960. options = me.options,
  15961. currentHeight,
  15962. timer;
  15963. function adjustHeight() {
  15964. var me = this;
  15965. clearTimeout(timer);
  15966. if(isFullscreen)return;
  15967. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  15968. timer = setTimeout(function(){
  15969. var node = me.body.lastChild;
  15970. while(node && node.nodeType != 1){
  15971. node = node.previousSibling;
  15972. }
  15973. if(node && node.nodeType == 1){
  15974. node.style.clear = 'both';
  15975. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  15976. if (currentHeight != lastHeight) {
  15977. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  15978. me.iframe.parentNode.style.height = currentHeight + 'px';
  15979. }
  15980. me.body.style.height = currentHeight + 'px';
  15981. lastHeight = currentHeight;
  15982. }
  15983. domUtils.removeStyle(node,'clear');
  15984. }
  15985. },50)
  15986. }
  15987. }
  15988. var isFullscreen;
  15989. me.addListener('fullscreenchanged',function(cmd,f){
  15990. isFullscreen = f
  15991. });
  15992. me.addListener('destroy', function () {
  15993. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  15994. });
  15995. me.enableAutoHeight = function () {
  15996. var me = this;
  15997. if (!me.autoHeightEnabled) {
  15998. return;
  15999. }
  16000. var doc = me.document;
  16001. me.autoHeightEnabled = true;
  16002. bakOverflow = doc.body.style.overflowY;
  16003. doc.body.style.overflowY = 'hidden';
  16004. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16005. //ff不给事件算得不对
  16006. setTimeout(function () {
  16007. adjustHeight.call(me);
  16008. }, browser.gecko ? 100 : 0);
  16009. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16010. };
  16011. me.disableAutoHeight = function () {
  16012. me.body.style.overflowY = bakOverflow || '';
  16013. me.removeListener('contentchange', adjustHeight);
  16014. me.removeListener('keyup', adjustHeight);
  16015. me.removeListener('mouseup', adjustHeight);
  16016. me.autoHeightEnabled = false;
  16017. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16018. };
  16019. me.on('setHeight',function(){
  16020. me.disableAutoHeight()
  16021. });
  16022. me.addListener('ready', function () {
  16023. me.enableAutoHeight();
  16024. //trace:1764
  16025. var timer;
  16026. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16027. clearTimeout(timer);
  16028. timer = setTimeout(function () {
  16029. //trace:3681
  16030. adjustHeight.call(me);
  16031. }, 100);
  16032. });
  16033. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16034. var lastScrollY;
  16035. window.onscroll = function(){
  16036. if(lastScrollY === null){
  16037. lastScrollY = this.scrollY
  16038. }else if(this.scrollY == 0 && lastScrollY != 0){
  16039. me.window.scrollTo(0,0);
  16040. lastScrollY = null;
  16041. }
  16042. }
  16043. });
  16044. };
  16045. // plugins/autofloat.js
  16046. ///import core
  16047. ///commands 悬浮工具栏
  16048. ///commandsName AutoFloat,autoFloatEnabled
  16049. ///commandsTitle 悬浮工具栏
  16050. /**
  16051. * modified by chengchao01
  16052. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16053. */
  16054. UE.plugins['autofloat'] = function() {
  16055. var me = this,
  16056. lang = me.getLang();
  16057. me.setOpt({
  16058. topOffset:0
  16059. });
  16060. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16061. topOffset = me.options.topOffset;
  16062. //如果不固定toolbar的位置,则直接退出
  16063. if(!optsAutoFloatEnabled){
  16064. return;
  16065. }
  16066. var uiUtils = UE.ui.uiUtils,
  16067. LteIE6 = browser.ie && browser.version <= 6,
  16068. quirks = browser.quirks;
  16069. function checkHasUI(){
  16070. if(!UE.ui){
  16071. alert(lang.autofloatMsg);
  16072. return 0;
  16073. }
  16074. return 1;
  16075. }
  16076. function fixIE6FixedPos(){
  16077. var docStyle = document.body.style;
  16078. docStyle.backgroundImage = 'url("about:blank")';
  16079. docStyle.backgroundAttachment = 'fixed';
  16080. }
  16081. var bakCssText,
  16082. placeHolder = document.createElement('div'),
  16083. toolbarBox,orgTop,
  16084. getPosition,
  16085. flag =true; //ie7模式下需要偏移
  16086. function setFloating(){
  16087. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16088. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16089. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16090. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16091. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16092. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16093. if (LteIE6 || (quirks && browser.ie)) {
  16094. if(toolbarBox.style.position != 'absolute'){
  16095. toolbarBox.style.position = 'absolute';
  16096. }
  16097. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16098. } else {
  16099. if (browser.ie7Compat && flag) {
  16100. flag = false;
  16101. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16102. }
  16103. if(toolbarBox.style.position != 'fixed'){
  16104. toolbarBox.style.position = 'fixed';
  16105. toolbarBox.style.top = topOffset +"px";
  16106. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16107. }
  16108. }
  16109. }
  16110. function unsetFloating(){
  16111. flag = true;
  16112. if(placeHolder.parentNode){
  16113. placeHolder.parentNode.removeChild(placeHolder);
  16114. }
  16115. toolbarBox.style.cssText = bakCssText;
  16116. }
  16117. function updateFloating(){
  16118. var rect3 = getPosition(me.container);
  16119. var offset=me.options.toolbarTopOffset||0;
  16120. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16121. setFloating();
  16122. }else{
  16123. unsetFloating();
  16124. }
  16125. }
  16126. var defer_updateFloating = utils.defer(function(){
  16127. updateFloating();
  16128. },browser.ie ? 200 : 100,true);
  16129. me.addListener('destroy',function(){
  16130. domUtils.un(window, ['scroll','resize'], updateFloating);
  16131. me.removeListener('keydown', defer_updateFloating);
  16132. });
  16133. me.addListener('ready', function(){
  16134. if(checkHasUI(me)){
  16135. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16136. if(!me.ui){
  16137. return;
  16138. }
  16139. getPosition = uiUtils.getClientRect;
  16140. toolbarBox = me.ui.getDom('toolbarbox');
  16141. orgTop = getPosition(toolbarBox).top;
  16142. bakCssText = toolbarBox.style.cssText;
  16143. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16144. if(LteIE6){
  16145. fixIE6FixedPos();
  16146. }
  16147. domUtils.on(window, ['scroll','resize'], updateFloating);
  16148. me.addListener('keydown', defer_updateFloating);
  16149. me.addListener('beforefullscreenchange', function (t, enabled){
  16150. if (enabled) {
  16151. unsetFloating();
  16152. }
  16153. });
  16154. me.addListener('fullscreenchanged', function (t, enabled){
  16155. if (!enabled) {
  16156. updateFloating();
  16157. }
  16158. });
  16159. me.addListener('sourcemodechanged', function (t, enabled){
  16160. setTimeout(function (){
  16161. updateFloating();
  16162. },0);
  16163. });
  16164. me.addListener("clearDoc",function(){
  16165. setTimeout(function(){
  16166. updateFloating();
  16167. },0);
  16168. })
  16169. }
  16170. });
  16171. };
  16172. // plugins/video.js
  16173. /**
  16174. * video插件, 为UEditor提供视频插入支持
  16175. * @file
  16176. * @since 1.2.6.1
  16177. */
  16178. UE.plugins['video'] = function (){
  16179. var me =this;
  16180. /**
  16181. * 创建插入视频字符窜
  16182. * @param url 视频地址
  16183. * @param width 视频宽度
  16184. * @param height 视频高度
  16185. * @param align 视频对齐
  16186. * @param toEmbed 是否以flash代替显示
  16187. * @param addParagraph 是否需要添加P 标签
  16188. */
  16189. function creatInsertStr(url,width,height,id,align,classname,type){
  16190. var str;
  16191. switch (type){
  16192. case 'image':
  16193. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16194. ' 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 + ';': '')+'" />'
  16195. break;
  16196. case 'embed':
  16197. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16198. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16199. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16200. break;
  16201. case 'video':
  16202. var ext = url.substr(url.lastIndexOf('.') + 1);
  16203. if(ext == 'ogv') ext = 'ogg';
  16204. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16205. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16206. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16207. break;
  16208. }
  16209. return str;
  16210. }
  16211. function switchImgAndVideo(root,img2video){
  16212. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16213. var className = node.getAttr('class');
  16214. if(className && className.indexOf('edui-faked-video') != -1){
  16215. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16216. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16217. }
  16218. if(className && className.indexOf('edui-upload-video') != -1){
  16219. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16220. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16221. }
  16222. })
  16223. }
  16224. me.addOutputRule(function(root){
  16225. switchImgAndVideo(root,true)
  16226. });
  16227. me.addInputRule(function(root){
  16228. switchImgAndVideo(root)
  16229. });
  16230. /**
  16231. * 插入视频
  16232. * @command insertvideo
  16233. * @method execCommand
  16234. * @param { String } cmd 命令字符串
  16235. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16236. * @example
  16237. * ```javascript
  16238. *
  16239. * var videoAttr = {
  16240. * //视频地址
  16241. * url: 'http://www.youku.com/xxx',
  16242. * //视频宽高值, 单位px
  16243. * width: 200,
  16244. * height: 100
  16245. * };
  16246. *
  16247. * //editor 是编辑器实例
  16248. * //向编辑器插入单个视频
  16249. * editor.execCommand( 'insertvideo', videoAttr );
  16250. * ```
  16251. */
  16252. /**
  16253. * 插入视频
  16254. * @command insertvideo
  16255. * @method execCommand
  16256. * @param { String } cmd 命令字符串
  16257. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16258. * @example
  16259. * ```javascript
  16260. *
  16261. * var videoAttr1 = {
  16262. * //视频地址
  16263. * url: 'http://www.youku.com/xxx',
  16264. * //视频宽高值, 单位px
  16265. * width: 200,
  16266. * height: 100
  16267. * },
  16268. * videoAttr2 = {
  16269. * //视频地址
  16270. * url: 'http://www.youku.com/xxx',
  16271. * //视频宽高值, 单位px
  16272. * width: 200,
  16273. * height: 100
  16274. * }
  16275. *
  16276. * //editor 是编辑器实例
  16277. * //该方法将会向编辑器内插入两个视频
  16278. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16279. * ```
  16280. */
  16281. /**
  16282. * 查询当前光标所在处是否是一个视频
  16283. * @command insertvideo
  16284. * @method queryCommandState
  16285. * @param { String } cmd 需要查询的命令字符串
  16286. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16287. * @example
  16288. * ```javascript
  16289. *
  16290. * //editor 是编辑器实例
  16291. * editor.queryCommandState( 'insertvideo' );
  16292. * ```
  16293. */
  16294. me.commands["insertvideo"] = {
  16295. execCommand: function (cmd, videoObjs, type){
  16296. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16297. var html = [],id = 'tmpVedio', cl;
  16298. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16299. vi = videoObjs[i];
  16300. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16301. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16302. }
  16303. me.execCommand("inserthtml",html.join(""),true);
  16304. var rng = this.selection.getRange();
  16305. for(var i= 0,len=videoObjs.length;i<len;i++){
  16306. var img = this.document.getElementById('tmpVedio'+i);
  16307. domUtils.removeAttributes(img,'id');
  16308. rng.selectNode(img).select();
  16309. me.execCommand('imagefloat',videoObjs[i].align)
  16310. }
  16311. },
  16312. queryCommandState : function(){
  16313. var img = me.selection.getRange().getClosedNode(),
  16314. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16315. return flag ? 1 : 0;
  16316. }
  16317. };
  16318. };
  16319. // plugins/table.core.js
  16320. /**
  16321. * Created with JetBrains WebStorm.
  16322. * User: taoqili
  16323. * Date: 13-1-18
  16324. * Time: 上午11:09
  16325. * To change this template use File | Settings | File Templates.
  16326. */
  16327. /**
  16328. * UE表格操作类
  16329. * @param table
  16330. * @constructor
  16331. */
  16332. (function () {
  16333. var UETable = UE.UETable = function (table) {
  16334. this.table = table;
  16335. this.indexTable = [];
  16336. this.selectedTds = [];
  16337. this.cellsRange = {};
  16338. this.update(table);
  16339. };
  16340. //===以下为静态工具方法===
  16341. UETable.removeSelectedClass = function (cells) {
  16342. utils.each(cells, function (cell) {
  16343. domUtils.removeClasses(cell, "selectTdClass");
  16344. })
  16345. };
  16346. UETable.addSelectedClass = function (cells) {
  16347. utils.each(cells, function (cell) {
  16348. domUtils.addClass(cell, "selectTdClass");
  16349. })
  16350. };
  16351. UETable.isEmptyBlock = function (node) {
  16352. var reg = new RegExp(domUtils.fillChar, 'g');
  16353. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16354. return 0;
  16355. }
  16356. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16357. if (node.getElementsByTagName(i).length) {
  16358. return 0;
  16359. }
  16360. }
  16361. return 1;
  16362. };
  16363. UETable.getWidth = function (cell) {
  16364. if (!cell)return 0;
  16365. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16366. };
  16367. /**
  16368. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16369. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16370. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16371. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16372. */
  16373. UETable.getTableCellAlignState = function ( cells ) {
  16374. !utils.isArray( cells ) && ( cells = [cells] );
  16375. var result = {},
  16376. status = ['align', 'valign'],
  16377. tempStatus = null,
  16378. isSame = true;//状态是否相同
  16379. utils.each( cells, function( cellNode ){
  16380. utils.each( status, function( currentState ){
  16381. tempStatus = cellNode.getAttribute( currentState );
  16382. if( !result[ currentState ] && tempStatus ) {
  16383. result[ currentState ] = tempStatus;
  16384. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16385. isSame = false;
  16386. return false;
  16387. }
  16388. } );
  16389. return isSame;
  16390. });
  16391. return isSame ? result : null;
  16392. };
  16393. /**
  16394. * 根据当前选区获取相关的table信息
  16395. * @return {Object}
  16396. */
  16397. UETable.getTableItemsByRange = function (editor) {
  16398. var start = editor.selection.getStart();
  16399. //ff下会选中bookmark
  16400. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16401. start = start.nextSibling;
  16402. }
  16403. //在table或者td边缘有可能存在选中tr的情况
  16404. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16405. tr = cell && cell.parentNode,
  16406. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16407. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16408. return {
  16409. cell:cell,
  16410. tr:tr,
  16411. table:table,
  16412. caption:caption
  16413. }
  16414. };
  16415. UETable.getUETableBySelected = function (editor) {
  16416. var table = UETable.getTableItemsByRange(editor).table;
  16417. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16418. return table.ueTable;
  16419. }
  16420. return null;
  16421. };
  16422. UETable.getDefaultValue = function (editor, table) {
  16423. var borderMap = {
  16424. thin:'0px',
  16425. medium:'1px',
  16426. thick:'2px'
  16427. },
  16428. tableBorder, tdPadding, tdBorder, tmpValue;
  16429. if (!table) {
  16430. table = editor.document.createElement('table');
  16431. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16432. editor.body.appendChild(table);
  16433. var td = table.getElementsByTagName('td')[0];
  16434. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16435. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16436. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16437. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16438. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16439. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16440. domUtils.remove(table);
  16441. return {
  16442. tableBorder:tableBorder,
  16443. tdPadding:tdPadding,
  16444. tdBorder:tdBorder
  16445. };
  16446. } else {
  16447. td = table.getElementsByTagName('td')[0];
  16448. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16449. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16450. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16451. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16452. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16453. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16454. return {
  16455. tableBorder:tableBorder,
  16456. tdPadding:tdPadding,
  16457. tdBorder:tdBorder
  16458. };
  16459. }
  16460. };
  16461. /**
  16462. * 根据当前点击的td或者table获取索引对象
  16463. * @param tdOrTable
  16464. */
  16465. UETable.getUETable = function (tdOrTable) {
  16466. var tag = tdOrTable.tagName.toLowerCase();
  16467. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16468. if (!tdOrTable.ueTable) {
  16469. tdOrTable.ueTable = new UETable(tdOrTable);
  16470. }
  16471. return tdOrTable.ueTable;
  16472. };
  16473. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16474. if (!cell || utils.isString(cell)) {
  16475. return this.table.ownerDocument.createElement(cell || 'td');
  16476. }
  16477. var flag = domUtils.hasClass(cell, "selectTdClass");
  16478. flag && domUtils.removeClasses(cell, "selectTdClass");
  16479. var tmpCell = cell.cloneNode(true);
  16480. if (ignoreMerge) {
  16481. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16482. }
  16483. //去掉宽高
  16484. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16485. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16486. tmpCell.style.borderLeftStyle = "";
  16487. tmpCell.style.borderTopStyle = "";
  16488. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16489. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16490. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16491. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16492. flag && domUtils.addClass(cell, "selectTdClass");
  16493. return tmpCell;
  16494. }
  16495. UETable.prototype = {
  16496. getMaxRows:function () {
  16497. var rows = this.table.rows, maxLen = 1;
  16498. for (var i = 0, row; row = rows[i]; i++) {
  16499. var currentMax = 1;
  16500. for (var j = 0, cj; cj = row.cells[j++];) {
  16501. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16502. }
  16503. maxLen = Math.max(currentMax + i, maxLen);
  16504. }
  16505. return maxLen;
  16506. },
  16507. /**
  16508. * 获取当前表格的最大列数
  16509. */
  16510. getMaxCols:function () {
  16511. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16512. for (var i = 0, row; row = rows[i]; i++) {
  16513. var cellsNum = 0;
  16514. for (var j = 0, cj; cj = row.cells[j++];) {
  16515. cellsNum += (cj.colSpan || 1);
  16516. if (cj.rowSpan && cj.rowSpan > 1) {
  16517. for (var k = 1; k < cj.rowSpan; k++) {
  16518. if (!cellRows['row_' + (i + k)]) {
  16519. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16520. } else {
  16521. cellRows['row_' + (i + k)]++
  16522. }
  16523. }
  16524. }
  16525. }
  16526. cellsNum += cellRows['row_' + i] || 0;
  16527. maxLen = Math.max(cellsNum, maxLen);
  16528. }
  16529. return maxLen;
  16530. },
  16531. getCellColIndex:function (cell) {
  16532. },
  16533. /**
  16534. * 获取当前cell旁边的单元格,
  16535. * @param cell
  16536. * @param right
  16537. */
  16538. getHSideCell:function (cell, right) {
  16539. try {
  16540. var cellInfo = this.getCellInfo(cell),
  16541. previewRowIndex, previewColIndex;
  16542. var len = this.selectedTds.length,
  16543. range = this.cellsRange;
  16544. //首行或者首列没有前置单元格
  16545. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16546. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16547. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16548. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16549. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16550. } catch (e) {
  16551. showError(e);
  16552. }
  16553. },
  16554. getTabNextCell:function (cell, preRowIndex) {
  16555. var cellInfo = this.getCellInfo(cell),
  16556. rowIndex = preRowIndex || cellInfo.rowIndex,
  16557. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16558. nextCell;
  16559. try {
  16560. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16561. } catch (e) {
  16562. try {
  16563. rowIndex = rowIndex * 1 + 1;
  16564. colIndex = 0;
  16565. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16566. } catch (e) {
  16567. }
  16568. }
  16569. return nextCell;
  16570. },
  16571. /**
  16572. * 获取视觉上的后置单元格
  16573. * @param cell
  16574. * @param bottom
  16575. */
  16576. getVSideCell:function (cell, bottom, ignoreRange) {
  16577. try {
  16578. var cellInfo = this.getCellInfo(cell),
  16579. nextRowIndex, nextColIndex;
  16580. var len = this.selectedTds.length && !ignoreRange,
  16581. range = this.cellsRange;
  16582. //末行或者末列没有后置单元格
  16583. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16584. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16585. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16586. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16587. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16588. } catch (e) {
  16589. showError(e);
  16590. }
  16591. },
  16592. /**
  16593. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16594. */
  16595. getSameEndPosCells:function (cell, xOrY) {
  16596. try {
  16597. var flag = (xOrY.toLowerCase() === "x"),
  16598. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16599. rows = this.table.rows,
  16600. cells = null, returns = [];
  16601. for (var i = 0; i < this.rowsNum; i++) {
  16602. cells = rows[i].cells;
  16603. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16604. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16605. //对应行的td已经被上面行rowSpan了
  16606. if (tmpEnd > end && flag) break;
  16607. if (cell == tmpCell || end == tmpEnd) {
  16608. //只获取单一的单元格
  16609. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16610. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16611. returns.push(tmpCell);
  16612. }
  16613. if (flag) break;
  16614. }
  16615. }
  16616. }
  16617. return returns;
  16618. } catch (e) {
  16619. showError(e);
  16620. }
  16621. },
  16622. setCellContent:function (cell, content) {
  16623. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16624. },
  16625. cloneCell:UETable.cloneCell,
  16626. /**
  16627. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16628. */
  16629. getSameStartPosXCells:function (cell) {
  16630. try {
  16631. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16632. rows = this.table.rows, cells , returns = [];
  16633. for (var i = 0; i < this.rowsNum; i++) {
  16634. cells = rows[i].cells;
  16635. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16636. var tmpStart = domUtils.getXY(tmpCell).x;
  16637. if (tmpStart > start) break;
  16638. if (tmpStart == start && tmpCell.colSpan == 1) {
  16639. returns.push(tmpCell);
  16640. break;
  16641. }
  16642. }
  16643. }
  16644. return returns;
  16645. } catch (e) {
  16646. showError(e);
  16647. }
  16648. },
  16649. /**
  16650. * 更新table对应的索引表
  16651. */
  16652. update:function (table) {
  16653. this.table = table || this.table;
  16654. this.selectedTds = [];
  16655. this.cellsRange = {};
  16656. this.indexTable = [];
  16657. var rows = this.table.rows,
  16658. rowsNum = this.getMaxRows(),
  16659. dNum = rowsNum - rows.length,
  16660. colsNum = this.getMaxCols();
  16661. while (dNum--) {
  16662. this.table.insertRow(rows.length);
  16663. }
  16664. this.rowsNum = rowsNum;
  16665. this.colsNum = colsNum;
  16666. for (var i = 0, len = rows.length; i < len; i++) {
  16667. this.indexTable[i] = new Array(colsNum);
  16668. }
  16669. //填充索引表
  16670. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16671. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16672. //修正整行被rowSpan时导致的行数计算错误
  16673. if (cell.rowSpan > rowsNum) {
  16674. cell.rowSpan = rowsNum;
  16675. }
  16676. var colIndex = cellIndex,
  16677. rowSpan = cell.rowSpan || 1,
  16678. colSpan = cell.colSpan || 1;
  16679. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16680. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16681. for (var j = 0; j < rowSpan; j++) {
  16682. for (var k = 0; k < colSpan; k++) {
  16683. this.indexTable[rowIndex + j][colIndex + k] = {
  16684. rowIndex:rowIndex,
  16685. cellIndex:cellIndex,
  16686. colIndex:colIndex,
  16687. rowSpan:rowSpan,
  16688. colSpan:colSpan
  16689. }
  16690. }
  16691. }
  16692. }
  16693. }
  16694. //修复残缺td
  16695. for (j = 0; j < rowsNum; j++) {
  16696. for (k = 0; k < colsNum; k++) {
  16697. if (this.indexTable[j][k] === undefined) {
  16698. row = rows[j];
  16699. cell = row.cells[row.cells.length - 1];
  16700. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16701. this.setCellContent(cell);
  16702. if (cell.colSpan !== 1)cell.colSpan = 1;
  16703. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16704. row.appendChild(cell);
  16705. this.indexTable[j][k] = {
  16706. rowIndex:j,
  16707. cellIndex:cell.cellIndex,
  16708. colIndex:k,
  16709. rowSpan:1,
  16710. colSpan:1
  16711. }
  16712. }
  16713. }
  16714. }
  16715. //当框选后删除行或者列后撤销,需要重建选区。
  16716. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16717. selectTds = [];
  16718. utils.each(tds, function (td) {
  16719. if (domUtils.hasClass(td, "selectTdClass")) {
  16720. selectTds.push(td);
  16721. }
  16722. });
  16723. if (selectTds.length) {
  16724. var start = selectTds[0],
  16725. end = selectTds[selectTds.length - 1],
  16726. startInfo = this.getCellInfo(start),
  16727. endInfo = this.getCellInfo(end);
  16728. this.selectedTds = selectTds;
  16729. this.cellsRange = {
  16730. beginRowIndex:startInfo.rowIndex,
  16731. beginColIndex:startInfo.colIndex,
  16732. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16733. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16734. };
  16735. }
  16736. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16737. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16738. domUtils.addClass(this.table.rows[0], "firstRow");
  16739. for(var i = 1; i< this.table.rows.length; i++) {
  16740. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16741. }
  16742. }
  16743. },
  16744. /**
  16745. * 获取单元格的索引信息
  16746. */
  16747. getCellInfo:function (cell) {
  16748. if (!cell) return;
  16749. var cellIndex = cell.cellIndex,
  16750. rowIndex = cell.parentNode.rowIndex,
  16751. rowInfo = this.indexTable[rowIndex],
  16752. numCols = this.colsNum;
  16753. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16754. var cellInfo = rowInfo[colIndex];
  16755. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16756. return cellInfo;
  16757. }
  16758. }
  16759. },
  16760. /**
  16761. * 根据行列号获取单元格
  16762. */
  16763. getCell:function (rowIndex, cellIndex) {
  16764. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16765. },
  16766. /**
  16767. * 删除单元格
  16768. */
  16769. deleteCell:function (cell, rowIndex) {
  16770. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16771. var row = this.table.rows[rowIndex];
  16772. row.deleteCell(cell.cellIndex);
  16773. },
  16774. /**
  16775. * 根据始末两个单元格获取被框选的所有单元格范围
  16776. */
  16777. getCellsRange:function (cellA, cellB) {
  16778. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16779. var tmpBeginRowIndex = beginRowIndex,
  16780. tmpBeginColIndex = beginColIndex,
  16781. tmpEndRowIndex = endRowIndex,
  16782. tmpEndColIndex = endColIndex,
  16783. cellInfo, colIndex, rowIndex;
  16784. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16785. if (beginRowIndex > 0) {
  16786. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16787. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16788. rowIndex = cellInfo.rowIndex;
  16789. if (rowIndex < beginRowIndex) {
  16790. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16791. }
  16792. }
  16793. }
  16794. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16795. if (endColIndex < me.colsNum) {
  16796. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16797. cellInfo = me.indexTable[rowIndex][endColIndex];
  16798. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16799. if (colIndex > endColIndex) {
  16800. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16801. }
  16802. }
  16803. }
  16804. // 检查是否有超出TableRange下边界的情况
  16805. if (endRowIndex < me.rowsNum) {
  16806. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16807. cellInfo = me.indexTable[endRowIndex][colIndex];
  16808. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16809. if (rowIndex > endRowIndex) {
  16810. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16811. }
  16812. }
  16813. }
  16814. // 检查是否有超出TableRange左边界的情况
  16815. if (beginColIndex > 0) {
  16816. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16817. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16818. colIndex = cellInfo.colIndex;
  16819. if (colIndex < beginColIndex) {
  16820. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16821. }
  16822. }
  16823. }
  16824. //递归调用直至所有完成所有框选单元格的扩展
  16825. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16826. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16827. } else {
  16828. // 不需要扩展TableRange的情况
  16829. return {
  16830. beginRowIndex:beginRowIndex,
  16831. beginColIndex:beginColIndex,
  16832. endRowIndex:endRowIndex,
  16833. endColIndex:endColIndex
  16834. };
  16835. }
  16836. }
  16837. try {
  16838. var me = this,
  16839. cellAInfo = me.getCellInfo(cellA);
  16840. if (cellA === cellB) {
  16841. return {
  16842. beginRowIndex:cellAInfo.rowIndex,
  16843. beginColIndex:cellAInfo.colIndex,
  16844. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16845. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16846. };
  16847. }
  16848. var cellBInfo = me.getCellInfo(cellB);
  16849. // 计算TableRange的四个边
  16850. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16851. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16852. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16853. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16854. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16855. } catch (e) {
  16856. //throw e;
  16857. }
  16858. },
  16859. /**
  16860. * 依据cellsRange获取对应的单元格集合
  16861. */
  16862. getCells:function (range) {
  16863. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16864. this.clearSelected();
  16865. var beginRowIndex = range.beginRowIndex,
  16866. beginColIndex = range.beginColIndex,
  16867. endRowIndex = range.endRowIndex,
  16868. endColIndex = range.endColIndex,
  16869. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16870. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16871. for (var j = beginColIndex; j <= endColIndex; j++) {
  16872. cellInfo = this.indexTable[i][j];
  16873. rowIndex = cellInfo.rowIndex;
  16874. colIndex = cellInfo.colIndex;
  16875. // 如果Cells里已经包含了此Cell则跳过
  16876. var key = rowIndex + '|' + colIndex;
  16877. if (tdHash[key]) continue;
  16878. tdHash[key] = 1;
  16879. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16880. return null;
  16881. }
  16882. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16883. }
  16884. }
  16885. return returnTds;
  16886. },
  16887. /**
  16888. * 清理已经选中的单元格
  16889. */
  16890. clearSelected:function () {
  16891. UETable.removeSelectedClass(this.selectedTds);
  16892. this.selectedTds = [];
  16893. this.cellsRange = {};
  16894. },
  16895. /**
  16896. * 根据range设置已经选中的单元格
  16897. */
  16898. setSelected:function (range) {
  16899. var cells = this.getCells(range);
  16900. UETable.addSelectedClass(cells);
  16901. this.selectedTds = cells;
  16902. this.cellsRange = range;
  16903. },
  16904. isFullRow:function () {
  16905. var range = this.cellsRange;
  16906. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16907. },
  16908. isFullCol:function () {
  16909. var range = this.cellsRange,
  16910. table = this.table,
  16911. ths = table.getElementsByTagName("th"),
  16912. rows = range.endRowIndex - range.beginRowIndex + 1;
  16913. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16914. },
  16915. /**
  16916. * 获取视觉上的前置单元格,默认是左边,top传入时
  16917. * @param cell
  16918. * @param top
  16919. */
  16920. getNextCell:function (cell, bottom, ignoreRange) {
  16921. try {
  16922. var cellInfo = this.getCellInfo(cell),
  16923. nextRowIndex, nextColIndex;
  16924. var len = this.selectedTds.length && !ignoreRange,
  16925. range = this.cellsRange;
  16926. //末行或者末列没有后置单元格
  16927. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16928. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16929. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16930. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16931. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16932. } catch (e) {
  16933. showError(e);
  16934. }
  16935. },
  16936. getPreviewCell:function (cell, top) {
  16937. try {
  16938. var cellInfo = this.getCellInfo(cell),
  16939. previewRowIndex, previewColIndex;
  16940. var len = this.selectedTds.length,
  16941. range = this.cellsRange;
  16942. //首行或者首列没有前置单元格
  16943. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16944. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  16945. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  16946. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16947. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  16948. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16949. } catch (e) {
  16950. showError(e);
  16951. }
  16952. },
  16953. /**
  16954. * 移动单元格中的内容
  16955. */
  16956. moveContent:function (cellTo, cellFrom) {
  16957. if (UETable.isEmptyBlock(cellFrom)) return;
  16958. if (UETable.isEmptyBlock(cellTo)) {
  16959. cellTo.innerHTML = cellFrom.innerHTML;
  16960. return;
  16961. }
  16962. var child = cellTo.lastChild;
  16963. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  16964. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  16965. }
  16966. while (child = cellFrom.firstChild) {
  16967. cellTo.appendChild(child);
  16968. }
  16969. },
  16970. /**
  16971. * 向右合并单元格
  16972. */
  16973. mergeRight:function (cell) {
  16974. var cellInfo = this.getCellInfo(cell),
  16975. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  16976. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  16977. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  16978. //合并
  16979. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  16980. //被合并的单元格不应存在宽度属性
  16981. cell.removeAttribute("width");
  16982. //移动内容
  16983. this.moveContent(cell, rightCell);
  16984. //删掉被合并的Cell
  16985. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  16986. this.update();
  16987. },
  16988. /**
  16989. * 向下合并单元格
  16990. */
  16991. mergeDown:function (cell) {
  16992. var cellInfo = this.getCellInfo(cell),
  16993. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  16994. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  16995. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  16996. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  16997. cell.removeAttribute("height");
  16998. this.moveContent(cell, downCell);
  16999. this.deleteCell(downCell, downCellInfo.rowIndex);
  17000. this.update();
  17001. },
  17002. /**
  17003. * 合并整个range中的内容
  17004. */
  17005. mergeRange:function () {
  17006. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17007. var range = this.cellsRange,
  17008. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17009. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17010. var index = this.indexTable,
  17011. info = this.getCellInfo(leftTopCell);
  17012. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17013. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17014. }
  17015. // 删除剩余的Cells
  17016. var cells = this.getCells(range);
  17017. for(var i= 0,ci;ci=cells[i++];){
  17018. if (ci !== leftTopCell) {
  17019. this.moveContent(leftTopCell, ci);
  17020. this.deleteCell(ci);
  17021. }
  17022. }
  17023. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17024. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17025. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17026. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17027. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17028. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17029. leftTopCell.colSpan = 1;
  17030. }
  17031. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17032. var rowIndex = leftTopCell.parentNode.rowIndex;
  17033. //解决IE下的表格操作问题
  17034. if( this.table.deleteRow ) {
  17035. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17036. this.table.deleteRow(curIndex);
  17037. }
  17038. } else {
  17039. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17040. var row = this.table.rows[rowIndex + 1];
  17041. row.parentNode.removeChild(row);
  17042. }
  17043. }
  17044. leftTopCell.rowSpan = 1;
  17045. }
  17046. this.update();
  17047. },
  17048. /**
  17049. * 插入一行单元格
  17050. */
  17051. insertRow:function (rowIndex, sourceCell) {
  17052. var numCols = this.colsNum,
  17053. table = this.table,
  17054. row = table.insertRow(rowIndex), cell,
  17055. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17056. function replaceTdToTh(colIndex, cell, tableRow) {
  17057. if (colIndex == 0) {
  17058. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17059. th = tr.cells[colIndex];
  17060. if (th.tagName == 'TH') {
  17061. th = cell.ownerDocument.createElement("th");
  17062. th.appendChild(cell.firstChild);
  17063. tableRow.insertBefore(th, cell);
  17064. domUtils.remove(cell)
  17065. }
  17066. }else{
  17067. if (cell.tagName == 'TH') {
  17068. var td = cell.ownerDocument.createElement("td");
  17069. td.appendChild(cell.firstChild);
  17070. tableRow.insertBefore(td, cell);
  17071. domUtils.remove(cell)
  17072. }
  17073. }
  17074. }
  17075. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17076. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17077. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17078. cell = this.cloneCell(sourceCell, true);
  17079. this.setCellContent(cell);
  17080. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17081. row.appendChild(cell);
  17082. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17083. }
  17084. } else {
  17085. var infoRow = this.indexTable[rowIndex],
  17086. cellIndex = 0;
  17087. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17088. var cellInfo = infoRow[colIndex];
  17089. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17090. if (cellInfo.rowIndex < rowIndex) {
  17091. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17092. cell.rowSpan = cellInfo.rowSpan + 1;
  17093. } else {
  17094. cell = this.cloneCell(sourceCell, true);
  17095. this.setCellContent(cell);
  17096. row.appendChild(cell);
  17097. }
  17098. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17099. }
  17100. }
  17101. //框选时插入不触发contentchange,需要手动更新索引。
  17102. this.update();
  17103. return row;
  17104. },
  17105. /**
  17106. * 删除一行单元格
  17107. * @param rowIndex
  17108. */
  17109. deleteRow:function (rowIndex) {
  17110. var row = this.table.rows[rowIndex],
  17111. infoRow = this.indexTable[rowIndex],
  17112. colsNum = this.colsNum,
  17113. count = 0; //处理计数
  17114. for (var colIndex = 0; colIndex < colsNum;) {
  17115. var cellInfo = infoRow[colIndex],
  17116. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17117. if (cell.rowSpan > 1) {
  17118. if (cellInfo.rowIndex == rowIndex) {
  17119. var clone = cell.cloneNode(true);
  17120. clone.rowSpan = cell.rowSpan - 1;
  17121. clone.innerHTML = "";
  17122. cell.rowSpan = 1;
  17123. var nextRowIndex = rowIndex + 1,
  17124. nextRow = this.table.rows[nextRowIndex],
  17125. insertCellIndex,
  17126. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17127. if (preMerged < colIndex) {
  17128. insertCellIndex = colIndex - preMerged - 1;
  17129. //nextRow.insertCell(insertCellIndex);
  17130. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17131. } else {
  17132. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17133. }
  17134. count += 1;
  17135. //cell.parentNode.removeChild(cell);
  17136. }
  17137. }
  17138. colIndex += cell.colSpan || 1;
  17139. }
  17140. var deleteTds = [], cacheMap = {};
  17141. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17142. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17143. tmpCellIndex = infoRow[colIndex].cellIndex,
  17144. key = tmpRowIndex + "_" + tmpCellIndex;
  17145. if (cacheMap[key])continue;
  17146. cacheMap[key] = 1;
  17147. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17148. deleteTds.push(cell);
  17149. }
  17150. var mergeTds = [];
  17151. utils.each(deleteTds, function (td) {
  17152. if (td.rowSpan == 1) {
  17153. td.parentNode.removeChild(td);
  17154. } else {
  17155. mergeTds.push(td);
  17156. }
  17157. });
  17158. utils.each(mergeTds, function (td) {
  17159. td.rowSpan--;
  17160. });
  17161. row.parentNode.removeChild(row);
  17162. //浏览器方法本身存在bug,采用自定义方法删除
  17163. //this.table.deleteRow(rowIndex);
  17164. this.update();
  17165. },
  17166. insertCol:function (colIndex, sourceCell, defaultValue) {
  17167. var rowsNum = this.rowsNum,
  17168. rowIndex = 0,
  17169. tableRow, cell,
  17170. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17171. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17172. function replaceTdToTh(rowIndex, cell, tableRow) {
  17173. if (rowIndex == 0) {
  17174. var th = cell.nextSibling || cell.previousSibling;
  17175. if (th.tagName == 'TH') {
  17176. th = cell.ownerDocument.createElement("th");
  17177. th.appendChild(cell.firstChild);
  17178. tableRow.insertBefore(th, cell);
  17179. domUtils.remove(cell)
  17180. }
  17181. }else{
  17182. if (cell.tagName == 'TH') {
  17183. var td = cell.ownerDocument.createElement("td");
  17184. td.appendChild(cell.firstChild);
  17185. tableRow.insertBefore(td, cell);
  17186. domUtils.remove(cell)
  17187. }
  17188. }
  17189. }
  17190. var preCell;
  17191. if (colIndex == 0 || colIndex == this.colsNum) {
  17192. for (; rowIndex < rowsNum; rowIndex++) {
  17193. tableRow = this.table.rows[rowIndex];
  17194. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17195. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17196. this.setCellContent(cell);
  17197. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17198. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17199. if (!colIndex) {
  17200. tableRow.insertBefore(cell, tableRow.cells[0]);
  17201. } else {
  17202. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17203. }
  17204. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17205. }
  17206. } else {
  17207. for (; rowIndex < rowsNum; rowIndex++) {
  17208. var cellInfo = this.indexTable[rowIndex][colIndex];
  17209. if (cellInfo.colIndex < colIndex) {
  17210. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17211. cell.colSpan = cellInfo.colSpan + 1;
  17212. } else {
  17213. tableRow = this.table.rows[rowIndex];
  17214. preCell = tableRow.cells[cellInfo.cellIndex];
  17215. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17216. this.setCellContent(cell);
  17217. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17218. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17219. //防止IE下报错
  17220. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17221. }
  17222. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17223. }
  17224. }
  17225. //框选时插入不触发contentchange,需要手动更新索引
  17226. this.update();
  17227. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17228. },
  17229. updateWidth:function (width, defaultValue) {
  17230. var table = this.table,
  17231. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17232. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17233. table.setAttribute("width", tmpWidth);
  17234. return;
  17235. }
  17236. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17237. utils.each(tds, function (td) {
  17238. td.setAttribute("width", width);
  17239. })
  17240. },
  17241. deleteCol:function (colIndex) {
  17242. var indexTable = this.indexTable,
  17243. tableRows = this.table.rows,
  17244. backTableWidth = this.table.getAttribute("width"),
  17245. backTdWidth = 0,
  17246. rowsNum = this.rowsNum,
  17247. cacheMap = {};
  17248. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17249. var infoRow = indexTable[rowIndex],
  17250. cellInfo = infoRow[colIndex],
  17251. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17252. // 跳过已经处理过的Cell
  17253. if (cacheMap[key])continue;
  17254. cacheMap[key] = 1;
  17255. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17256. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17257. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17258. if (cell.colSpan > 1) {
  17259. cell.colSpan--;
  17260. } else {
  17261. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17262. }
  17263. rowIndex += cellInfo.rowSpan || 1;
  17264. }
  17265. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17266. this.update();
  17267. },
  17268. splitToCells:function (cell) {
  17269. var me = this,
  17270. cells = this.splitToRows(cell);
  17271. utils.each(cells, function (cell) {
  17272. me.splitToCols(cell);
  17273. })
  17274. },
  17275. splitToRows:function (cell) {
  17276. var cellInfo = this.getCellInfo(cell),
  17277. rowIndex = cellInfo.rowIndex,
  17278. colIndex = cellInfo.colIndex,
  17279. results = [];
  17280. // 修改Cell的rowSpan
  17281. cell.rowSpan = 1;
  17282. results.push(cell);
  17283. // 补齐单元格
  17284. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17285. if (i == rowIndex)continue;
  17286. var tableRow = this.table.rows[i],
  17287. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17288. tmpCell.colSpan = cellInfo.colSpan;
  17289. this.setCellContent(tmpCell);
  17290. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17291. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17292. if (cell.style.cssText) {
  17293. tmpCell.style.cssText = cell.style.cssText;
  17294. }
  17295. results.push(tmpCell);
  17296. }
  17297. this.update();
  17298. return results;
  17299. },
  17300. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17301. var indexRow = this.indexTable[rowIndex],
  17302. num = 0;
  17303. for (var i = 0; i < colIndex;) {
  17304. var colSpan = indexRow[i].colSpan,
  17305. tmpRowIndex = indexRow[i].rowIndex;
  17306. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17307. i += colSpan;
  17308. }
  17309. return num;
  17310. },
  17311. splitToCols:function (cell) {
  17312. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17313. cellInfo = this.getCellInfo(cell),
  17314. rowIndex = cellInfo.rowIndex,
  17315. colIndex = cellInfo.colIndex,
  17316. results = [];
  17317. // 修改Cell的rowSpan
  17318. cell.colSpan = 1;
  17319. cell.setAttribute("width", backWidth);
  17320. results.push(cell);
  17321. // 补齐单元格
  17322. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17323. if (j == colIndex)continue;
  17324. var tableRow = this.table.rows[rowIndex],
  17325. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17326. tmpCell.rowSpan = cellInfo.rowSpan;
  17327. this.setCellContent(tmpCell);
  17328. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17329. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17330. tmpCell.setAttribute('width', backWidth);
  17331. if (cell.style.cssText) {
  17332. tmpCell.style.cssText = cell.style.cssText;
  17333. }
  17334. //处理th的情况
  17335. if (cell.tagName == 'TH') {
  17336. var th = cell.ownerDocument.createElement('th');
  17337. th.appendChild(tmpCell.firstChild);
  17338. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17339. th.rowSpan = tmpCell.rowSpan;
  17340. tableRow.insertBefore(th, tmpCell);
  17341. domUtils.remove(tmpCell);
  17342. }
  17343. results.push(tmpCell);
  17344. }
  17345. this.update();
  17346. return results;
  17347. },
  17348. isLastCell:function (cell, rowsNum, colsNum) {
  17349. rowsNum = rowsNum || this.rowsNum;
  17350. colsNum = colsNum || this.colsNum;
  17351. var cellInfo = this.getCellInfo(cell);
  17352. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17353. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17354. },
  17355. getLastCell:function (cells) {
  17356. cells = cells || this.table.getElementsByTagName("td");
  17357. var firstInfo = this.getCellInfo(cells[0]);
  17358. var me = this, last = cells[0],
  17359. tr = last.parentNode,
  17360. cellsNum = 0, cols = 0, rows;
  17361. utils.each(cells, function (cell) {
  17362. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17363. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17364. });
  17365. rows = cellsNum / cols;
  17366. utils.each(cells, function (cell) {
  17367. if (me.isLastCell(cell, rows, cols)) {
  17368. last = cell;
  17369. return false;
  17370. }
  17371. });
  17372. return last;
  17373. },
  17374. selectRow:function (rowIndex) {
  17375. var indexRow = this.indexTable[rowIndex],
  17376. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17377. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17378. range = this.getCellsRange(start, end);
  17379. this.setSelected(range);
  17380. },
  17381. selectTable:function () {
  17382. var tds = this.table.getElementsByTagName("td"),
  17383. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17384. this.setSelected(range);
  17385. },
  17386. setBackground:function (cells, value) {
  17387. if (typeof value === "string") {
  17388. utils.each(cells, function (cell) {
  17389. cell.style.backgroundColor = value;
  17390. })
  17391. } else if (typeof value === "object") {
  17392. value = utils.extend({
  17393. repeat:true,
  17394. colorList:["#ddd", "#fff"]
  17395. }, value);
  17396. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17397. count = 0,
  17398. colors = value.colorList,
  17399. getColor = function (list, index, repeat) {
  17400. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17401. };
  17402. for (var i = 0, cell; cell = cells[i++];) {
  17403. var cellInfo = this.getCellInfo(cell);
  17404. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17405. }
  17406. }
  17407. },
  17408. removeBackground:function (cells) {
  17409. utils.each(cells, function (cell) {
  17410. cell.style.backgroundColor = "";
  17411. })
  17412. }
  17413. };
  17414. function showError(e) {
  17415. }
  17416. })();
  17417. // plugins/table.cmds.js
  17418. /**
  17419. * Created with JetBrains PhpStorm.
  17420. * User: taoqili
  17421. * Date: 13-2-20
  17422. * Time: 下午6:25
  17423. * To change this template use File | Settings | File Templates.
  17424. */
  17425. ;
  17426. (function () {
  17427. var UT = UE.UETable,
  17428. getTableItemsByRange = function (editor) {
  17429. return UT.getTableItemsByRange(editor);
  17430. },
  17431. getUETableBySelected = function (editor) {
  17432. return UT.getUETableBySelected(editor)
  17433. },
  17434. getDefaultValue = function (editor, table) {
  17435. return UT.getDefaultValue(editor, table);
  17436. },
  17437. getUETable = function (tdOrTable) {
  17438. return UT.getUETable(tdOrTable);
  17439. };
  17440. UE.commands['inserttable'] = {
  17441. queryCommandState: function () {
  17442. return getTableItemsByRange(this).table ? -1 : 0;
  17443. },
  17444. execCommand: function (cmd, opt) {
  17445. function createTable(opt, tdWidth) {
  17446. var html = [],
  17447. rowsNum = opt.numRows,
  17448. colsNum = opt.numCols;
  17449. for (var r = 0; r < rowsNum; r++) {
  17450. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17451. for (var c = 0; c < colsNum; c++) {
  17452. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17453. }
  17454. html.push('</tr>')
  17455. }
  17456. //禁止指定table-width
  17457. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17458. }
  17459. if (!opt) {
  17460. opt = utils.extend({}, {
  17461. numCols: this.options.defaultCols,
  17462. numRows: this.options.defaultRows,
  17463. tdvalign: this.options.tdvalign
  17464. })
  17465. }
  17466. var me = this;
  17467. var range = this.selection.getRange(),
  17468. start = range.startContainer,
  17469. firstParentBlock = domUtils.findParent(start, function (node) {
  17470. return domUtils.isBlockElm(node);
  17471. }, true) || me.body;
  17472. var defaultValue = getDefaultValue(me),
  17473. tableWidth = firstParentBlock.offsetWidth,
  17474. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17475. //todo其他属性
  17476. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17477. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17478. }
  17479. };
  17480. UE.commands['insertparagraphbeforetable'] = {
  17481. queryCommandState: function () {
  17482. return getTableItemsByRange(this).cell ? 0 : -1;
  17483. },
  17484. execCommand: function () {
  17485. var table = getTableItemsByRange(this).table;
  17486. if (table) {
  17487. var p = this.document.createElement("p");
  17488. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17489. table.parentNode.insertBefore(p, table);
  17490. this.selection.getRange().setStart(p, 0).setCursor();
  17491. }
  17492. }
  17493. };
  17494. UE.commands['deletetable'] = {
  17495. queryCommandState: function () {
  17496. var rng = this.selection.getRange();
  17497. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17498. },
  17499. execCommand: function (cmd, table) {
  17500. var rng = this.selection.getRange();
  17501. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17502. if (table) {
  17503. var next = table.nextSibling;
  17504. if (!next) {
  17505. next = domUtils.createElement(this.document, 'p', {
  17506. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17507. });
  17508. table.parentNode.insertBefore(next, table);
  17509. }
  17510. domUtils.remove(table);
  17511. rng = this.selection.getRange();
  17512. if (next.nodeType == 3) {
  17513. rng.setStartBefore(next)
  17514. } else {
  17515. rng.setStart(next, 0)
  17516. }
  17517. rng.setCursor(false, true)
  17518. this.fireEvent("tablehasdeleted")
  17519. }
  17520. }
  17521. };
  17522. UE.commands['cellalign'] = {
  17523. queryCommandState: function () {
  17524. return getSelectedArr(this).length ? 0 : -1
  17525. },
  17526. execCommand: function (cmd, align) {
  17527. var selectedTds = getSelectedArr(this);
  17528. if (selectedTds.length) {
  17529. for (var i = 0, ci; ci = selectedTds[i++];) {
  17530. ci.setAttribute('align', align);
  17531. }
  17532. }
  17533. }
  17534. };
  17535. UE.commands['cellvalign'] = {
  17536. queryCommandState: function () {
  17537. return getSelectedArr(this).length ? 0 : -1;
  17538. },
  17539. execCommand: function (cmd, valign) {
  17540. var selectedTds = getSelectedArr(this);
  17541. if (selectedTds.length) {
  17542. for (var i = 0, ci; ci = selectedTds[i++];) {
  17543. ci.setAttribute('vAlign', valign);
  17544. }
  17545. }
  17546. }
  17547. };
  17548. UE.commands['insertcaption'] = {
  17549. queryCommandState: function () {
  17550. var table = getTableItemsByRange(this).table;
  17551. if (table) {
  17552. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17553. }
  17554. return -1;
  17555. },
  17556. execCommand: function () {
  17557. var table = getTableItemsByRange(this).table;
  17558. if (table) {
  17559. var caption = this.document.createElement('caption');
  17560. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17561. table.insertBefore(caption, table.firstChild);
  17562. var range = this.selection.getRange();
  17563. range.setStart(caption, 0).setCursor();
  17564. }
  17565. }
  17566. };
  17567. UE.commands['deletecaption'] = {
  17568. queryCommandState: function () {
  17569. var rng = this.selection.getRange(),
  17570. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17571. if (table) {
  17572. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17573. }
  17574. return -1;
  17575. },
  17576. execCommand: function () {
  17577. var rng = this.selection.getRange(),
  17578. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17579. if (table) {
  17580. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17581. var range = this.selection.getRange();
  17582. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17583. }
  17584. }
  17585. };
  17586. UE.commands['inserttitle'] = {
  17587. queryCommandState: function () {
  17588. var table = getTableItemsByRange(this).table;
  17589. if (table) {
  17590. var firstRow = table.rows[0];
  17591. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17592. }
  17593. return -1;
  17594. },
  17595. execCommand: function () {
  17596. var table = getTableItemsByRange(this).table;
  17597. if (table) {
  17598. getUETable(table).insertRow(0, 'th');
  17599. }
  17600. var th = table.getElementsByTagName('th')[0];
  17601. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17602. }
  17603. };
  17604. UE.commands['deletetitle'] = {
  17605. queryCommandState: function () {
  17606. var table = getTableItemsByRange(this).table;
  17607. if (table) {
  17608. var firstRow = table.rows[0];
  17609. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17610. }
  17611. return -1;
  17612. },
  17613. execCommand: function () {
  17614. var table = getTableItemsByRange(this).table;
  17615. if (table) {
  17616. domUtils.remove(table.rows[0])
  17617. }
  17618. var td = table.getElementsByTagName('td')[0];
  17619. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17620. }
  17621. };
  17622. UE.commands['inserttitlecol'] = {
  17623. queryCommandState: function () {
  17624. var table = getTableItemsByRange(this).table;
  17625. if (table) {
  17626. var lastRow = table.rows[table.rows.length-1];
  17627. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17628. }
  17629. return -1;
  17630. },
  17631. execCommand: function (cmd) {
  17632. var table = getTableItemsByRange(this).table;
  17633. if (table) {
  17634. getUETable(table).insertCol(0, 'th');
  17635. }
  17636. resetTdWidth(table, this);
  17637. var th = table.getElementsByTagName('th')[0];
  17638. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17639. }
  17640. };
  17641. UE.commands['deletetitlecol'] = {
  17642. queryCommandState: function () {
  17643. var table = getTableItemsByRange(this).table;
  17644. if (table) {
  17645. var lastRow = table.rows[table.rows.length-1];
  17646. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17647. }
  17648. return -1;
  17649. },
  17650. execCommand: function () {
  17651. var table = getTableItemsByRange(this).table;
  17652. if (table) {
  17653. for(var i = 0; i< table.rows.length; i++ ){
  17654. domUtils.remove(table.rows[i].children[0])
  17655. }
  17656. }
  17657. resetTdWidth(table, this);
  17658. var td = table.getElementsByTagName('td')[0];
  17659. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17660. }
  17661. };
  17662. UE.commands["mergeright"] = {
  17663. queryCommandState: function (cmd) {
  17664. var tableItems = getTableItemsByRange(this),
  17665. table = tableItems.table,
  17666. cell = tableItems.cell;
  17667. if (!table || !cell) return -1;
  17668. var ut = getUETable(table);
  17669. if (ut.selectedTds.length) return -1;
  17670. var cellInfo = ut.getCellInfo(cell),
  17671. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17672. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17673. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17674. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17675. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17676. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17677. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17678. },
  17679. execCommand: function (cmd) {
  17680. var rng = this.selection.getRange(),
  17681. bk = rng.createBookmark(true);
  17682. var cell = getTableItemsByRange(this).cell,
  17683. ut = getUETable(cell);
  17684. ut.mergeRight(cell);
  17685. rng.moveToBookmark(bk).select();
  17686. }
  17687. };
  17688. UE.commands["mergedown"] = {
  17689. queryCommandState: function (cmd) {
  17690. var tableItems = getTableItemsByRange(this),
  17691. table = tableItems.table,
  17692. cell = tableItems.cell;
  17693. if (!table || !cell) return -1;
  17694. var ut = getUETable(table);
  17695. if (ut.selectedTds.length)return -1;
  17696. var cellInfo = ut.getCellInfo(cell),
  17697. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17698. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17699. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17700. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17701. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17702. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17703. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17704. },
  17705. execCommand: function () {
  17706. var rng = this.selection.getRange(),
  17707. bk = rng.createBookmark(true);
  17708. var cell = getTableItemsByRange(this).cell,
  17709. ut = getUETable(cell);
  17710. ut.mergeDown(cell);
  17711. rng.moveToBookmark(bk).select();
  17712. }
  17713. };
  17714. UE.commands["mergecells"] = {
  17715. queryCommandState: function () {
  17716. return getUETableBySelected(this) ? 0 : -1;
  17717. },
  17718. execCommand: function () {
  17719. var ut = getUETableBySelected(this);
  17720. if (ut && ut.selectedTds.length) {
  17721. var cell = ut.selectedTds[0];
  17722. ut.mergeRange();
  17723. var rng = this.selection.getRange();
  17724. if (domUtils.isEmptyBlock(cell)) {
  17725. rng.setStart(cell, 0).collapse(true)
  17726. } else {
  17727. rng.selectNodeContents(cell)
  17728. }
  17729. rng.select();
  17730. }
  17731. }
  17732. };
  17733. UE.commands["insertrow"] = {
  17734. queryCommandState: function () {
  17735. var tableItems = getTableItemsByRange(this),
  17736. cell = tableItems.cell;
  17737. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17738. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17739. },
  17740. execCommand: function () {
  17741. var rng = this.selection.getRange(),
  17742. bk = rng.createBookmark(true);
  17743. var tableItems = getTableItemsByRange(this),
  17744. cell = tableItems.cell,
  17745. table = tableItems.table,
  17746. ut = getUETable(table),
  17747. cellInfo = ut.getCellInfo(cell);
  17748. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17749. if (!ut.selectedTds.length) {
  17750. ut.insertRow(cellInfo.rowIndex, cell);
  17751. } else {
  17752. var range = ut.cellsRange;
  17753. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17754. ut.insertRow(range.beginRowIndex, cell);
  17755. }
  17756. }
  17757. rng.moveToBookmark(bk).select();
  17758. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17759. }
  17760. };
  17761. //后插入行
  17762. UE.commands["insertrownext"] = {
  17763. queryCommandState: function () {
  17764. var tableItems = getTableItemsByRange(this),
  17765. cell = tableItems.cell;
  17766. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17767. },
  17768. execCommand: function () {
  17769. var rng = this.selection.getRange(),
  17770. bk = rng.createBookmark(true);
  17771. var tableItems = getTableItemsByRange(this),
  17772. cell = tableItems.cell,
  17773. table = tableItems.table,
  17774. ut = getUETable(table),
  17775. cellInfo = ut.getCellInfo(cell);
  17776. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17777. if (!ut.selectedTds.length) {
  17778. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17779. } else {
  17780. var range = ut.cellsRange;
  17781. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17782. ut.insertRow(range.endRowIndex + 1, cell);
  17783. }
  17784. }
  17785. rng.moveToBookmark(bk).select();
  17786. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17787. }
  17788. };
  17789. UE.commands["deleterow"] = {
  17790. queryCommandState: function () {
  17791. var tableItems = getTableItemsByRange(this);
  17792. return tableItems.cell ? 0 : -1;
  17793. },
  17794. execCommand: function () {
  17795. var cell = getTableItemsByRange(this).cell,
  17796. ut = getUETable(cell),
  17797. cellsRange = ut.cellsRange,
  17798. cellInfo = ut.getCellInfo(cell),
  17799. preCell = ut.getVSideCell(cell),
  17800. nextCell = ut.getVSideCell(cell, true),
  17801. rng = this.selection.getRange();
  17802. if (utils.isEmptyObject(cellsRange)) {
  17803. ut.deleteRow(cellInfo.rowIndex);
  17804. } else {
  17805. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17806. ut.deleteRow(cellsRange.beginRowIndex);
  17807. }
  17808. }
  17809. var table = ut.table;
  17810. if (!table.getElementsByTagName('td').length) {
  17811. var nextSibling = table.nextSibling;
  17812. domUtils.remove(table);
  17813. if (nextSibling) {
  17814. rng.setStart(nextSibling, 0).setCursor(false, true);
  17815. }
  17816. } else {
  17817. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17818. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17819. } else {
  17820. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17821. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17822. }
  17823. }
  17824. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17825. }
  17826. };
  17827. UE.commands["insertcol"] = {
  17828. queryCommandState: function (cmd) {
  17829. var tableItems = getTableItemsByRange(this),
  17830. cell = tableItems.cell;
  17831. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17832. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17833. },
  17834. execCommand: function (cmd) {
  17835. var rng = this.selection.getRange(),
  17836. bk = rng.createBookmark(true);
  17837. if (this.queryCommandState(cmd) == -1)return;
  17838. var cell = getTableItemsByRange(this).cell,
  17839. ut = getUETable(cell),
  17840. cellInfo = ut.getCellInfo(cell);
  17841. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17842. if (!ut.selectedTds.length) {
  17843. ut.insertCol(cellInfo.colIndex, cell);
  17844. } else {
  17845. var range = ut.cellsRange;
  17846. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17847. ut.insertCol(range.beginColIndex, cell);
  17848. }
  17849. }
  17850. rng.moveToBookmark(bk).select(true);
  17851. }
  17852. };
  17853. UE.commands["insertcolnext"] = {
  17854. queryCommandState: function () {
  17855. var tableItems = getTableItemsByRange(this),
  17856. cell = tableItems.cell;
  17857. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17858. },
  17859. execCommand: function () {
  17860. var rng = this.selection.getRange(),
  17861. bk = rng.createBookmark(true);
  17862. var cell = getTableItemsByRange(this).cell,
  17863. ut = getUETable(cell),
  17864. cellInfo = ut.getCellInfo(cell);
  17865. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17866. if (!ut.selectedTds.length) {
  17867. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17868. } else {
  17869. var range = ut.cellsRange;
  17870. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17871. ut.insertCol(range.endColIndex + 1, cell);
  17872. }
  17873. }
  17874. rng.moveToBookmark(bk).select();
  17875. }
  17876. };
  17877. UE.commands["deletecol"] = {
  17878. queryCommandState: function () {
  17879. var tableItems = getTableItemsByRange(this);
  17880. return tableItems.cell ? 0 : -1;
  17881. },
  17882. execCommand: function () {
  17883. var cell = getTableItemsByRange(this).cell,
  17884. ut = getUETable(cell),
  17885. range = ut.cellsRange,
  17886. cellInfo = ut.getCellInfo(cell),
  17887. preCell = ut.getHSideCell(cell),
  17888. nextCell = ut.getHSideCell(cell, true);
  17889. if (utils.isEmptyObject(range)) {
  17890. ut.deleteCol(cellInfo.colIndex);
  17891. } else {
  17892. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17893. ut.deleteCol(range.beginColIndex);
  17894. }
  17895. }
  17896. var table = ut.table,
  17897. rng = this.selection.getRange();
  17898. if (!table.getElementsByTagName('td').length) {
  17899. var nextSibling = table.nextSibling;
  17900. domUtils.remove(table);
  17901. if (nextSibling) {
  17902. rng.setStart(nextSibling, 0).setCursor(false, true);
  17903. }
  17904. } else {
  17905. if (domUtils.inDoc(cell, this.document)) {
  17906. rng.setStart(cell, 0).setCursor(false, true);
  17907. } else {
  17908. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17909. rng.selectNodeContents(nextCell).setCursor(false, true);
  17910. } else {
  17911. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17912. rng.selectNodeContents(preCell).setCursor(true, true);
  17913. }
  17914. }
  17915. }
  17916. }
  17917. }
  17918. };
  17919. UE.commands["splittocells"] = {
  17920. queryCommandState: function () {
  17921. var tableItems = getTableItemsByRange(this),
  17922. cell = tableItems.cell;
  17923. if (!cell) return -1;
  17924. var ut = getUETable(tableItems.table);
  17925. if (ut.selectedTds.length > 0) return -1;
  17926. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17927. },
  17928. execCommand: function () {
  17929. var rng = this.selection.getRange(),
  17930. bk = rng.createBookmark(true);
  17931. var cell = getTableItemsByRange(this).cell,
  17932. ut = getUETable(cell);
  17933. ut.splitToCells(cell);
  17934. rng.moveToBookmark(bk).select();
  17935. }
  17936. };
  17937. UE.commands["splittorows"] = {
  17938. queryCommandState: function () {
  17939. var tableItems = getTableItemsByRange(this),
  17940. cell = tableItems.cell;
  17941. if (!cell) return -1;
  17942. var ut = getUETable(tableItems.table);
  17943. if (ut.selectedTds.length > 0) return -1;
  17944. return cell && cell.rowSpan > 1 ? 0 : -1;
  17945. },
  17946. execCommand: function () {
  17947. var rng = this.selection.getRange(),
  17948. bk = rng.createBookmark(true);
  17949. var cell = getTableItemsByRange(this).cell,
  17950. ut = getUETable(cell);
  17951. ut.splitToRows(cell);
  17952. rng.moveToBookmark(bk).select();
  17953. }
  17954. };
  17955. UE.commands["splittocols"] = {
  17956. queryCommandState: function () {
  17957. var tableItems = getTableItemsByRange(this),
  17958. cell = tableItems.cell;
  17959. if (!cell) return -1;
  17960. var ut = getUETable(tableItems.table);
  17961. if (ut.selectedTds.length > 0) return -1;
  17962. return cell && cell.colSpan > 1 ? 0 : -1;
  17963. },
  17964. execCommand: function () {
  17965. var rng = this.selection.getRange(),
  17966. bk = rng.createBookmark(true);
  17967. var cell = getTableItemsByRange(this).cell,
  17968. ut = getUETable(cell);
  17969. ut.splitToCols(cell);
  17970. rng.moveToBookmark(bk).select();
  17971. }
  17972. };
  17973. UE.commands["adaptbytext"] =
  17974. UE.commands["adaptbywindow"] = {
  17975. queryCommandState: function () {
  17976. return getTableItemsByRange(this).table ? 0 : -1
  17977. },
  17978. execCommand: function (cmd) {
  17979. var tableItems = getTableItemsByRange(this),
  17980. table = tableItems.table;
  17981. if (table) {
  17982. if (cmd == 'adaptbywindow') {
  17983. resetTdWidth(table, this);
  17984. } else {
  17985. var cells = domUtils.getElementsByTagName(table, "td th");
  17986. utils.each(cells, function (cell) {
  17987. cell.removeAttribute("width");
  17988. });
  17989. table.removeAttribute("width");
  17990. }
  17991. }
  17992. }
  17993. };
  17994. //平均分配各列
  17995. UE.commands['averagedistributecol'] = {
  17996. queryCommandState: function () {
  17997. var ut = getUETableBySelected(this);
  17998. if (!ut) return -1;
  17999. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18000. },
  18001. execCommand: function (cmd) {
  18002. var me = this,
  18003. ut = getUETableBySelected(me);
  18004. function getAverageWidth() {
  18005. var tb = ut.table,
  18006. averageWidth, sumWidth = 0, colsNum = 0,
  18007. tbAttr = getDefaultValue(me, tb);
  18008. if (ut.isFullRow()) {
  18009. sumWidth = tb.offsetWidth;
  18010. colsNum = ut.colsNum;
  18011. } else {
  18012. var begin = ut.cellsRange.beginColIndex,
  18013. end = ut.cellsRange.endColIndex,
  18014. node;
  18015. for (var i = begin; i <= end;) {
  18016. node = ut.selectedTds[i];
  18017. sumWidth += node.offsetWidth;
  18018. i += node.colSpan;
  18019. colsNum += 1;
  18020. }
  18021. }
  18022. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18023. return averageWidth;
  18024. }
  18025. function setAverageWidth(averageWidth) {
  18026. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18027. node.setAttribute("width", "");
  18028. });
  18029. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18030. utils.each(cells, function (node) {
  18031. if (node.colSpan == 1) {
  18032. node.setAttribute("width", averageWidth);
  18033. }
  18034. });
  18035. }
  18036. if (ut && ut.selectedTds.length) {
  18037. setAverageWidth(getAverageWidth());
  18038. }
  18039. }
  18040. };
  18041. //平均分配各行
  18042. UE.commands['averagedistributerow'] = {
  18043. queryCommandState: function () {
  18044. var ut = getUETableBySelected(this);
  18045. if (!ut) return -1;
  18046. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18047. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18048. },
  18049. execCommand: function (cmd) {
  18050. var me = this,
  18051. ut = getUETableBySelected(me);
  18052. function getAverageHeight() {
  18053. var averageHeight, rowNum, sumHeight = 0,
  18054. tb = ut.table,
  18055. tbAttr = getDefaultValue(me, tb),
  18056. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18057. if (ut.isFullCol()) {
  18058. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18059. thArr = domUtils.getElementsByTagName(tb, "th"),
  18060. captionHeight, thHeight;
  18061. if (captionArr.length > 0) {
  18062. captionHeight = captionArr[0].offsetHeight;
  18063. }
  18064. if (thArr.length > 0) {
  18065. thHeight = thArr[0].offsetHeight;
  18066. }
  18067. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18068. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18069. } else {
  18070. var begin = ut.cellsRange.beginRowIndex,
  18071. end = ut.cellsRange.endRowIndex,
  18072. count = 0,
  18073. trs = domUtils.getElementsByTagName(tb, "tr");
  18074. for (var i = begin; i <= end; i++) {
  18075. sumHeight += trs[i].offsetHeight;
  18076. count += 1;
  18077. }
  18078. rowNum = count;
  18079. }
  18080. //ie8下是混杂模式
  18081. if (browser.ie && browser.version < 9) {
  18082. averageHeight = Math.ceil(sumHeight / rowNum);
  18083. } else {
  18084. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18085. }
  18086. return averageHeight;
  18087. }
  18088. function setAverageHeight(averageHeight) {
  18089. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18090. utils.each(cells, function (node) {
  18091. if (node.rowSpan == 1) {
  18092. node.setAttribute("height", averageHeight);
  18093. }
  18094. });
  18095. }
  18096. if (ut && ut.selectedTds.length) {
  18097. setAverageHeight(getAverageHeight());
  18098. }
  18099. }
  18100. };
  18101. //单元格对齐方式
  18102. UE.commands['cellalignment'] = {
  18103. queryCommandState: function () {
  18104. return getTableItemsByRange(this).table ? 0 : -1
  18105. },
  18106. execCommand: function (cmd, data) {
  18107. var me = this,
  18108. ut = getUETableBySelected(me);
  18109. if (!ut) {
  18110. var start = me.selection.getStart(),
  18111. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18112. if (!/caption/ig.test(cell.tagName)) {
  18113. domUtils.setAttributes(cell, data);
  18114. } else {
  18115. cell.style.textAlign = data.align;
  18116. cell.style.verticalAlign = data.vAlign;
  18117. }
  18118. me.selection.getRange().setCursor(true);
  18119. } else {
  18120. utils.each(ut.selectedTds, function (cell) {
  18121. domUtils.setAttributes(cell, data);
  18122. });
  18123. }
  18124. },
  18125. /**
  18126. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18127. * @see UE.UETable.getTableCellAlignState
  18128. */
  18129. queryCommandValue: function (cmd) {
  18130. var activeMenuCell = getTableItemsByRange( this).cell;
  18131. if( !activeMenuCell ) {
  18132. activeMenuCell = getSelectedArr(this)[0];
  18133. }
  18134. if (!activeMenuCell) {
  18135. return null;
  18136. } else {
  18137. //获取同时选中的其他单元格
  18138. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18139. !cells.length && ( cells = activeMenuCell );
  18140. return UE.UETable.getTableCellAlignState(cells);
  18141. }
  18142. }
  18143. };
  18144. //表格对齐方式
  18145. UE.commands['tablealignment'] = {
  18146. queryCommandState: function () {
  18147. if (browser.ie && browser.version < 8) {
  18148. return -1;
  18149. }
  18150. return getTableItemsByRange(this).table ? 0 : -1
  18151. },
  18152. execCommand: function (cmd, value) {
  18153. var me = this,
  18154. start = me.selection.getStart(),
  18155. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18156. if (table) {
  18157. table.setAttribute("align",value);
  18158. }
  18159. }
  18160. };
  18161. //表格属性
  18162. UE.commands['edittable'] = {
  18163. queryCommandState: function () {
  18164. return getTableItemsByRange(this).table ? 0 : -1
  18165. },
  18166. execCommand: function (cmd, color) {
  18167. var rng = this.selection.getRange(),
  18168. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18169. if (table) {
  18170. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18171. domUtils.getElementsByTagName(table, "th"),
  18172. domUtils.getElementsByTagName(table, "caption")
  18173. );
  18174. utils.each(arr, function (node) {
  18175. node.style.borderColor = color;
  18176. });
  18177. }
  18178. }
  18179. };
  18180. //单元格属性
  18181. UE.commands['edittd'] = {
  18182. queryCommandState: function () {
  18183. return getTableItemsByRange(this).table ? 0 : -1
  18184. },
  18185. execCommand: function (cmd, bkColor) {
  18186. var me = this,
  18187. ut = getUETableBySelected(me);
  18188. if (!ut) {
  18189. var start = me.selection.getStart(),
  18190. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18191. if (cell) {
  18192. cell.style.backgroundColor = bkColor;
  18193. }
  18194. } else {
  18195. utils.each(ut.selectedTds, function (cell) {
  18196. cell.style.backgroundColor = bkColor;
  18197. });
  18198. }
  18199. }
  18200. };
  18201. UE.commands["settablebackground"] = {
  18202. queryCommandState: function () {
  18203. return getSelectedArr(this).length > 1 ? 0 : -1;
  18204. },
  18205. execCommand: function (cmd, value) {
  18206. var cells, ut;
  18207. cells = getSelectedArr(this);
  18208. ut = getUETable(cells[0]);
  18209. ut.setBackground(cells, value);
  18210. }
  18211. };
  18212. UE.commands["cleartablebackground"] = {
  18213. queryCommandState: function () {
  18214. var cells = getSelectedArr(this);
  18215. if (!cells.length)return -1;
  18216. for (var i = 0, cell; cell = cells[i++];) {
  18217. if (cell.style.backgroundColor !== "") return 0;
  18218. }
  18219. return -1;
  18220. },
  18221. execCommand: function () {
  18222. var cells = getSelectedArr(this),
  18223. ut = getUETable(cells[0]);
  18224. ut.removeBackground(cells);
  18225. }
  18226. };
  18227. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18228. queryCommandState: function (cmd) {
  18229. var table = getTableItemsByRange(this).table;
  18230. if (!table) return -1;
  18231. var interlaced = table.getAttribute("interlaced");
  18232. if (cmd == "interlacetable") {
  18233. //TODO 待定
  18234. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18235. return (interlaced === "enabled") ? -1 : 0;
  18236. } else {
  18237. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18238. }
  18239. },
  18240. execCommand: function (cmd, classList) {
  18241. var table = getTableItemsByRange(this).table;
  18242. if (cmd == "interlacetable") {
  18243. table.setAttribute("interlaced", "enabled");
  18244. this.fireEvent("interlacetable", table, classList);
  18245. } else {
  18246. table.setAttribute("interlaced", "disabled");
  18247. this.fireEvent("uninterlacetable", table);
  18248. }
  18249. }
  18250. };
  18251. UE.commands["setbordervisible"] = {
  18252. queryCommandState: function (cmd) {
  18253. var table = getTableItemsByRange(this).table;
  18254. if (!table) return -1;
  18255. return 0;
  18256. },
  18257. execCommand: function () {
  18258. var table = getTableItemsByRange(this).table;
  18259. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18260. td.style.borderWidth = '1px';
  18261. td.style.borderStyle = 'solid';
  18262. })
  18263. }
  18264. };
  18265. function resetTdWidth(table, editor) {
  18266. var tds = domUtils.getElementsByTagName(table,'td th');
  18267. utils.each(tds, function (td) {
  18268. td.removeAttribute("width");
  18269. });
  18270. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18271. var tdsWidths = [];
  18272. setTimeout(function () {
  18273. utils.each(tds, function (td) {
  18274. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18275. })
  18276. utils.each(tds, function (td,i) {
  18277. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18278. })
  18279. }, 0);
  18280. }
  18281. function getTableWidth(editor, needIEHack, defaultValue) {
  18282. var body = editor.body;
  18283. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18284. }
  18285. function getSelectedArr(editor) {
  18286. var cell = getTableItemsByRange(editor).cell;
  18287. if (cell) {
  18288. var ut = getUETable(cell);
  18289. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18290. } else {
  18291. return [];
  18292. }
  18293. }
  18294. })();
  18295. // plugins/table.action.js
  18296. /**
  18297. * Created with JetBrains PhpStorm.
  18298. * User: taoqili
  18299. * Date: 12-10-12
  18300. * Time: 上午10:05
  18301. * To change this template use File | Settings | File Templates.
  18302. */
  18303. UE.plugins['table'] = function () {
  18304. var me = this,
  18305. tabTimer = null,
  18306. //拖动计时器
  18307. tableDragTimer = null,
  18308. //双击计时器
  18309. tableResizeTimer = null,
  18310. //单元格最小宽度
  18311. cellMinWidth = 5,
  18312. isInResizeBuffer = false,
  18313. //单元格边框大小
  18314. cellBorderWidth = 5,
  18315. //鼠标偏移距离
  18316. offsetOfTableCell = 10,
  18317. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18318. singleClickState = 0,
  18319. userActionStatus = null,
  18320. //双击允许的时间范围
  18321. dblclickTime = 360,
  18322. UT = UE.UETable,
  18323. getUETable = function (tdOrTable) {
  18324. return UT.getUETable(tdOrTable);
  18325. },
  18326. getUETableBySelected = function (editor) {
  18327. return UT.getUETableBySelected(editor);
  18328. },
  18329. getDefaultValue = function (editor, table) {
  18330. return UT.getDefaultValue(editor, table);
  18331. },
  18332. removeSelectedClass = function (cells) {
  18333. return UT.removeSelectedClass(cells);
  18334. };
  18335. function showError(e) {
  18336. // throw e;
  18337. }
  18338. me.ready(function(){
  18339. var me = this;
  18340. var orgGetText = me.selection.getText;
  18341. me.selection.getText = function(){
  18342. var table = getUETableBySelected(me);
  18343. if(table){
  18344. var str = '';
  18345. utils.each(table.selectedTds,function(td){
  18346. str += td[browser.ie?'innerText':'textContent'];
  18347. })
  18348. return str;
  18349. }else{
  18350. return orgGetText.call(me.selection)
  18351. }
  18352. }
  18353. })
  18354. //处理拖动及框选相关方法
  18355. var startTd = null, //鼠标按下时的锚点td
  18356. currentTd = null, //当前鼠标经过时的td
  18357. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18358. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18359. dragButton = null,
  18360. dragOver = false,
  18361. dragLine = null, //模拟的拖动线
  18362. dragTd = null; //发生拖动的目标td
  18363. var mousedown = false,
  18364. //todo 判断混乱模式
  18365. needIEHack = true;
  18366. me.setOpt({
  18367. 'maxColNum':20,
  18368. 'maxRowNum':100,
  18369. 'defaultCols':5,
  18370. 'defaultRows':5,
  18371. 'tdvalign':'top',
  18372. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18373. 'tableDragable':false,
  18374. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18375. });
  18376. me.getUETable = getUETable;
  18377. var commands = {
  18378. 'deletetable':1,
  18379. 'inserttable':1,
  18380. 'cellvalign':1,
  18381. 'insertcaption':1,
  18382. 'deletecaption':1,
  18383. 'inserttitle':1,
  18384. 'deletetitle':1,
  18385. "mergeright":1,
  18386. "mergedown":1,
  18387. "mergecells":1,
  18388. "insertrow":1,
  18389. "insertrownext":1,
  18390. "deleterow":1,
  18391. "insertcol":1,
  18392. "insertcolnext":1,
  18393. "deletecol":1,
  18394. "splittocells":1,
  18395. "splittorows":1,
  18396. "splittocols":1,
  18397. "adaptbytext":1,
  18398. "adaptbywindow":1,
  18399. "adaptbycustomer":1,
  18400. "insertparagraph":1,
  18401. "insertparagraphbeforetable":1,
  18402. "averagedistributecol":1,
  18403. "averagedistributerow":1
  18404. };
  18405. me.ready(function () {
  18406. utils.cssRule('table',
  18407. //选中的td上的样式
  18408. '.selectTdClass{background-color:#edf5fa !important}' +
  18409. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18410. //插入的表格的默认样式
  18411. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18412. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18413. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18414. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18415. 'table tr.firstRow th{border-top-width:2px;}' +
  18416. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18417. 'td p{margin:0;padding:0;}', me.document);
  18418. var tableCopyList, isFullCol, isFullRow;
  18419. //注册del/backspace事件
  18420. me.addListener('keydown', function (cmd, evt) {
  18421. var me = this;
  18422. var keyCode = evt.keyCode || evt.which;
  18423. if (keyCode == 8) {
  18424. var ut = getUETableBySelected(me);
  18425. if (ut && ut.selectedTds.length) {
  18426. if (ut.isFullCol()) {
  18427. me.execCommand('deletecol')
  18428. } else if (ut.isFullRow()) {
  18429. me.execCommand('deleterow')
  18430. } else {
  18431. me.fireEvent('delcells');
  18432. }
  18433. domUtils.preventDefault(evt);
  18434. }
  18435. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18436. range = me.selection.getRange();
  18437. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18438. me.fireEvent('saveScene');
  18439. var table = caption.parentNode;
  18440. domUtils.remove(caption);
  18441. if (table) {
  18442. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18443. }
  18444. me.fireEvent('saveScene');
  18445. }
  18446. }
  18447. if (keyCode == 46) {
  18448. ut = getUETableBySelected(me);
  18449. if (ut) {
  18450. me.fireEvent('saveScene');
  18451. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18452. domUtils.fillNode(me.document, ci)
  18453. }
  18454. me.fireEvent('saveScene');
  18455. domUtils.preventDefault(evt);
  18456. }
  18457. }
  18458. if (keyCode == 13) {
  18459. var rng = me.selection.getRange(),
  18460. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18461. if (caption) {
  18462. var table = domUtils.findParentByTagName(caption, 'table');
  18463. if (!rng.collapsed) {
  18464. rng.deleteContents();
  18465. me.fireEvent('saveScene');
  18466. } else {
  18467. if (caption) {
  18468. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18469. }
  18470. }
  18471. domUtils.preventDefault(evt);
  18472. return;
  18473. }
  18474. if (rng.collapsed) {
  18475. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18476. if (table) {
  18477. var cell = table.rows[0].cells[0],
  18478. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18479. preNode = table.previousSibling;
  18480. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18481. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18482. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18483. me.execCommand('insertparagraphbeforetable');
  18484. domUtils.preventDefault(evt);
  18485. }
  18486. }
  18487. }
  18488. }
  18489. }
  18490. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18491. tableCopyList = null;
  18492. var ut = getUETableBySelected(me);
  18493. if (ut) {
  18494. var tds = ut.selectedTds;
  18495. isFullCol = ut.isFullCol();
  18496. isFullRow = ut.isFullRow();
  18497. tableCopyList = [
  18498. [ut.cloneCell(tds[0],null,true)]
  18499. ];
  18500. for (var i = 1, ci; ci = tds[i]; i++) {
  18501. if (ci.parentNode !== tds[i - 1].parentNode) {
  18502. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18503. } else {
  18504. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18505. }
  18506. }
  18507. }
  18508. }
  18509. });
  18510. me.addListener("tablehasdeleted",function(){
  18511. toggleDraggableState(this, false, "", null);
  18512. if (dragButton)domUtils.remove(dragButton);
  18513. });
  18514. me.addListener('beforepaste', function (cmd, html) {
  18515. var me = this;
  18516. var rng = me.selection.getRange();
  18517. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18518. var div = me.document.createElement("div");
  18519. div.innerHTML = html.html;
  18520. //trace:3729
  18521. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18522. return;
  18523. }
  18524. var table = getUETableBySelected(me);
  18525. if (tableCopyList) {
  18526. me.fireEvent('saveScene');
  18527. var rng = me.selection.getRange();
  18528. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18529. if (td) {
  18530. var ut = getUETable(td);
  18531. if (isFullRow) {
  18532. var rowIndex = ut.getCellInfo(td).rowIndex;
  18533. if (td.tagName == 'TH') {
  18534. rowIndex++;
  18535. }
  18536. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18537. var tr = ut.insertRow(rowIndex++, "td");
  18538. for (var j = 0, cj; cj = ci[j]; j++) {
  18539. var cell = tr.cells[j];
  18540. if (!cell) {
  18541. cell = tr.insertCell(j)
  18542. }
  18543. cell.innerHTML = cj.innerHTML;
  18544. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18545. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18546. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18547. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18548. }
  18549. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18550. if (!ci[j])
  18551. break;
  18552. cj.innerHTML = ci[j].innerHTML;
  18553. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18554. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18555. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18556. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18557. }
  18558. }
  18559. } else {
  18560. if (isFullCol) {
  18561. cellInfo = ut.getCellInfo(td);
  18562. var maxColNum = 0;
  18563. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18564. maxColNum += cj.colSpan || 1;
  18565. }
  18566. me.__hasEnterExecCommand = true;
  18567. for (i = 0; i < maxColNum; i++) {
  18568. me.execCommand('insertcol');
  18569. }
  18570. me.__hasEnterExecCommand = false;
  18571. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18572. if (td.tagName == 'TH') {
  18573. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18574. }
  18575. }
  18576. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18577. tmpNode = td;
  18578. for (var j = 0, cj; cj = ci[j++];) {
  18579. if (td) {
  18580. td.innerHTML = cj.innerHTML;
  18581. //todo 定制处理
  18582. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18583. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18584. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18585. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18586. preNode = td;
  18587. td = td.nextSibling;
  18588. } else {
  18589. var cloneTd = cj.cloneNode(true);
  18590. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18591. preNode.parentNode.appendChild(cloneTd)
  18592. }
  18593. }
  18594. td = ut.getNextCell(tmpNode, true, true);
  18595. if (!tableCopyList[i])
  18596. break;
  18597. if (!td) {
  18598. var cellInfo = ut.getCellInfo(tmpNode);
  18599. ut.table.insertRow(ut.table.rows.length);
  18600. ut.update();
  18601. td = ut.getVSideCell(tmpNode, true);
  18602. }
  18603. }
  18604. }
  18605. ut.update();
  18606. } else {
  18607. table = me.document.createElement('table');
  18608. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18609. var tr = table.insertRow(table.rows.length);
  18610. for (var j = 0, cj; cj = ci[j++];) {
  18611. cloneTd = UT.cloneCell(cj,null,true);
  18612. domUtils.removeAttributes(cloneTd, ['class']);
  18613. tr.appendChild(cloneTd)
  18614. }
  18615. if (j == 2 && cloneTd.rowSpan > 1) {
  18616. cloneTd.rowSpan = 1;
  18617. }
  18618. }
  18619. var defaultValue = getDefaultValue(me),
  18620. width = me.body.offsetWidth -
  18621. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18622. me.execCommand('insertHTML', '<table ' +
  18623. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18624. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18625. }
  18626. me.fireEvent('contentchange');
  18627. me.fireEvent('saveScene');
  18628. html.html = '';
  18629. return true;
  18630. } else {
  18631. var div = me.document.createElement("div"), tables;
  18632. div.innerHTML = html.html;
  18633. tables = div.getElementsByTagName("table");
  18634. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18635. utils.each(tables, function (t) {
  18636. domUtils.remove(t)
  18637. });
  18638. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18639. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18640. }
  18641. } else {
  18642. utils.each(tables, function (table) {
  18643. removeStyleSize(table, true);
  18644. domUtils.removeAttributes(table, ['style', 'border']);
  18645. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18646. if (isEmptyBlock(td)) {
  18647. domUtils.fillNode(me.document, td);
  18648. }
  18649. removeStyleSize(td, true);
  18650. // domUtils.removeAttributes(td, ['style'])
  18651. });
  18652. });
  18653. }
  18654. html.html = div.innerHTML;
  18655. }
  18656. });
  18657. me.addListener('afterpaste', function () {
  18658. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18659. if (table.offsetWidth > me.body.offsetWidth) {
  18660. var defaultValue = getDefaultValue(me, table);
  18661. 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'
  18662. }
  18663. })
  18664. });
  18665. me.addListener('blur', function () {
  18666. tableCopyList = null;
  18667. });
  18668. var timer;
  18669. me.addListener('keydown', function () {
  18670. clearTimeout(timer);
  18671. timer = setTimeout(function () {
  18672. var rng = me.selection.getRange(),
  18673. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18674. if (cell) {
  18675. var table = cell.parentNode.parentNode.parentNode;
  18676. if (table.offsetWidth > table.getAttribute("width")) {
  18677. cell.style.wordBreak = "break-all";
  18678. }
  18679. }
  18680. }, 100);
  18681. });
  18682. me.addListener("selectionchange", function () {
  18683. toggleDraggableState(me, false, "", null);
  18684. });
  18685. //内容变化时触发索引更新
  18686. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18687. me.addListener("contentchange", function () {
  18688. var me = this;
  18689. //尽可能排除一些不需要更新的状况
  18690. hideDragLine(me);
  18691. if (getUETableBySelected(me))return;
  18692. var rng = me.selection.getRange();
  18693. var start = rng.startContainer;
  18694. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18695. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18696. if (me.fireEvent("excludetable", table) === true) return;
  18697. table.ueTable = new UT(table);
  18698. //trace:3742
  18699. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18700. //
  18701. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18702. // domUtils.fillNode(me.document, td);
  18703. // if (browser.ie && browser.version == 6) {
  18704. // td.innerHTML = '&nbsp;'
  18705. // }
  18706. // }
  18707. // });
  18708. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18709. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18710. // domUtils.fillNode(me.document, th);
  18711. // if (browser.ie && browser.version == 6) {
  18712. // th.innerHTML = '&nbsp;'
  18713. // }
  18714. // }
  18715. // });
  18716. table.onmouseover = function () {
  18717. me.fireEvent('tablemouseover', table);
  18718. };
  18719. table.onmousemove = function () {
  18720. me.fireEvent('tablemousemove', table);
  18721. me.options.tableDragable && toggleDragButton(true, this, me);
  18722. utils.defer(function(){
  18723. me.fireEvent('contentchange',50)
  18724. },true)
  18725. };
  18726. table.onmouseout = function () {
  18727. me.fireEvent('tablemouseout', table);
  18728. toggleDraggableState(me, false, "", null);
  18729. hideDragLine(me);
  18730. };
  18731. table.onclick = function (evt) {
  18732. evt = me.window.event || evt;
  18733. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18734. if (!target)return;
  18735. var ut = getUETable(target),
  18736. table = ut.table,
  18737. cellInfo = ut.getCellInfo(target),
  18738. cellsRange,
  18739. rng = me.selection.getRange();
  18740. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18741. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18742. // ut.setSelected(cellsRange);
  18743. // return;
  18744. // }
  18745. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18746. //
  18747. // return;
  18748. // }
  18749. if (inTableSide(table, target, evt, true)) {
  18750. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18751. if (evt.shiftKey && ut.selectedTds.length) {
  18752. if (ut.selectedTds[0] !== endTdCol) {
  18753. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18754. ut.setSelected(cellsRange);
  18755. } else {
  18756. rng && rng.selectNodeContents(endTdCol).select();
  18757. }
  18758. } else {
  18759. if (target !== endTdCol) {
  18760. cellsRange = ut.getCellsRange(target, endTdCol);
  18761. ut.setSelected(cellsRange);
  18762. } else {
  18763. rng && rng.selectNodeContents(endTdCol).select();
  18764. }
  18765. }
  18766. return;
  18767. }
  18768. if (inTableSide(table, target, evt)) {
  18769. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18770. if (evt.shiftKey && ut.selectedTds.length) {
  18771. if (ut.selectedTds[0] !== endTdRow) {
  18772. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18773. ut.setSelected(cellsRange);
  18774. } else {
  18775. rng && rng.selectNodeContents(endTdRow).select();
  18776. }
  18777. } else {
  18778. if (target !== endTdRow) {
  18779. cellsRange = ut.getCellsRange(target, endTdRow);
  18780. ut.setSelected(cellsRange);
  18781. } else {
  18782. rng && rng.selectNodeContents(endTdRow).select();
  18783. }
  18784. }
  18785. }
  18786. };
  18787. });
  18788. switchBorderColor(me, true);
  18789. });
  18790. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18791. domUtils.on(me.document, "mouseout", function (evt) {
  18792. var target = evt.target || evt.srcElement;
  18793. if (target.tagName == "TABLE") {
  18794. toggleDraggableState(me, false, "", null);
  18795. }
  18796. });
  18797. /**
  18798. * 表格隔行变色
  18799. */
  18800. me.addListener("interlacetable",function(type,table,classList){
  18801. if(!table) return;
  18802. var me = this,
  18803. rows = table.rows,
  18804. len = rows.length,
  18805. getClass = function(list,index,repeat){
  18806. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18807. };
  18808. for(var i = 0;i<len;i++){
  18809. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18810. }
  18811. });
  18812. me.addListener("uninterlacetable",function(type,table){
  18813. if(!table) return;
  18814. var me = this,
  18815. rows = table.rows,
  18816. classList = me.options.classList,
  18817. len = rows.length;
  18818. for(var i = 0;i<len;i++){
  18819. domUtils.removeClasses( rows[i], classList );
  18820. }
  18821. });
  18822. me.addListener("mousedown", mouseDownEvent);
  18823. me.addListener("mouseup", mouseUpEvent);
  18824. //拖动的时候触发mouseup
  18825. domUtils.on( me.body, 'dragstart', function( evt ){
  18826. mouseUpEvent.call( me, 'dragstart', evt );
  18827. });
  18828. me.addOutputRule(function(root){
  18829. utils.each(root.getNodesByTagName('div'),function(n){
  18830. if (n.getAttr('id') == 'ue_tableDragLine') {
  18831. n.parentNode.removeChild(n);
  18832. }
  18833. });
  18834. });
  18835. var currentRowIndex = 0;
  18836. me.addListener("mousedown", function () {
  18837. currentRowIndex = 0;
  18838. });
  18839. me.addListener('tabkeydown', function () {
  18840. var range = this.selection.getRange(),
  18841. common = range.getCommonAncestor(true, true),
  18842. table = domUtils.findParentByTagName(common, 'table');
  18843. if (table) {
  18844. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18845. var cell = domUtils.getElementsByTagName(table, 'th td');
  18846. if (cell && cell.length) {
  18847. range.setStart(cell[0], 0).setCursor(false, true)
  18848. }
  18849. } else {
  18850. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18851. ua = getUETable(cell);
  18852. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18853. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18854. if (nextCell) {
  18855. if (isEmptyBlock(nextCell)) {
  18856. range.setStart(nextCell, 0).setCursor(false, true)
  18857. } else {
  18858. range.selectNodeContents(nextCell).select()
  18859. }
  18860. } else {
  18861. me.fireEvent('saveScene');
  18862. me.__hasEnterExecCommand = true;
  18863. this.execCommand('insertrownext');
  18864. me.__hasEnterExecCommand = false;
  18865. range = this.selection.getRange();
  18866. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18867. me.fireEvent('saveScene');
  18868. }
  18869. }
  18870. return true;
  18871. }
  18872. });
  18873. browser.ie && me.addListener('selectionchange', function () {
  18874. toggleDraggableState(this, false, "", null);
  18875. });
  18876. me.addListener("keydown", function (type, evt) {
  18877. var me = this;
  18878. //处理在表格的最后一个输入tab产生新的表格
  18879. var keyCode = evt.keyCode || evt.which;
  18880. if (keyCode == 8 || keyCode == 46) {
  18881. return;
  18882. }
  18883. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18884. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18885. var ut = getUETableBySelected(me);
  18886. if (!ut) return;
  18887. notCtrlKey && ut.clearSelected();
  18888. });
  18889. me.addListener("beforegetcontent", function () {
  18890. switchBorderColor(this, false);
  18891. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18892. if (domUtils.isEmptyNode(ci)) {
  18893. ci.innerHTML = '&nbsp;'
  18894. }
  18895. });
  18896. });
  18897. me.addListener("aftergetcontent", function () {
  18898. switchBorderColor(this, true);
  18899. });
  18900. me.addListener("getAllHtml", function () {
  18901. removeSelectedClass(me.document.getElementsByTagName("td"));
  18902. });
  18903. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18904. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18905. if (!fullscreen) {
  18906. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18907. tables = domUtils.getElementsByTagName(this.body, "table");
  18908. utils.each(tables, function (table) {
  18909. if (table.offsetWidth < me.body.offsetWidth) return false;
  18910. var tds = domUtils.getElementsByTagName(table, "td"),
  18911. backWidths = [];
  18912. utils.each(tds, function (td) {
  18913. backWidths.push(td.offsetWidth);
  18914. });
  18915. for (var i = 0, td; td = tds[i]; i++) {
  18916. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18917. }
  18918. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18919. });
  18920. }
  18921. });
  18922. //重写execCommand命令,用于处理框选时的处理
  18923. var oldExecCommand = me.execCommand;
  18924. me.execCommand = function (cmd, datatat) {
  18925. var me = this,
  18926. args = arguments;
  18927. cmd = cmd.toLowerCase();
  18928. var ut = getUETableBySelected(me), tds,
  18929. range = new dom.Range(me.document),
  18930. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18931. result;
  18932. if (!cmdFun) return;
  18933. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18934. me.__hasEnterExecCommand = true;
  18935. me.fireEvent("beforeexeccommand", cmd);
  18936. tds = ut.selectedTds;
  18937. var lastState = -2, lastValue = -2, value, state;
  18938. for (var i = 0, td; td = tds[i]; i++) {
  18939. if (isEmptyBlock(td)) {
  18940. range.setStart(td, 0).setCursor(false, true)
  18941. } else {
  18942. range.selectNode(td).select(true);
  18943. }
  18944. state = me.queryCommandState(cmd);
  18945. value = me.queryCommandValue(cmd);
  18946. if (state != -1) {
  18947. if (lastState !== state || lastValue !== value) {
  18948. me._ignoreContentChange = true;
  18949. result = oldExecCommand.apply(me, arguments);
  18950. me._ignoreContentChange = false;
  18951. }
  18952. lastState = me.queryCommandState(cmd);
  18953. lastValue = me.queryCommandValue(cmd);
  18954. if (domUtils.isEmptyBlock(td)) {
  18955. domUtils.fillNode(me.document, td)
  18956. }
  18957. }
  18958. }
  18959. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  18960. me.fireEvent('contentchange');
  18961. me.fireEvent("afterexeccommand", cmd);
  18962. me.__hasEnterExecCommand = false;
  18963. me._selectionChange();
  18964. } else {
  18965. result = oldExecCommand.apply(me, arguments);
  18966. }
  18967. return result;
  18968. };
  18969. });
  18970. /**
  18971. * 删除obj的宽高style,改成属性宽高
  18972. * @param obj
  18973. * @param replaceToProperty
  18974. */
  18975. function removeStyleSize(obj, replaceToProperty) {
  18976. removeStyle(obj, "width", true);
  18977. removeStyle(obj, "height", true);
  18978. }
  18979. function removeStyle(obj, styleName, replaceToProperty) {
  18980. if (obj.style[styleName]) {
  18981. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  18982. obj.style[styleName] = "";
  18983. }
  18984. }
  18985. function getParentTdOrTh(ele) {
  18986. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  18987. var td;
  18988. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  18989. return null;
  18990. }
  18991. function isEmptyBlock(node) {
  18992. var reg = new RegExp(domUtils.fillChar, 'g');
  18993. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  18994. return 0;
  18995. }
  18996. for (var n in dtd.$isNotEmpty) {
  18997. if (node.getElementsByTagName(n).length) {
  18998. return 0;
  18999. }
  19000. }
  19001. return 1;
  19002. }
  19003. function mouseCoords(evt) {
  19004. if (evt.pageX || evt.pageY) {
  19005. return { x:evt.pageX, y:evt.pageY };
  19006. }
  19007. return {
  19008. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19009. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19010. };
  19011. }
  19012. function mouseMoveEvent(evt) {
  19013. if( isEditorDisabled() ) {
  19014. return;
  19015. }
  19016. try {
  19017. //普通状态下鼠标移动
  19018. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19019. pos;
  19020. //区分用户的行为是拖动还是双击
  19021. if( isInResizeBuffer ) {
  19022. me.body.style.webkitUserSelect = 'none';
  19023. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19024. clearTableDragTimer();
  19025. isInResizeBuffer = false;
  19026. singleClickState = 0;
  19027. //drag action
  19028. tableBorderDrag(evt);
  19029. }
  19030. }
  19031. //修改单元格大小时的鼠标移动
  19032. if (onDrag && dragTd) {
  19033. singleClickState = 0;
  19034. me.body.style.webkitUserSelect = 'none';
  19035. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19036. pos = mouseCoords(evt);
  19037. toggleDraggableState(me, true, onDrag, pos, target);
  19038. if (onDrag == "h") {
  19039. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19040. } else if (onDrag == "v") {
  19041. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19042. }
  19043. return;
  19044. }
  19045. //当鼠标处于table上时,修改移动过程中的光标状态
  19046. if (target) {
  19047. //针对使用table作为容器的组件不触发拖拽效果
  19048. if (me.fireEvent('excludetable', target) === true)
  19049. return;
  19050. pos = mouseCoords(evt);
  19051. var state = getRelation(target, pos),
  19052. table = domUtils.findParentByTagName(target, "table", true);
  19053. if (inTableSide(table, target, evt, true)) {
  19054. if (me.fireEvent("excludetable", table) === true) return;
  19055. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19056. } else if (inTableSide(table, target, evt)) {
  19057. if (me.fireEvent("excludetable", table) === true) return;
  19058. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19059. } else {
  19060. me.body.style.cursor = "text";
  19061. var curCell = target;
  19062. if (/\d/.test(state)) {
  19063. state = state.replace(/\d/, '');
  19064. target = getUETable(target).getPreviewCell(target, state == "v");
  19065. }
  19066. //位于第一行的顶部或者第一列的左边时不可拖动
  19067. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19068. }
  19069. } else {
  19070. toggleDragButton(false, table, me);
  19071. }
  19072. } catch (e) {
  19073. showError(e);
  19074. }
  19075. }
  19076. var dragButtonTimer;
  19077. function toggleDragButton(show, table, editor) {
  19078. if (!show) {
  19079. if (dragOver)return;
  19080. dragButtonTimer = setTimeout(function () {
  19081. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19082. }, 2000);
  19083. } else {
  19084. createDragButton(table, editor);
  19085. }
  19086. }
  19087. function createDragButton(table, editor) {
  19088. var pos = domUtils.getXY(table),
  19089. doc = table.ownerDocument;
  19090. if (dragButton && dragButton.parentNode)return dragButton;
  19091. dragButton = doc.createElement("div");
  19092. dragButton.contentEditable = false;
  19093. dragButton.innerHTML = "";
  19094. 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;";
  19095. domUtils.unSelectable(dragButton);
  19096. dragButton.onmouseover = function (evt) {
  19097. dragOver = true;
  19098. };
  19099. dragButton.onmouseout = function (evt) {
  19100. dragOver = false;
  19101. };
  19102. domUtils.on(dragButton, 'click', function (type, evt) {
  19103. doClick(evt, this);
  19104. });
  19105. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19106. doDblClick(evt);
  19107. });
  19108. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19109. domUtils.preventDefault(evt);
  19110. });
  19111. var timer;
  19112. function doClick(evt, button) {
  19113. // 部分浏览器下需要清理
  19114. clearTimeout(timer);
  19115. timer = setTimeout(function () {
  19116. editor.fireEvent("tableClicked", table, button);
  19117. }, 300);
  19118. }
  19119. function doDblClick(evt) {
  19120. clearTimeout(timer);
  19121. var ut = getUETable(table),
  19122. start = table.rows[0].cells[0],
  19123. end = ut.getLastCell(),
  19124. range = ut.getCellsRange(start, end);
  19125. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19126. ut.setSelected(range);
  19127. }
  19128. doc.body.appendChild(dragButton);
  19129. }
  19130. // function inPosition(table, pos) {
  19131. // var tablePos = domUtils.getXY(table),
  19132. // width = table.offsetWidth,
  19133. // height = table.offsetHeight;
  19134. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19135. // return "topLeft";
  19136. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19137. // return "bottomRight";
  19138. // }
  19139. // }
  19140. function inTableSide(table, cell, evt, top) {
  19141. var pos = mouseCoords(evt),
  19142. state = getRelation(cell, pos);
  19143. if (top) {
  19144. var caption = table.getElementsByTagName("caption")[0],
  19145. capHeight = caption ? caption.offsetHeight : 0;
  19146. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19147. } else {
  19148. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19149. }
  19150. }
  19151. /**
  19152. * 获取拖动时允许的X轴坐标
  19153. * @param dragTd
  19154. * @param evt
  19155. */
  19156. function getPermissionX(dragTd, evt) {
  19157. var ut = getUETable(dragTd);
  19158. if (ut) {
  19159. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19160. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19161. mouseX = mouseCoords(evt).x,
  19162. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19163. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19164. left += cellMinWidth;
  19165. right -= cellMinWidth;
  19166. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19167. }
  19168. }
  19169. /**
  19170. * 获取拖动时允许的Y轴坐标
  19171. */
  19172. function getPermissionY(dragTd, evt) {
  19173. try {
  19174. var top = domUtils.getXY(dragTd).y,
  19175. mousePosY = mouseCoords(evt).y;
  19176. return mousePosY < top ? top : mousePosY;
  19177. } catch (e) {
  19178. showError(e);
  19179. }
  19180. }
  19181. /**
  19182. * 移动状态切换
  19183. */
  19184. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19185. try {
  19186. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19187. if (browser.ie) {
  19188. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19189. getDragLine(editor, editor.document);
  19190. showDragLineAt(dir, cell);
  19191. } else {
  19192. hideDragLine(editor)
  19193. }
  19194. }
  19195. onBorder = draggable;
  19196. } catch (e) {
  19197. showError(e);
  19198. }
  19199. }
  19200. /**
  19201. * 获取与UETable相关的resize line
  19202. * @param uetable UETable对象
  19203. */
  19204. function getResizeLineByUETable() {
  19205. var lineId = '_UETableResizeLine',
  19206. line = this.document.getElementById( lineId );
  19207. if( !line ) {
  19208. line = this.document.createElement("div");
  19209. line.id = lineId;
  19210. line.contnetEditable = false;
  19211. line.setAttribute("unselectable", "on");
  19212. var styles = {
  19213. width: 2*cellBorderWidth + 1 + 'px',
  19214. position: 'absolute',
  19215. 'z-index': 100000,
  19216. cursor: 'col-resize',
  19217. background: 'red',
  19218. display: 'none'
  19219. };
  19220. //切换状态
  19221. line.onmouseout = function(){
  19222. this.style.display = 'none';
  19223. };
  19224. utils.extend( line.style, styles );
  19225. this.document.body.appendChild( line );
  19226. }
  19227. return line;
  19228. }
  19229. /**
  19230. * 更新resize-line
  19231. */
  19232. function updateResizeLine( cell, uetable ) {
  19233. var line = getResizeLineByUETable.call( this ),
  19234. table = uetable.table,
  19235. styles = {
  19236. top: domUtils.getXY( table ).y + 'px',
  19237. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19238. display: 'block',
  19239. height: table.offsetHeight + 'px'
  19240. };
  19241. utils.extend( line.style, styles );
  19242. }
  19243. /**
  19244. * 显示resize-line
  19245. */
  19246. function showResizeLine( cell ) {
  19247. var uetable = getUETable( cell );
  19248. updateResizeLine.call( this, cell, uetable );
  19249. }
  19250. /**
  19251. * 获取鼠标与当前单元格的相对位置
  19252. * @param ele
  19253. * @param mousePos
  19254. */
  19255. function getRelation(ele, mousePos) {
  19256. var elePos = domUtils.getXY(ele);
  19257. if( !elePos ) {
  19258. return '';
  19259. }
  19260. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19261. return "h";
  19262. }
  19263. if (mousePos.x - elePos.x < cellBorderWidth) {
  19264. return 'h1'
  19265. }
  19266. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19267. return "v";
  19268. }
  19269. if (mousePos.y - elePos.y < cellBorderWidth) {
  19270. return 'v1'
  19271. }
  19272. return '';
  19273. }
  19274. function mouseDownEvent(type, evt) {
  19275. if( isEditorDisabled() ) {
  19276. return ;
  19277. }
  19278. userActionStatus = {
  19279. x: evt.clientX,
  19280. y: evt.clientY
  19281. };
  19282. //右键菜单单独处理
  19283. if (evt.button == 2) {
  19284. var ut = getUETableBySelected(me),
  19285. flag = false;
  19286. if (ut) {
  19287. var td = getTargetTd(me, evt);
  19288. utils.each(ut.selectedTds, function (ti) {
  19289. if (ti === td) {
  19290. flag = true;
  19291. }
  19292. });
  19293. if (!flag) {
  19294. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19295. ut.clearSelected()
  19296. } else {
  19297. td = ut.selectedTds[0];
  19298. setTimeout(function () {
  19299. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19300. }, 0);
  19301. }
  19302. }
  19303. } else {
  19304. tableClickHander( evt );
  19305. }
  19306. }
  19307. //清除表格的计时器
  19308. function clearTableTimer() {
  19309. tabTimer && clearTimeout( tabTimer );
  19310. tabTimer = null;
  19311. }
  19312. //双击收缩
  19313. function tableDbclickHandler(evt) {
  19314. singleClickState = 0;
  19315. evt = evt || me.window.event;
  19316. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19317. if (target) {
  19318. var h;
  19319. if (h = getRelation(target, mouseCoords(evt))) {
  19320. hideDragLine( me );
  19321. if (h == 'h1') {
  19322. h = 'h';
  19323. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19324. me.execCommand('adaptbywindow');
  19325. } else {
  19326. target = getUETable(target).getPreviewCell(target);
  19327. if (target) {
  19328. var rng = me.selection.getRange();
  19329. rng.selectNodeContents(target).setCursor(true, true)
  19330. }
  19331. }
  19332. }
  19333. if (h == 'h') {
  19334. var ut = getUETable(target),
  19335. table = ut.table,
  19336. cells = getCellsByMoveBorder( target, table, true );
  19337. cells = extractArray( cells, 'left' );
  19338. ut.width = ut.offsetWidth;
  19339. var oldWidth = [],
  19340. newWidth = [];
  19341. utils.each( cells, function( cell ){
  19342. oldWidth.push( cell.offsetWidth );
  19343. } );
  19344. utils.each( cells, function( cell ){
  19345. cell.removeAttribute("width");
  19346. } );
  19347. window.setTimeout( function(){
  19348. //是否允许改变
  19349. var changeable = true;
  19350. utils.each( cells, function( cell, index ){
  19351. var width = cell.offsetWidth;
  19352. if( width > oldWidth[index] ) {
  19353. changeable = false;
  19354. return false;
  19355. }
  19356. newWidth.push( width );
  19357. } );
  19358. var change = changeable ? newWidth : oldWidth;
  19359. utils.each( cells, function( cell, index ){
  19360. cell.width = change[index] - getTabcellSpace();
  19361. } );
  19362. }, 0 );
  19363. // minWidth -= cellMinWidth;
  19364. //
  19365. // table.removeAttribute("width");
  19366. // utils.each(cells, function (cell) {
  19367. // cell.style.width = "";
  19368. // cell.width -= minWidth;
  19369. // });
  19370. }
  19371. }
  19372. }
  19373. }
  19374. function tableClickHander( evt ) {
  19375. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19376. //trace:3113
  19377. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19378. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19379. t.ueTable = null;
  19380. });
  19381. startTd = getTargetTd(me, evt);
  19382. if( !startTd ) return;
  19383. var table = domUtils.findParentByTagName(startTd, "table", true);
  19384. ut = getUETable(table);
  19385. ut && ut.clearSelected();
  19386. //判断当前鼠标状态
  19387. if (!onBorder) {
  19388. me.document.body.style.webkitUserSelect = '';
  19389. mousedown = true;
  19390. me.addListener('mouseover', mouseOverEvent);
  19391. } else {
  19392. //边框上的动作处理
  19393. borderActionHandler( evt );
  19394. }
  19395. }
  19396. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19397. function borderActionHandler( evt ) {
  19398. if ( browser.ie ) {
  19399. evt = reconstruct(evt );
  19400. }
  19401. clearTableDragTimer();
  19402. //是否正在等待resize的缓冲中
  19403. isInResizeBuffer = true;
  19404. tableDragTimer = setTimeout(function(){
  19405. tableBorderDrag( evt );
  19406. }, dblclickTime);
  19407. }
  19408. function extractArray( originArr, key ) {
  19409. var result = [],
  19410. tmp = null;
  19411. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19412. tmp = originArr[ i ][ key ];
  19413. if( tmp ) {
  19414. result.push( tmp );
  19415. }
  19416. }
  19417. return result;
  19418. }
  19419. function clearTableDragTimer() {
  19420. tableDragTimer && clearTimeout(tableDragTimer);
  19421. tableDragTimer = null;
  19422. }
  19423. function reconstruct( obj ) {
  19424. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19425. newObj = {};
  19426. if( obj ) {
  19427. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19428. val=obj[ key ];
  19429. val && (newObj[ key ] = val);
  19430. }
  19431. }
  19432. return newObj;
  19433. }
  19434. //边框拖动
  19435. function tableBorderDrag( evt ) {
  19436. isInResizeBuffer = false;
  19437. startTd = evt.target || evt.srcElement;
  19438. if( !startTd ) return;
  19439. var state = getRelation(startTd, mouseCoords(evt));
  19440. if (/\d/.test(state)) {
  19441. state = state.replace(/\d/, '');
  19442. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19443. }
  19444. hideDragLine(me);
  19445. getDragLine(me, me.document);
  19446. me.fireEvent('saveScene');
  19447. showDragLineAt(state, startTd);
  19448. mousedown = true;
  19449. //拖动开始
  19450. onDrag = state;
  19451. dragTd = startTd;
  19452. }
  19453. function mouseUpEvent(type, evt) {
  19454. if( isEditorDisabled() ) {
  19455. return ;
  19456. }
  19457. clearTableDragTimer();
  19458. isInResizeBuffer = false;
  19459. if( onBorder ) {
  19460. singleClickState = ++singleClickState % 3;
  19461. userActionStatus = {
  19462. x: evt.clientX,
  19463. y: evt.clientY
  19464. };
  19465. tableResizeTimer = setTimeout(function(){
  19466. singleClickState > 0 && singleClickState--;
  19467. }, dblclickTime );
  19468. if( singleClickState === 2 ) {
  19469. singleClickState = 0;
  19470. tableDbclickHandler(evt);
  19471. return;
  19472. }
  19473. }
  19474. if (evt.button == 2)return;
  19475. var me = this;
  19476. //清除表格上原生跨选问题
  19477. var range = me.selection.getRange(),
  19478. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19479. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19480. if (start || end) {
  19481. if (start === end) {
  19482. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19483. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19484. if (start !== end) {
  19485. me.selection.clearRange()
  19486. }
  19487. } else {
  19488. me.selection.clearRange()
  19489. }
  19490. }
  19491. mousedown = false;
  19492. me.document.body.style.webkitUserSelect = '';
  19493. //拖拽状态下的mouseUP
  19494. if ( onDrag && dragTd ) {
  19495. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19496. singleClickState = 0;
  19497. dragLine = me.document.getElementById('ue_tableDragLine');
  19498. // trace 3973
  19499. if (dragLine) {
  19500. var dragTdPos = domUtils.getXY(dragTd),
  19501. dragLinePos = domUtils.getXY(dragLine);
  19502. switch (onDrag) {
  19503. case "h":
  19504. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19505. break;
  19506. case "v":
  19507. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19508. break;
  19509. default:
  19510. }
  19511. onDrag = "";
  19512. dragTd = null;
  19513. hideDragLine(me);
  19514. me.fireEvent('saveScene');
  19515. return;
  19516. }
  19517. }
  19518. //正常状态下的mouseup
  19519. if (!startTd) {
  19520. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19521. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19522. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19523. if (me.fireEvent("excludetable", target) === true) return;
  19524. range = new dom.Range(me.document);
  19525. range.setStart(target, 0).setCursor(false, true);
  19526. }
  19527. } else {
  19528. var ut = getUETable(startTd),
  19529. cell = ut ? ut.selectedTds[0] : null;
  19530. if (cell) {
  19531. range = new dom.Range(me.document);
  19532. if (domUtils.isEmptyBlock(cell)) {
  19533. range.setStart(cell, 0).setCursor(false, true);
  19534. } else {
  19535. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19536. }
  19537. } else {
  19538. range = me.selection.getRange().shrinkBoundary();
  19539. if (!range.collapsed) {
  19540. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19541. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19542. //在table里边的不能清除
  19543. if (start && !end || !start && end || start && end && start !== end) {
  19544. range.setCursor(false, true);
  19545. }
  19546. }
  19547. }
  19548. startTd = null;
  19549. me.removeListener('mouseover', mouseOverEvent);
  19550. }
  19551. me._selectionChange(250, evt);
  19552. }
  19553. function mouseOverEvent(type, evt) {
  19554. if( isEditorDisabled() ) {
  19555. return;
  19556. }
  19557. var me = this,
  19558. tar = evt.target || evt.srcElement;
  19559. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19560. //需要判断两个TD是否位于同一个表格内
  19561. if (startTd && currentTd &&
  19562. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19563. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19564. var ut = getUETable(currentTd);
  19565. if (startTd != currentTd) {
  19566. me.document.body.style.webkitUserSelect = 'none';
  19567. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19568. var range = ut.getCellsRange(startTd, currentTd);
  19569. ut.setSelected(range);
  19570. } else {
  19571. me.document.body.style.webkitUserSelect = '';
  19572. ut.clearSelected();
  19573. }
  19574. }
  19575. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19576. }
  19577. function setCellHeight(cell, height, backHeight) {
  19578. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19579. tmpHeight = backHeight + height;
  19580. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19581. if (cell.style.height) cell.style.height = "";
  19582. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19583. }
  19584. function getWidth(cell) {
  19585. if (!cell)return 0;
  19586. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19587. }
  19588. function changeColWidth(cell, changeValue) {
  19589. var ut = getUETable(cell);
  19590. if (ut) {
  19591. //根据当前移动的边框获取相关的单元格
  19592. var table = ut.table,
  19593. cells = getCellsByMoveBorder( cell, table );
  19594. table.style.width = "";
  19595. table.removeAttribute("width");
  19596. //修正改变量
  19597. changeValue = correctChangeValue( changeValue, cell, cells );
  19598. if (cell.nextSibling) {
  19599. var i=0;
  19600. utils.each( cells, function( cellGroup ){
  19601. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19602. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19603. } );
  19604. } else {
  19605. utils.each( cells, function( cellGroup ){
  19606. cellGroup.left.width -= -changeValue;
  19607. } );
  19608. }
  19609. }
  19610. }
  19611. function isEditorDisabled() {
  19612. return me.body.contentEditable === "false";
  19613. }
  19614. function changeRowHeight(td, changeValue) {
  19615. if (Math.abs(changeValue) < 10) return;
  19616. var ut = getUETable(td);
  19617. if (ut) {
  19618. var cells = ut.getSameEndPosCells(td, "y"),
  19619. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19620. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19621. for (var i = 0, cell; cell = cells[i++];) {
  19622. setCellHeight(cell, changeValue, backHeight);
  19623. }
  19624. }
  19625. }
  19626. /**
  19627. * 获取调整单元格大小的相关单元格
  19628. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19629. */
  19630. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19631. if( !table ) {
  19632. table = domUtils.findParentByTagName( cell, 'table' );
  19633. }
  19634. if( !table ) {
  19635. return null;
  19636. }
  19637. //获取到该单元格所在行的序列号
  19638. var index = domUtils.getNodeIndex( cell ),
  19639. temp = cell,
  19640. rows = table.rows,
  19641. colIndex = 0;
  19642. while( temp ) {
  19643. //获取到当前单元格在未发生单元格合并时的序列
  19644. if( temp.nodeType === 1 ) {
  19645. colIndex += (temp.colSpan || 1);
  19646. }
  19647. temp = temp.previousSibling;
  19648. }
  19649. temp = null;
  19650. //记录想关的单元格
  19651. var borderCells = [];
  19652. utils.each(rows, function( tabRow ){
  19653. var cells = tabRow.cells,
  19654. currIndex = 0;
  19655. utils.each( cells, function( tabCell ){
  19656. currIndex += (tabCell.colSpan || 1);
  19657. if( currIndex === colIndex ) {
  19658. borderCells.push({
  19659. left: tabCell,
  19660. right: tabCell.nextSibling || null
  19661. });
  19662. return false;
  19663. } else if( currIndex > colIndex ) {
  19664. if( isContainMergeCell ) {
  19665. borderCells.push({
  19666. left: tabCell
  19667. });
  19668. }
  19669. return false;
  19670. }
  19671. } );
  19672. });
  19673. return borderCells;
  19674. }
  19675. /**
  19676. * 通过给定的单元格集合获取最小的单元格width
  19677. */
  19678. function getMinWidthByTableCells( cells ) {
  19679. var minWidth = Number.MAX_VALUE;
  19680. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19681. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19682. }
  19683. return minWidth;
  19684. }
  19685. function correctChangeValue( changeValue, relatedCell, cells ) {
  19686. //为单元格的paading预留空间
  19687. changeValue -= getTabcellSpace();
  19688. if( changeValue < 0 ) {
  19689. return 0;
  19690. }
  19691. changeValue -= getTableCellWidth( relatedCell );
  19692. //确定方向
  19693. var direction = changeValue < 0 ? 'left':'right';
  19694. changeValue = Math.abs(changeValue);
  19695. //只关心非最后一个单元格就可以
  19696. utils.each( cells, function( cellGroup ){
  19697. var curCell = cellGroup[direction];
  19698. //为单元格保留最小空间
  19699. if( curCell ) {
  19700. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19701. }
  19702. } );
  19703. //修正越界
  19704. changeValue = changeValue < 0 ? 0 : changeValue;
  19705. return direction === 'left' ? -changeValue : changeValue;
  19706. }
  19707. function getTableCellWidth( cell ) {
  19708. var width = 0,
  19709. //偏移纠正量
  19710. offset = 0,
  19711. width = cell.offsetWidth - getTabcellSpace();
  19712. //最后一个节点纠正一下
  19713. if( !cell.nextSibling ) {
  19714. width -= getTableCellOffset( cell );
  19715. }
  19716. width = width < 0 ? 0 : width;
  19717. try {
  19718. cell.width = width;
  19719. } catch(e) {
  19720. }
  19721. return width;
  19722. }
  19723. /**
  19724. * 获取单元格所在表格的最末单元格的偏移量
  19725. */
  19726. function getTableCellOffset( cell ) {
  19727. tab = domUtils.findParentByTagName( cell, "table", false);
  19728. if( tab.offsetVal === undefined ) {
  19729. var prev = cell.previousSibling;
  19730. if( prev ) {
  19731. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19732. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19733. } else {
  19734. tab.offsetVal = 0;
  19735. }
  19736. }
  19737. return tab.offsetVal;
  19738. }
  19739. function getTabcellSpace() {
  19740. if( UT.tabcellSpace === undefined ) {
  19741. var cell = null,
  19742. tab = me.document.createElement("table"),
  19743. tbody = me.document.createElement("tbody"),
  19744. trow = me.document.createElement("tr"),
  19745. tabcell = me.document.createElement("td"),
  19746. mirror = null;
  19747. tabcell.style.cssText = 'border: 0;';
  19748. tabcell.width = 1;
  19749. trow.appendChild( tabcell );
  19750. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19751. tbody.appendChild( trow );
  19752. tab.appendChild( tbody );
  19753. tab.style.cssText = "visibility: hidden;";
  19754. me.body.appendChild( tab );
  19755. UT.paddingSpace = tabcell.offsetWidth - 1;
  19756. var tmpTabWidth = tab.offsetWidth;
  19757. tabcell.style.cssText = '';
  19758. mirror.style.cssText = '';
  19759. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19760. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19761. me.body.removeChild( tab );
  19762. }
  19763. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19764. return UT.tabcellSpace;
  19765. }
  19766. function getDragLine(editor, doc) {
  19767. if (mousedown)return;
  19768. dragLine = editor.document.createElement("div");
  19769. domUtils.setAttributes(dragLine, {
  19770. id:"ue_tableDragLine",
  19771. unselectable:'on',
  19772. contenteditable:false,
  19773. 'onresizestart':'return false',
  19774. 'ondragstart':'return false',
  19775. 'onselectstart':'return false',
  19776. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19777. });
  19778. editor.body.appendChild(dragLine);
  19779. }
  19780. function hideDragLine(editor) {
  19781. if (mousedown)return;
  19782. var line;
  19783. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19784. domUtils.remove(line)
  19785. }
  19786. }
  19787. /**
  19788. * 依据state(v|h)在cell位置显示横线
  19789. * @param state
  19790. * @param cell
  19791. */
  19792. function showDragLineAt(state, cell) {
  19793. if (!cell) return;
  19794. var table = domUtils.findParentByTagName(cell, "table"),
  19795. caption = table.getElementsByTagName('caption'),
  19796. width = table.offsetWidth,
  19797. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19798. tablePos = domUtils.getXY(table),
  19799. cellPos = domUtils.getXY(cell), css;
  19800. switch (state) {
  19801. case "h":
  19802. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19803. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19804. break;
  19805. case "v":
  19806. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19807. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19808. 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)';
  19809. break;
  19810. default:
  19811. }
  19812. }
  19813. /**
  19814. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19815. * @param editor
  19816. * @param flag
  19817. */
  19818. function switchBorderColor(editor, flag) {
  19819. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19820. for (var i = 0, node; node = tableArr[i++];) {
  19821. var td = domUtils.getElementsByTagName(node, "td");
  19822. if (td[0]) {
  19823. if (flag) {
  19824. color = (td[0].style.borderColor).replace(/\s/g, "");
  19825. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19826. domUtils.addClass(node, "noBorderTable")
  19827. } else {
  19828. domUtils.removeClasses(node, "noBorderTable")
  19829. }
  19830. }
  19831. }
  19832. }
  19833. function getTableWidth(editor, needIEHack, defaultValue) {
  19834. var body = editor.body;
  19835. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19836. }
  19837. /**
  19838. * 获取当前拖动的单元格
  19839. */
  19840. function getTargetTd(editor, evt) {
  19841. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19842. dir = null;
  19843. if( !target ) {
  19844. return null;
  19845. }
  19846. dir = getRelation( target, mouseCoords( evt ) );
  19847. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19848. if( !target ) {
  19849. return null;
  19850. }
  19851. if( dir === 'h1' && target.previousSibling ) {
  19852. var position = domUtils.getXY( target),
  19853. cellWidth = target.offsetWidth;
  19854. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19855. target = target.previousSibling;
  19856. }
  19857. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19858. var position = domUtils.getXY( target),
  19859. cellHeight = target.offsetHeight;
  19860. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19861. target = target.parentNode.previousSibling.firstChild;
  19862. }
  19863. }
  19864. //排除了非td内部以及用于代码高亮部分的td
  19865. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19866. }
  19867. };
  19868. // plugins/table.sort.js
  19869. /**
  19870. * Created with JetBrains PhpStorm.
  19871. * User: Jinqn
  19872. * Date: 13-10-12
  19873. * Time: 上午10:20
  19874. * To change this template use File | Settings | File Templates.
  19875. */
  19876. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19877. var table = this.table,
  19878. rows = table.rows,
  19879. trArray = [],
  19880. flag = rows[0].cells[0].tagName === "TH",
  19881. lastRowIndex = 0;
  19882. if(this.selectedTds.length){
  19883. var range = this.cellsRange,
  19884. len = range.endRowIndex + 1;
  19885. for (var i = range.beginRowIndex; i < len; i++) {
  19886. trArray[i] = rows[i];
  19887. }
  19888. trArray.splice(0,range.beginRowIndex);
  19889. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19890. }else{
  19891. for (var i = 0,len = rows.length; i < len; i++) {
  19892. trArray[i] = rows[i];
  19893. }
  19894. }
  19895. var Fn = {
  19896. 'reversecurrent': function(td1,td2){
  19897. return 1;
  19898. },
  19899. 'orderbyasc': function(td1,td2){
  19900. var value1 = td1.innerText||td1.textContent,
  19901. value2 = td2.innerText||td2.textContent;
  19902. return value1.localeCompare(value2);
  19903. },
  19904. 'reversebyasc': function(td1,td2){
  19905. var value1 = td1.innerHTML,
  19906. value2 = td2.innerHTML;
  19907. return value2.localeCompare(value1);
  19908. },
  19909. 'orderbynum': function(td1,td2){
  19910. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19911. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19912. if(value1) value1 = +value1[0];
  19913. if(value2) value2 = +value2[0];
  19914. return (value1||0) - (value2||0);
  19915. },
  19916. 'reversebynum': function(td1,td2){
  19917. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19918. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19919. if(value1) value1 = +value1[0];
  19920. if(value2) value2 = +value2[0];
  19921. return (value2||0) - (value1||0);
  19922. }
  19923. };
  19924. //对表格设置排序的标记data-sort-type
  19925. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19926. //th不参与排序
  19927. flag && trArray.splice(0, 1);
  19928. trArray = utils.sort(trArray,function (tr1, tr2) {
  19929. var result;
  19930. if (compareFn && typeof compareFn === "function") {
  19931. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19932. } else if (compareFn && typeof compareFn === "number") {
  19933. result = 1;
  19934. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19935. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19936. } else {
  19937. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19938. }
  19939. return result;
  19940. });
  19941. var fragment = table.ownerDocument.createDocumentFragment();
  19942. for (var j = 0, len = trArray.length; j < len; j++) {
  19943. fragment.appendChild(trArray[j]);
  19944. }
  19945. var tbody = table.getElementsByTagName("tbody")[0];
  19946. if(!lastRowIndex){
  19947. tbody.appendChild(fragment);
  19948. }else{
  19949. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  19950. }
  19951. };
  19952. UE.plugins['tablesort'] = function () {
  19953. var me = this,
  19954. UT = UE.UETable,
  19955. getUETable = function (tdOrTable) {
  19956. return UT.getUETable(tdOrTable);
  19957. },
  19958. getTableItemsByRange = function (editor) {
  19959. return UT.getTableItemsByRange(editor);
  19960. };
  19961. me.ready(function () {
  19962. //添加表格可排序的样式
  19963. utils.cssRule('tablesort',
  19964. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  19965. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  19966. me.document);
  19967. //做单元格合并操作时,清除可排序标识
  19968. me.addListener("afterexeccommand", function (type, cmd) {
  19969. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  19970. this.execCommand('disablesort');
  19971. }
  19972. });
  19973. });
  19974. //表格排序
  19975. UE.commands['sorttable'] = {
  19976. queryCommandState: function () {
  19977. var me = this,
  19978. tableItems = getTableItemsByRange(me);
  19979. if (!tableItems.cell) return -1;
  19980. var table = tableItems.table,
  19981. cells = table.getElementsByTagName("td");
  19982. for (var i = 0, cell; cell = cells[i++];) {
  19983. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  19984. }
  19985. return 0;
  19986. },
  19987. execCommand: function (cmd, fn) {
  19988. var me = this,
  19989. range = me.selection.getRange(),
  19990. bk = range.createBookmark(true),
  19991. tableItems = getTableItemsByRange(me),
  19992. cell = tableItems.cell,
  19993. ut = getUETable(tableItems.table),
  19994. cellInfo = ut.getCellInfo(cell);
  19995. ut.sortTable(cellInfo.cellIndex, fn);
  19996. range.moveToBookmark(bk);
  19997. try{
  19998. range.select();
  19999. }catch(e){}
  20000. }
  20001. };
  20002. //设置表格可排序,清除表格可排序
  20003. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20004. queryCommandState: function (cmd) {
  20005. var table = getTableItemsByRange(this).table;
  20006. if(table && cmd=='enablesort') {
  20007. var cells = domUtils.getElementsByTagName(table, 'th td');
  20008. for(var i = 0; i<cells.length; i++) {
  20009. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20010. }
  20011. }
  20012. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20013. },
  20014. execCommand: function (cmd) {
  20015. var table = getTableItemsByRange(this).table;
  20016. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20017. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20018. }
  20019. };
  20020. };
  20021. // plugins/contextmenu.js
  20022. ///import core
  20023. ///commands 右键菜单
  20024. ///commandsName ContextMenu
  20025. ///commandsTitle 右键菜单
  20026. /**
  20027. * 右键菜单
  20028. * @function
  20029. * @name baidu.editor.plugins.contextmenu
  20030. * @author zhanyi
  20031. */
  20032. UE.plugins['contextmenu'] = function () {
  20033. var me = this;
  20034. me.setOpt('enableContextMenu',true);
  20035. if(me.getOpt('enableContextMenu') === false){
  20036. return;
  20037. }
  20038. var lang = me.getLang( "contextMenu" ),
  20039. menu,
  20040. items = me.options.contextMenu || [
  20041. {label:lang['selectall'], cmdName:'selectall'},
  20042. {
  20043. label:lang.cleardoc,
  20044. cmdName:'cleardoc',
  20045. exec:function () {
  20046. if ( confirm( lang.confirmclear ) ) {
  20047. this.execCommand( 'cleardoc' );
  20048. }
  20049. }
  20050. },
  20051. '-',
  20052. {
  20053. label:lang.unlink,
  20054. cmdName:'unlink'
  20055. },
  20056. '-',
  20057. {
  20058. group:lang.paragraph,
  20059. icon:'justifyjustify',
  20060. subMenu:[
  20061. {
  20062. label:lang.justifyleft,
  20063. cmdName:'justify',
  20064. value:'left'
  20065. },
  20066. {
  20067. label:lang.justifyright,
  20068. cmdName:'justify',
  20069. value:'right'
  20070. },
  20071. {
  20072. label:lang.justifycenter,
  20073. cmdName:'justify',
  20074. value:'center'
  20075. },
  20076. {
  20077. label:lang.justifyjustify,
  20078. cmdName:'justify',
  20079. value:'justify'
  20080. }
  20081. ]
  20082. },
  20083. '-',
  20084. {
  20085. group:lang.table,
  20086. icon:'table',
  20087. subMenu:[
  20088. {
  20089. label:lang.inserttable,
  20090. cmdName:'inserttable'
  20091. },
  20092. {
  20093. label:lang.deletetable,
  20094. cmdName:'deletetable'
  20095. },
  20096. '-',
  20097. {
  20098. label:lang.deleterow,
  20099. cmdName:'deleterow'
  20100. },
  20101. {
  20102. label:lang.deletecol,
  20103. cmdName:'deletecol'
  20104. },
  20105. {
  20106. label:lang.insertcol,
  20107. cmdName:'insertcol'
  20108. },
  20109. {
  20110. label:lang.insertcolnext,
  20111. cmdName:'insertcolnext'
  20112. },
  20113. {
  20114. label:lang.insertrow,
  20115. cmdName:'insertrow'
  20116. },
  20117. {
  20118. label:lang.insertrownext,
  20119. cmdName:'insertrownext'
  20120. },
  20121. '-',
  20122. {
  20123. label:lang.insertcaption,
  20124. cmdName:'insertcaption'
  20125. },
  20126. {
  20127. label:lang.deletecaption,
  20128. cmdName:'deletecaption'
  20129. },
  20130. {
  20131. label:lang.inserttitle,
  20132. cmdName:'inserttitle'
  20133. },
  20134. {
  20135. label:lang.deletetitle,
  20136. cmdName:'deletetitle'
  20137. },
  20138. {
  20139. label:lang.inserttitlecol,
  20140. cmdName:'inserttitlecol'
  20141. },
  20142. {
  20143. label:lang.deletetitlecol,
  20144. cmdName:'deletetitlecol'
  20145. },
  20146. '-',
  20147. {
  20148. label:lang.mergecells,
  20149. cmdName:'mergecells'
  20150. },
  20151. {
  20152. label:lang.mergeright,
  20153. cmdName:'mergeright'
  20154. },
  20155. {
  20156. label:lang.mergedown,
  20157. cmdName:'mergedown'
  20158. },
  20159. '-',
  20160. {
  20161. label:lang.splittorows,
  20162. cmdName:'splittorows'
  20163. },
  20164. {
  20165. label:lang.splittocols,
  20166. cmdName:'splittocols'
  20167. },
  20168. {
  20169. label:lang.splittocells,
  20170. cmdName:'splittocells'
  20171. },
  20172. '-',
  20173. {
  20174. label:lang.averageDiseRow,
  20175. cmdName:'averagedistributerow'
  20176. },
  20177. {
  20178. label:lang.averageDisCol,
  20179. cmdName:'averagedistributecol'
  20180. },
  20181. '-',
  20182. {
  20183. label:lang.edittd,
  20184. cmdName:'edittd',
  20185. exec:function () {
  20186. if ( UE.ui['edittd'] ) {
  20187. new UE.ui['edittd']( this );
  20188. }
  20189. this.getDialog('edittd').open();
  20190. }
  20191. },
  20192. {
  20193. label:lang.edittable,
  20194. cmdName:'edittable',
  20195. exec:function () {
  20196. if ( UE.ui['edittable'] ) {
  20197. new UE.ui['edittable']( this );
  20198. }
  20199. this.getDialog('edittable').open();
  20200. }
  20201. },
  20202. {
  20203. label:lang.setbordervisible,
  20204. cmdName:'setbordervisible'
  20205. }
  20206. ]
  20207. },
  20208. {
  20209. group:lang.tablesort,
  20210. icon:'tablesort',
  20211. subMenu:[
  20212. {
  20213. label:lang.enablesort,
  20214. cmdName:'enablesort'
  20215. },
  20216. {
  20217. label:lang.disablesort,
  20218. cmdName:'disablesort'
  20219. },
  20220. '-',
  20221. {
  20222. label:lang.reversecurrent,
  20223. cmdName:'sorttable',
  20224. value:'reversecurrent'
  20225. },
  20226. {
  20227. label:lang.orderbyasc,
  20228. cmdName:'sorttable',
  20229. value:'orderbyasc'
  20230. },
  20231. {
  20232. label:lang.reversebyasc,
  20233. cmdName:'sorttable',
  20234. value:'reversebyasc'
  20235. },
  20236. {
  20237. label:lang.orderbynum,
  20238. cmdName:'sorttable',
  20239. value:'orderbynum'
  20240. },
  20241. {
  20242. label:lang.reversebynum,
  20243. cmdName:'sorttable',
  20244. value:'reversebynum'
  20245. }
  20246. ]
  20247. },
  20248. {
  20249. group:lang.borderbk,
  20250. icon:'borderBack',
  20251. subMenu:[
  20252. {
  20253. label:lang.setcolor,
  20254. cmdName:"interlacetable",
  20255. exec:function(){
  20256. this.execCommand("interlacetable");
  20257. }
  20258. },
  20259. {
  20260. label:lang.unsetcolor,
  20261. cmdName:"uninterlacetable",
  20262. exec:function(){
  20263. this.execCommand("uninterlacetable");
  20264. }
  20265. },
  20266. {
  20267. label:lang.setbackground,
  20268. cmdName:"settablebackground",
  20269. exec:function(){
  20270. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20271. }
  20272. },
  20273. {
  20274. label:lang.unsetbackground,
  20275. cmdName:"cleartablebackground",
  20276. exec:function(){
  20277. this.execCommand("cleartablebackground");
  20278. }
  20279. },
  20280. {
  20281. label:lang.redandblue,
  20282. cmdName:"settablebackground",
  20283. exec:function(){
  20284. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20285. }
  20286. },
  20287. {
  20288. label:lang.threecolorgradient,
  20289. cmdName:"settablebackground",
  20290. exec:function(){
  20291. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20292. }
  20293. }
  20294. ]
  20295. },
  20296. {
  20297. group:lang.aligntd,
  20298. icon:'aligntd',
  20299. subMenu:[
  20300. {
  20301. cmdName:'cellalignment',
  20302. value:{align:'left',vAlign:'top'}
  20303. },
  20304. {
  20305. cmdName:'cellalignment',
  20306. value:{align:'center',vAlign:'top'}
  20307. },
  20308. {
  20309. cmdName:'cellalignment',
  20310. value:{align:'right',vAlign:'top'}
  20311. },
  20312. {
  20313. cmdName:'cellalignment',
  20314. value:{align:'left',vAlign:'middle'}
  20315. },
  20316. {
  20317. cmdName:'cellalignment',
  20318. value:{align:'center',vAlign:'middle'}
  20319. },
  20320. {
  20321. cmdName:'cellalignment',
  20322. value:{align:'right',vAlign:'middle'}
  20323. },
  20324. {
  20325. cmdName:'cellalignment',
  20326. value:{align:'left',vAlign:'bottom'}
  20327. },
  20328. {
  20329. cmdName:'cellalignment',
  20330. value:{align:'center',vAlign:'bottom'}
  20331. },
  20332. {
  20333. cmdName:'cellalignment',
  20334. value:{align:'right',vAlign:'bottom'}
  20335. }
  20336. ]
  20337. },
  20338. {
  20339. group:lang.aligntable,
  20340. icon:'aligntable',
  20341. subMenu:[
  20342. {
  20343. cmdName:'tablealignment',
  20344. className: 'left',
  20345. label:lang.tableleft,
  20346. value:"left"
  20347. },
  20348. {
  20349. cmdName:'tablealignment',
  20350. className: 'center',
  20351. label:lang.tablecenter,
  20352. value:"center"
  20353. },
  20354. {
  20355. cmdName:'tablealignment',
  20356. className: 'right',
  20357. label:lang.tableright,
  20358. value:"right"
  20359. }
  20360. ]
  20361. },
  20362. '-',
  20363. {
  20364. label:lang.insertparagraphbefore,
  20365. cmdName:'insertparagraph',
  20366. value:true
  20367. },
  20368. {
  20369. label:lang.insertparagraphafter,
  20370. cmdName:'insertparagraph'
  20371. },
  20372. {
  20373. label:lang['copy'],
  20374. cmdName:'copy'
  20375. },
  20376. {
  20377. label:lang['paste'],
  20378. cmdName:'paste'
  20379. }
  20380. ];
  20381. if ( !items.length ) {
  20382. return;
  20383. }
  20384. var uiUtils = UE.ui.uiUtils;
  20385. me.addListener( 'contextmenu', function ( type, evt ) {
  20386. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20387. me.fireEvent( 'beforeselectionchange' );
  20388. if ( menu ) {
  20389. menu.destroy();
  20390. }
  20391. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20392. var last;
  20393. (function ( item ) {
  20394. if ( item == '-' ) {
  20395. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20396. contextItems.push( '-' );
  20397. }
  20398. } else if ( item.hasOwnProperty( "group" ) ) {
  20399. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20400. (function ( subItem ) {
  20401. if ( subItem == '-' ) {
  20402. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20403. subMenu.push( '-' );
  20404. }else{
  20405. subMenu.splice(subMenu.length-1);
  20406. }
  20407. } else {
  20408. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20409. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20410. subMenu.push( {
  20411. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20412. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20413. onclick:subItem.exec ? function () {
  20414. subItem.exec.call( me );
  20415. } : function () {
  20416. me.execCommand( subItem.cmdName, subItem.value );
  20417. }
  20418. } );
  20419. }
  20420. }
  20421. })( cj );
  20422. }
  20423. if ( subMenu.length ) {
  20424. function getLabel(){
  20425. switch (item.icon){
  20426. case "table":
  20427. return me.getLang( "contextMenu.table" );
  20428. case "justifyjustify":
  20429. return me.getLang( "contextMenu.paragraph" );
  20430. case "aligntd":
  20431. return me.getLang("contextMenu.aligntd");
  20432. case "aligntable":
  20433. return me.getLang("contextMenu.aligntable");
  20434. case "tablesort":
  20435. return lang.tablesort;
  20436. case "borderBack":
  20437. return lang.borderbk;
  20438. default :
  20439. return '';
  20440. }
  20441. }
  20442. contextItems.push( {
  20443. //todo 修正成自动获取方式
  20444. 'label':getLabel(),
  20445. className:'edui-for-' + item.icon,
  20446. 'subMenu':{
  20447. items:subMenu,
  20448. editor:me
  20449. }
  20450. } );
  20451. }
  20452. } else {
  20453. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20454. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20455. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20456. contextItems.push( {
  20457. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20458. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20459. onclick:item.exec ? function () {
  20460. item.exec.call( me );
  20461. } : function () {
  20462. me.execCommand( item.cmdName, item.value );
  20463. }
  20464. } );
  20465. }
  20466. }
  20467. })( ti );
  20468. }
  20469. if ( contextItems[contextItems.length - 1] == '-' ) {
  20470. contextItems.pop();
  20471. }
  20472. menu = new UE.ui.Menu( {
  20473. items:contextItems,
  20474. className:"edui-contextmenu",
  20475. editor:me
  20476. } );
  20477. menu.render();
  20478. menu.showAt( offset );
  20479. me.fireEvent("aftershowcontextmenu",menu);
  20480. domUtils.preventDefault( evt );
  20481. if ( browser.ie ) {
  20482. var ieRange;
  20483. try {
  20484. ieRange = me.selection.getNative().createRange();
  20485. } catch ( e ) {
  20486. return;
  20487. }
  20488. if ( ieRange.item ) {
  20489. var range = new dom.Range( me.document );
  20490. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20491. }
  20492. }
  20493. });
  20494. // 添加复制的flash按钮
  20495. me.addListener('aftershowcontextmenu', function(type, menu) {
  20496. if (me.zeroclipboard) {
  20497. var items = menu.items;
  20498. for (var key in items) {
  20499. if (items[key].className == 'edui-for-copy') {
  20500. me.zeroclipboard.clip(items[key].getDom());
  20501. }
  20502. }
  20503. }
  20504. });
  20505. };
  20506. // plugins/shortcutmenu.js
  20507. ///import core
  20508. ///commands 弹出菜单
  20509. // commandsName popupmenu
  20510. ///commandsTitle 弹出菜单
  20511. /**
  20512. * 弹出菜单
  20513. * @function
  20514. * @name baidu.editor.plugins.popupmenu
  20515. * @author xuheng
  20516. */
  20517. UE.plugins['shortcutmenu'] = function () {
  20518. var me = this,
  20519. menu,
  20520. items = me.options.shortcutMenu || [];
  20521. if (!items.length) {
  20522. return;
  20523. }
  20524. me.addListener ('contextmenu mouseup' , function (type , e) {
  20525. var me = this,
  20526. customEvt = {
  20527. type : type ,
  20528. target : e.target || e.srcElement ,
  20529. screenX : e.screenX ,
  20530. screenY : e.screenY ,
  20531. clientX : e.clientX ,
  20532. clientY : e.clientY
  20533. };
  20534. setTimeout (function () {
  20535. var rng = me.selection.getRange ();
  20536. if (rng.collapsed === false || type == "contextmenu") {
  20537. if (!menu) {
  20538. menu = new baidu.editor.ui.ShortCutMenu ({
  20539. editor : me ,
  20540. items : items ,
  20541. theme : me.options.theme ,
  20542. className : 'edui-shortcutmenu'
  20543. });
  20544. menu.render ();
  20545. me.fireEvent ("afterrendershortcutmenu" , menu);
  20546. }
  20547. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20548. }
  20549. });
  20550. if (type == 'contextmenu') {
  20551. domUtils.preventDefault (e);
  20552. if (browser.ie9below) {
  20553. var ieRange;
  20554. try {
  20555. ieRange = me.selection.getNative().createRange();
  20556. } catch (e) {
  20557. return;
  20558. }
  20559. if (ieRange.item) {
  20560. var range = new dom.Range (me.document);
  20561. range.selectNode (ieRange.item (0)).select (true , true);
  20562. }
  20563. }
  20564. }
  20565. });
  20566. me.addListener ('keydown' , function (type) {
  20567. if (type == "keydown") {
  20568. menu && !menu.isHidden && menu.hide ();
  20569. }
  20570. });
  20571. };
  20572. // plugins/basestyle.js
  20573. /**
  20574. * B、I、sub、super命令支持
  20575. * @file
  20576. * @since 1.2.6.1
  20577. */
  20578. UE.plugins['basestyle'] = function(){
  20579. /**
  20580. * 字体加粗
  20581. * @command bold
  20582. * @param { String } cmd 命令字符串
  20583. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20584. * @method execCommand
  20585. * @example
  20586. * ```javascript
  20587. * //editor是编辑器实例
  20588. * //对当前选中的文本内容执行加粗操作
  20589. * //第一次执行, 文本内容加粗
  20590. * editor.execCommand( 'bold' );
  20591. *
  20592. * //第二次执行, 文本内容取消加粗
  20593. * editor.execCommand( 'bold' );
  20594. * ```
  20595. */
  20596. /**
  20597. * 字体倾斜
  20598. * @command italic
  20599. * @method execCommand
  20600. * @param { String } cmd 命令字符串
  20601. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20602. * @example
  20603. * ```javascript
  20604. * //editor是编辑器实例
  20605. * //对当前选中的文本内容执行斜体操作
  20606. * //第一次操作, 文本内容将变成斜体
  20607. * editor.execCommand( 'italic' );
  20608. *
  20609. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20610. * editor.execCommand( 'italic' );
  20611. * ```
  20612. */
  20613. /**
  20614. * 下标文本,与“superscript”命令互斥
  20615. * @command subscript
  20616. * @method execCommand
  20617. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20618. * @param { String } cmd 命令字符串
  20619. * @example
  20620. * ```javascript
  20621. * //editor是编辑器实例
  20622. * //对当前选中的文本内容执行下标操作
  20623. * //第一次操作, 文本内容将变成下标文本
  20624. * editor.execCommand( 'subscript' );
  20625. *
  20626. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20627. * editor.execCommand( 'subscript' );
  20628. * ```
  20629. */
  20630. /**
  20631. * 上标文本,与“subscript”命令互斥
  20632. * @command superscript
  20633. * @method execCommand
  20634. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20635. * @param { String } cmd 命令字符串
  20636. * @example
  20637. * ```javascript
  20638. * //editor是编辑器实例
  20639. * //对当前选中的文本内容执行上标操作
  20640. * //第一次操作, 文本内容将变成上标文本
  20641. * editor.execCommand( 'superscript' );
  20642. *
  20643. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20644. * editor.execCommand( 'superscript' );
  20645. * ```
  20646. */
  20647. var basestyles = {
  20648. 'bold':['strong','b'],
  20649. 'italic':['em','i'],
  20650. 'subscript':['sub'],
  20651. 'superscript':['sup']
  20652. },
  20653. getObj = function(editor,tagNames){
  20654. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20655. },
  20656. me = this;
  20657. //添加快捷键
  20658. me.addshortcutkey({
  20659. "Bold" : "ctrl+66",//^B
  20660. "Italic" : "ctrl+73", //^I
  20661. "Underline" : "ctrl+85"//^U
  20662. });
  20663. me.addInputRule(function(root){
  20664. utils.each(root.getNodesByTagName('b i'),function(node){
  20665. switch (node.tagName){
  20666. case 'b':
  20667. node.tagName = 'strong';
  20668. break;
  20669. case 'i':
  20670. node.tagName = 'em';
  20671. }
  20672. });
  20673. });
  20674. for ( var style in basestyles ) {
  20675. (function( cmd, tagNames ) {
  20676. me.commands[cmd] = {
  20677. execCommand : function( cmdName ) {
  20678. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20679. if ( range.collapsed ) {
  20680. if ( obj ) {
  20681. var tmpText = me.document.createTextNode('');
  20682. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20683. range.setStartBefore(tmpText);
  20684. domUtils.remove(tmpText);
  20685. } else {
  20686. var tmpNode = range.document.createElement( tagNames[0] );
  20687. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20688. tmpText = me.document.createTextNode('');
  20689. range.insertNode(tmpText)
  20690. .removeInlineStyle(['sub','sup'])
  20691. .setStartBefore(tmpText)
  20692. .collapse(true);
  20693. }
  20694. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20695. }
  20696. range.collapse( true );
  20697. } else {
  20698. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20699. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20700. range.removeInlineStyle(['sub','sup']);
  20701. }
  20702. }
  20703. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20704. }
  20705. range.select();
  20706. },
  20707. queryCommandState : function() {
  20708. return getObj(this,tagNames) ? 1 : 0;
  20709. }
  20710. };
  20711. })( style, basestyles[style] );
  20712. }
  20713. };
  20714. // plugins/elementpath.js
  20715. /**
  20716. * 选取路径命令
  20717. * @file
  20718. */
  20719. UE.plugins['elementpath'] = function(){
  20720. var currentLevel,
  20721. tagNames,
  20722. me = this;
  20723. me.setOpt('elementPathEnabled',true);
  20724. if(!me.options.elementPathEnabled){
  20725. return;
  20726. }
  20727. me.commands['elementpath'] = {
  20728. execCommand : function( cmdName, level ) {
  20729. var start = tagNames[level],
  20730. range = me.selection.getRange();
  20731. currentLevel = level*1;
  20732. range.selectNode(start).select();
  20733. },
  20734. queryCommandValue : function() {
  20735. //产生一个副本,不能修改原来的startElementPath;
  20736. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20737. names = [];
  20738. tagNames = parents;
  20739. for(var i=0,ci;ci=parents[i];i++){
  20740. if(ci.nodeType == 3) {
  20741. continue;
  20742. }
  20743. var name = ci.tagName.toLowerCase();
  20744. if(name == 'img' && ci.getAttribute('anchorname')){
  20745. name = 'anchor';
  20746. }
  20747. names[i] = name;
  20748. if(currentLevel == i){
  20749. currentLevel = -1;
  20750. break;
  20751. }
  20752. }
  20753. return names;
  20754. }
  20755. };
  20756. };
  20757. // plugins/formatmatch.js
  20758. /**
  20759. * 格式刷,只格式inline的
  20760. * @file
  20761. * @since 1.2.6.1
  20762. */
  20763. /**
  20764. * 格式刷
  20765. * @command formatmatch
  20766. * @method execCommand
  20767. * @remind 该操作不能复制段落格式
  20768. * @param { String } cmd 命令字符串
  20769. * @example
  20770. * ```javascript
  20771. * //editor是编辑器实例
  20772. * //获取格式刷
  20773. * editor.execCommand( 'formatmatch' );
  20774. * ```
  20775. */
  20776. UE.plugins['formatmatch'] = function(){
  20777. var me = this,
  20778. list = [],img,
  20779. flag = 0;
  20780. me.addListener('reset',function(){
  20781. list = [];
  20782. flag = 0;
  20783. });
  20784. function addList(type,evt){
  20785. if(browser.webkit){
  20786. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20787. }
  20788. function addFormat(range){
  20789. if(text){
  20790. range.selectNode(text);
  20791. }
  20792. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20793. }
  20794. me.undoManger && me.undoManger.save();
  20795. var range = me.selection.getRange(),
  20796. imgT = target || range.getClosedNode();
  20797. if(img && imgT && imgT.tagName == 'IMG'){
  20798. //trace:964
  20799. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20800. img = null;
  20801. }else{
  20802. if(!img){
  20803. var collapsed = range.collapsed;
  20804. if(collapsed){
  20805. var text = me.document.createTextNode('match');
  20806. range.insertNode(text).select();
  20807. }
  20808. me.__hasEnterExecCommand = true;
  20809. //不能把block上的属性干掉
  20810. //trace:1553
  20811. var removeFormatAttributes = me.options.removeFormatAttributes;
  20812. me.options.removeFormatAttributes = '';
  20813. me.execCommand('removeformat');
  20814. me.options.removeFormatAttributes = removeFormatAttributes;
  20815. me.__hasEnterExecCommand = false;
  20816. //trace:969
  20817. range = me.selection.getRange();
  20818. if(list.length){
  20819. addFormat(range);
  20820. }
  20821. if(text){
  20822. range.setStartBefore(text).collapse(true);
  20823. }
  20824. range.select();
  20825. text && domUtils.remove(text);
  20826. }
  20827. }
  20828. me.undoManger && me.undoManger.save();
  20829. me.removeListener('mouseup',addList);
  20830. flag = 0;
  20831. }
  20832. me.commands['formatmatch'] = {
  20833. execCommand : function( cmdName ) {
  20834. if(flag){
  20835. flag = 0;
  20836. list = [];
  20837. me.removeListener('mouseup',addList);
  20838. return;
  20839. }
  20840. var range = me.selection.getRange();
  20841. img = range.getClosedNode();
  20842. if(!img || img.tagName != 'IMG'){
  20843. range.collapse(true).shrinkBoundary();
  20844. var start = range.startContainer;
  20845. list = domUtils.findParents(start,true,function(node){
  20846. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20847. });
  20848. //a不能加入格式刷, 并且克隆节点
  20849. for(var i=0,ci;ci=list[i];i++){
  20850. if(ci.tagName == 'A'){
  20851. list.splice(i,1);
  20852. break;
  20853. }
  20854. }
  20855. }
  20856. me.addListener('mouseup',addList);
  20857. flag = 1;
  20858. },
  20859. queryCommandState : function() {
  20860. return flag;
  20861. },
  20862. notNeedUndo : 1
  20863. };
  20864. };
  20865. // plugins/searchreplace.js
  20866. ///import core
  20867. ///commands 查找替换
  20868. ///commandsName SearchReplace
  20869. ///commandsTitle 查询替换
  20870. ///commandsDialog dialogs\searchreplace
  20871. /**
  20872. * @description 查找替换
  20873. * @author zhanyi
  20874. */
  20875. UE.plugin.register('searchreplace',function(){
  20876. var me = this;
  20877. function findTextInString(textContent,opt,currentIndex){
  20878. var str = opt.searchStr;
  20879. if(opt.dir == -1){
  20880. textContent = textContent.split('').reverse().join('');
  20881. str = str.split('').reverse().join('');
  20882. currentIndex = textContent.length - currentIndex;
  20883. }
  20884. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20885. while(match = reg.exec(textContent)){
  20886. if(match.index >= currentIndex){
  20887. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20888. }
  20889. }
  20890. return -1
  20891. }
  20892. function findTextBlockElm(node,currentIndex,opt){
  20893. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20894. if(domUtils.isBody(node)){
  20895. node = node.firstChild;
  20896. }
  20897. var first = 1;
  20898. while(node){
  20899. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20900. index = findTextInString(textContent,opt,currentIndex );
  20901. first = 0;
  20902. if(index!=-1){
  20903. return {
  20904. 'node':node,
  20905. 'index':index
  20906. }
  20907. }
  20908. node = domUtils[methodName](node);
  20909. if(node){
  20910. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20911. }
  20912. }
  20913. }
  20914. function findNTextInBlockElm(node,index,str){
  20915. var currentIndex = 0,
  20916. currentNode = node.firstChild,
  20917. currentNodeLength = 0,
  20918. result;
  20919. while(currentNode){
  20920. if(currentNode.nodeType == 3){
  20921. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20922. currentIndex += currentNodeLength;
  20923. if(currentIndex >= index){
  20924. return {
  20925. 'node':currentNode,
  20926. 'index': currentNodeLength - (currentIndex - index)
  20927. }
  20928. }
  20929. }else if(!dtd.$empty[currentNode.tagName]){
  20930. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20931. currentIndex += currentNodeLength;
  20932. if(currentIndex >= index){
  20933. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  20934. if(result){
  20935. return result;
  20936. }
  20937. }
  20938. }
  20939. currentNode = domUtils.getNextDomNode(currentNode);
  20940. }
  20941. }
  20942. function searchReplace(me,opt){
  20943. var rng = me.selection.getRange(),
  20944. startBlockNode,
  20945. searchStr = opt.searchStr,
  20946. span = me.document.createElement('span');
  20947. span.innerHTML = '$$ueditor_searchreplace_key$$';
  20948. //判断是不是第一次选中
  20949. if(!rng.collapsed){
  20950. rng.select();
  20951. var rngText = me.selection.getText();
  20952. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  20953. if(opt.replaceStr != undefined){
  20954. replaceText(rng,opt.replaceStr);
  20955. rng.select();
  20956. return true;
  20957. }else{
  20958. rng.collapse(opt.dir == -1)
  20959. }
  20960. }
  20961. }
  20962. rng.insertNode(span);
  20963. rng.enlargeToBlockElm(true);
  20964. startBlockNode = rng.startContainer;
  20965. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  20966. rng.setStartBefore(span);
  20967. domUtils.remove(span);
  20968. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  20969. if(result){
  20970. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  20971. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  20972. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  20973. if(opt.replaceStr !== undefined){
  20974. replaceText(rng,opt.replaceStr)
  20975. }
  20976. rng.select();
  20977. return true;
  20978. }else{
  20979. rng.setCursor()
  20980. }
  20981. }
  20982. function replaceText(rng,str){
  20983. me.fireEvent('saveScene');
  20984. str = me.document.createTextNode(str);
  20985. rng.deleteContents().insertNode(str);
  20986. me.fireEvent('saveScene');
  20987. }
  20988. return {
  20989. commands:{
  20990. 'searchreplace':{
  20991. execCommand:function(cmdName,opt){
  20992. utils.extend(opt,{
  20993. all : false,
  20994. casesensitive : false,
  20995. dir : 1
  20996. },true);
  20997. var num = 0;
  20998. if(opt.all){
  20999. var rng = me.selection.getRange(),
  21000. first = me.body.firstChild;
  21001. if(first && first.nodeType == 1){
  21002. rng.setStart(first,0)
  21003. }else if(first.nodeType == 3){
  21004. rng.setStartBefore(first)
  21005. }
  21006. rng.collapse(true).select(true);
  21007. while(searchReplace(this,opt)){
  21008. num++;
  21009. }
  21010. }else{
  21011. if(searchReplace(this,opt)){
  21012. num++
  21013. }
  21014. }
  21015. return num;
  21016. },
  21017. notNeedUndo:1
  21018. }
  21019. }
  21020. }
  21021. });
  21022. // plugins/customstyle.js
  21023. /**
  21024. * 自定义样式
  21025. * @file
  21026. * @since 1.2.6.1
  21027. */
  21028. /**
  21029. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21030. * @command customstyle
  21031. * @method execCommand
  21032. * @param { String } cmd 命令字符串
  21033. * @example
  21034. * ```javascript
  21035. * editor.execCommand( 'customstyle' );
  21036. * ```
  21037. */
  21038. UE.plugins['customstyle'] = function() {
  21039. var me = this;
  21040. me.setOpt({ 'customstyle':[
  21041. {tag:'h1',name:'tc', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
  21042. {tag:'h1',name:'tl', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;'},
  21043. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21044. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21045. ]});
  21046. me.commands['customstyle'] = {
  21047. execCommand : function(cmdName, obj) {
  21048. var me = this,
  21049. tagName = obj.tag,
  21050. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21051. return node.getAttribute('label');
  21052. }, true),
  21053. range,bk,tmpObj = {};
  21054. for (var p in obj) {
  21055. if(obj[p]!==undefined)
  21056. tmpObj[p] = obj[p];
  21057. }
  21058. delete tmpObj.tag;
  21059. if (node && node.getAttribute('label') == obj.label) {
  21060. range = this.selection.getRange();
  21061. bk = range.createBookmark();
  21062. if (range.collapsed) {
  21063. //trace:1732 删掉自定义标签,要有p来回填站位
  21064. if(dtd.$block[node.tagName]){
  21065. var fillNode = me.document.createElement('p');
  21066. domUtils.moveChild(node, fillNode);
  21067. node.parentNode.insertBefore(fillNode, node);
  21068. domUtils.remove(node);
  21069. }else{
  21070. domUtils.remove(node,true);
  21071. }
  21072. } else {
  21073. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21074. nodes = domUtils.getElementsByTagName(common, tagName);
  21075. if(new RegExp(tagName,'i').test(common.tagName)){
  21076. nodes.push(common);
  21077. }
  21078. for (var i = 0,ni; ni = nodes[i++];) {
  21079. if (ni.getAttribute('label') == obj.label) {
  21080. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21081. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21082. &&
  21083. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21084. )
  21085. if (dtd.$block[tagName]) {
  21086. var fillNode = me.document.createElement('p');
  21087. domUtils.moveChild(ni, fillNode);
  21088. ni.parentNode.insertBefore(fillNode, ni);
  21089. }
  21090. domUtils.remove(ni, true);
  21091. }
  21092. }
  21093. node = domUtils.findParent(common, function(node) {
  21094. return node.getAttribute('label') == obj.label;
  21095. }, true);
  21096. if (node) {
  21097. domUtils.remove(node, true);
  21098. }
  21099. }
  21100. range.moveToBookmark(bk).select();
  21101. } else {
  21102. if (dtd.$block[tagName]) {
  21103. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21104. range = me.selection.getRange();
  21105. if (!range.collapsed) {
  21106. range.collapse();
  21107. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21108. return node.getAttribute('label') == obj.label;
  21109. }, true);
  21110. var pNode = me.document.createElement('p');
  21111. domUtils.insertAfter(node, pNode);
  21112. domUtils.fillNode(me.document, pNode);
  21113. range.setStart(pNode, 0).setCursor();
  21114. }
  21115. } else {
  21116. range = me.selection.getRange();
  21117. if (range.collapsed) {
  21118. node = me.document.createElement(tagName);
  21119. domUtils.setAttributes(node, tmpObj);
  21120. range.insertNode(node).setStart(node, 0).setCursor();
  21121. return;
  21122. }
  21123. bk = range.createBookmark();
  21124. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21125. }
  21126. }
  21127. },
  21128. queryCommandValue : function() {
  21129. var parent = domUtils.filterNodeList(
  21130. this.selection.getStartElementPath(),
  21131. function(node){return node.getAttribute('label')}
  21132. );
  21133. return parent ? parent.getAttribute('label') : '';
  21134. }
  21135. };
  21136. //当去掉customstyle是,如果是块元素,用p代替
  21137. me.addListener('keyup', function(type, evt) {
  21138. var keyCode = evt.keyCode || evt.which;
  21139. if (keyCode == 32 || keyCode == 13) {
  21140. var range = me.selection.getRange();
  21141. if (range.collapsed) {
  21142. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21143. return node.getAttribute('label');
  21144. }, true);
  21145. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21146. var p = me.document.createElement('p');
  21147. domUtils.insertAfter(node, p);
  21148. domUtils.fillNode(me.document, p);
  21149. domUtils.remove(node);
  21150. range.setStart(p, 0).setCursor();
  21151. }
  21152. }
  21153. }
  21154. });
  21155. };
  21156. // plugins/catchremoteimage.js
  21157. ///import core
  21158. ///commands 远程图片抓取
  21159. ///commandsName catchRemoteImage,catchremoteimageenable
  21160. ///commandsTitle 远程图片抓取
  21161. /**
  21162. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21163. */
  21164. UE.plugins['catchremoteimage'] = function () {
  21165. var me = this,
  21166. ajax = UE.ajax;
  21167. /* 设置默认值 */
  21168. if (me.options.catchRemoteImageEnable === false) return;
  21169. me.setOpt({
  21170. catchRemoteImageEnable: false
  21171. });
  21172. me.addListener("afterpaste", function () {
  21173. me.fireEvent("catchRemoteImage");
  21174. });
  21175. me.addListener("catchRemoteImage", function () {
  21176. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21177. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21178. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21179. catcherFieldName = me.getOpt('catcherFieldName');
  21180. var remoteImages = [],
  21181. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21182. test = function (src, urls) {
  21183. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21184. return true;
  21185. }
  21186. if (urls) {
  21187. for (var j = 0, url; url = urls[j++];) {
  21188. if (src.indexOf(url) !== -1) {
  21189. return true;
  21190. }
  21191. }
  21192. }
  21193. return false;
  21194. };
  21195. for (var i = 0, ci; ci = imgs[i++];) {
  21196. if (ci.getAttribute("word_img")) {
  21197. continue;
  21198. }
  21199. var src = ci.getAttribute("_src") || ci.src || "";
  21200. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21201. remoteImages.push(src);
  21202. }
  21203. }
  21204. if (remoteImages.length) {
  21205. catchremoteimage(remoteImages, {
  21206. //成功抓取
  21207. success: function (r) {
  21208. try {
  21209. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21210. } catch (e) {
  21211. return;
  21212. }
  21213. /* 获取源路径和新路径 */
  21214. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21215. for (i = 0; ci = imgs[i++];) {
  21216. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21217. for (j = 0; cj = list[j++];) {
  21218. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21219. newSrc = catcherUrlPrefix + cj.url;
  21220. domUtils.setAttributes(ci, {
  21221. "src": newSrc,
  21222. "_src": newSrc
  21223. });
  21224. break;
  21225. }
  21226. }
  21227. }
  21228. me.fireEvent('catchremotesuccess')
  21229. },
  21230. //回调失败,本次请求超时
  21231. error: function () {
  21232. me.fireEvent("catchremoteerror");
  21233. }
  21234. });
  21235. }
  21236. function catchremoteimage(imgs, callbacks) {
  21237. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21238. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21239. isJsonp = utils.isCrossDomainUrl(url),
  21240. opt = {
  21241. 'method': 'POST',
  21242. 'dataType': isJsonp ? 'jsonp':'',
  21243. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21244. 'onsuccess': callbacks["success"],
  21245. 'onerror': callbacks["error"]
  21246. };
  21247. opt[catcherFieldName] = imgs;
  21248. ajax.request(url, opt);
  21249. }
  21250. });
  21251. };
  21252. // plugins/snapscreen.js
  21253. /**
  21254. * 截屏插件,为UEditor提供插入支持
  21255. * @file
  21256. * @since 1.4.2
  21257. */
  21258. UE.plugin.register('snapscreen', function (){
  21259. var me = this;
  21260. var snapplugin;
  21261. function getLocation(url){
  21262. var search,
  21263. a = document.createElement('a'),
  21264. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21265. a.href = url;
  21266. if (browser.ie) {
  21267. a.href = a.href;
  21268. }
  21269. search = a.search;
  21270. if (params) {
  21271. search = search ? search + params:'?' + params;
  21272. search = search.replace(/[&]+/ig, '&');
  21273. }
  21274. return {
  21275. 'port': a.port,
  21276. 'hostname': a.hostname,
  21277. 'path': a.pathname + search || + a.hash
  21278. }
  21279. }
  21280. return {
  21281. commands:{
  21282. /**
  21283. * 字体背景颜色
  21284. * @command snapscreen
  21285. * @method execCommand
  21286. * @param { String } cmd 命令字符串
  21287. * @example
  21288. * ```javascript
  21289. * editor.execCommand('snapscreen');
  21290. * ```
  21291. */
  21292. 'snapscreen':{
  21293. execCommand:function (cmd) {
  21294. var url, local, res;
  21295. var lang = me.getLang("snapScreen_plugin");
  21296. if(!snapplugin){
  21297. var container = me.container;
  21298. var doc = me.container.ownerDocument || me.container.document;
  21299. snapplugin = doc.createElement("object");
  21300. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21301. return;
  21302. }
  21303. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21304. snapplugin.setAttribute("width","0");
  21305. snapplugin.setAttribute("height","0");
  21306. container.appendChild(snapplugin);
  21307. }
  21308. function onSuccess(rs){
  21309. try{
  21310. rs = eval("("+ rs +")");
  21311. if(rs.state == 'SUCCESS'){
  21312. var opt = me.options;
  21313. me.execCommand('insertimage', {
  21314. src: opt.snapscreenUrlPrefix + rs.url,
  21315. _src: opt.snapscreenUrlPrefix + rs.url,
  21316. alt: rs.title || '',
  21317. floatStyle: opt.snapscreenImgAlign
  21318. });
  21319. } else {
  21320. alert(rs.state);
  21321. }
  21322. }catch(e){
  21323. alert(lang.callBackErrorMsg);
  21324. }
  21325. }
  21326. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21327. local = getLocation(url);
  21328. setTimeout(function () {
  21329. try{
  21330. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21331. }catch(e){
  21332. me.ui._dialogs['snapscreenDialog'].open();
  21333. return;
  21334. }
  21335. onSuccess(res);
  21336. }, 50);
  21337. },
  21338. queryCommandState: function(){
  21339. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21340. }
  21341. }
  21342. }
  21343. }
  21344. });
  21345. // plugins/insertparagraph.js
  21346. /**
  21347. * 插入段落
  21348. * @file
  21349. * @since 1.2.6.1
  21350. */
  21351. /**
  21352. * 插入段落
  21353. * @command insertparagraph
  21354. * @method execCommand
  21355. * @param { String } cmd 命令字符串
  21356. * @example
  21357. * ```javascript
  21358. * //editor是编辑器实例
  21359. * editor.execCommand( 'insertparagraph' );
  21360. * ```
  21361. */
  21362. UE.commands['insertparagraph'] = {
  21363. execCommand : function( cmdName,front) {
  21364. var me = this,
  21365. range = me.selection.getRange(),
  21366. start = range.startContainer,tmpNode;
  21367. while(start ){
  21368. if(domUtils.isBody(start)){
  21369. break;
  21370. }
  21371. tmpNode = start;
  21372. start = start.parentNode;
  21373. }
  21374. if(tmpNode){
  21375. var p = me.document.createElement('p');
  21376. if(front){
  21377. tmpNode.parentNode.insertBefore(p,tmpNode)
  21378. }else{
  21379. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21380. }
  21381. domUtils.fillNode(me.document,p);
  21382. range.setStart(p,0).setCursor(false,true);
  21383. }
  21384. }
  21385. };
  21386. // plugins/webapp.js
  21387. /**
  21388. * 百度应用
  21389. * @file
  21390. * @since 1.2.6.1
  21391. */
  21392. /**
  21393. * 插入百度应用
  21394. * @command webapp
  21395. * @method execCommand
  21396. * @remind 需要百度APPKey
  21397. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21398. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21399. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21400. * @example
  21401. * ```javascript
  21402. * //editor是编辑器实例
  21403. * //在编辑器里插入一个“植物大战僵尸”的APP
  21404. * editor.execCommand( 'webapp' , {
  21405. * title: '植物大战僵尸',
  21406. * width: 560,
  21407. * height: 465,
  21408. * logo: '应用展示的图片',
  21409. * url: '百度应用的地址'
  21410. * } );
  21411. * ```
  21412. */
  21413. //UE.plugins['webapp'] = function () {
  21414. // var me = this;
  21415. // function createInsertStr( obj, toIframe, addParagraph ) {
  21416. // return !toIframe ?
  21417. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21418. // ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" style="background:url(' + obj.logo+') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" />' +
  21419. // (addParagraph ? '</p>' : '')
  21420. // :
  21421. // '<iframe class="edui-faked-webapp" title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = '+obj.logo+'></iframe>';
  21422. // }
  21423. //
  21424. // function switchImgAndIframe( img2frame ) {
  21425. // var tmpdiv,
  21426. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21427. // for ( var i = 0, node; node = nodes[i++]; ) {
  21428. // if ( node.className != "edui-faked-webapp" ){
  21429. // continue;
  21430. // }
  21431. // tmpdiv = me.document.createElement( "div" );
  21432. // tmpdiv.innerHTML = createInsertStr( img2frame ? {url:node.getAttribute( "_url" ), width:node.width, height:node.height,title:node.title,logo:node.style.backgroundImage.replace("url(","").replace(")","")} : {url:node.getAttribute( "src", 2 ),title:node.title, width:node.width, height:node.height,logo:node.getAttribute("logo_url")}, img2frame ? true : false,false );
  21433. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21434. // }
  21435. // }
  21436. //
  21437. // me.addListener( "beforegetcontent", function () {
  21438. // switchImgAndIframe( true );
  21439. // } );
  21440. // me.addListener( 'aftersetcontent', function () {
  21441. // switchImgAndIframe( false );
  21442. // } );
  21443. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21444. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21445. // return;
  21446. // }
  21447. // switchImgAndIframe( false );
  21448. // } );
  21449. //
  21450. // me.commands['webapp'] = {
  21451. // execCommand:function ( cmd, obj ) {
  21452. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21453. // }
  21454. // };
  21455. //};
  21456. UE.plugin.register('webapp', function (){
  21457. var me = this;
  21458. function createInsertStr(obj,toEmbed){
  21459. return !toEmbed ?
  21460. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21461. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21462. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21463. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21464. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21465. '/>'
  21466. :
  21467. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21468. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21469. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21470. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21471. }
  21472. return {
  21473. outputRule: function(root){
  21474. utils.each(root.getNodesByTagName('img'),function(node){
  21475. var html;
  21476. if(node.getAttr('class') == 'edui-faked-webapp'){
  21477. html = createInsertStr({
  21478. title:node.getAttr('title'),
  21479. 'width':node.getAttr('width'),
  21480. 'height':node.getAttr('height'),
  21481. 'align':node.getAttr('align'),
  21482. 'cssfloat':node.getStyle('float'),
  21483. 'url':node.getAttr("_url"),
  21484. 'logo':node.getAttr('_logo_url')
  21485. },true);
  21486. var embed = UE.uNode.createElement(html);
  21487. node.parentNode.replaceChild(embed,node);
  21488. }
  21489. })
  21490. },
  21491. inputRule:function(root){
  21492. utils.each(root.getNodesByTagName('iframe'),function(node){
  21493. if(node.getAttr('class') == 'edui-faked-webapp'){
  21494. var img = UE.uNode.createElement(createInsertStr({
  21495. title:node.getAttr('title'),
  21496. 'width':node.getAttr('width'),
  21497. 'height':node.getAttr('height'),
  21498. 'align':node.getAttr('align'),
  21499. 'cssfloat':node.getStyle('float'),
  21500. 'url':node.getAttr("src"),
  21501. 'logo':node.getAttr('logo_url')
  21502. }));
  21503. node.parentNode.replaceChild(img,node);
  21504. }
  21505. })
  21506. },
  21507. commands:{
  21508. /**
  21509. * 插入百度应用
  21510. * @command webapp
  21511. * @method execCommand
  21512. * @remind 需要百度APPKey
  21513. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21514. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21515. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21516. * @example
  21517. * ```javascript
  21518. * //editor是编辑器实例
  21519. * //在编辑器里插入一个“植物大战僵尸”的APP
  21520. * editor.execCommand( 'webapp' , {
  21521. * title: '植物大战僵尸',
  21522. * width: 560,
  21523. * height: 465,
  21524. * logo: '应用展示的图片',
  21525. * url: '百度应用的地址'
  21526. * } );
  21527. * ```
  21528. */
  21529. 'webapp':{
  21530. execCommand:function (cmd, obj) {
  21531. var me = this,
  21532. str = createInsertStr(utils.extend(obj,{
  21533. align:'none'
  21534. }), false);
  21535. me.execCommand("inserthtml",str);
  21536. },
  21537. queryCommandState:function () {
  21538. var me = this,
  21539. img = me.selection.getRange().getClosedNode(),
  21540. flag = img && (img.className == "edui-faked-webapp");
  21541. return flag ? 1 : 0;
  21542. }
  21543. }
  21544. }
  21545. }
  21546. });
  21547. // plugins/template.js
  21548. ///import core
  21549. ///import plugins\inserthtml.js
  21550. ///import plugins\cleardoc.js
  21551. ///commands 模板
  21552. ///commandsName template
  21553. ///commandsTitle 模板
  21554. ///commandsDialog dialogs\template
  21555. UE.plugins['template'] = function () {
  21556. UE.commands['template'] = {
  21557. execCommand:function (cmd, obj) {
  21558. obj.html && this.execCommand("inserthtml", obj.html);
  21559. }
  21560. };
  21561. this.addListener("click", function (type, evt) {
  21562. var el = evt.target || evt.srcElement,
  21563. range = this.selection.getRange();
  21564. var tnode = domUtils.findParent(el, function (node) {
  21565. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21566. return node;
  21567. }
  21568. }, true);
  21569. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21570. });
  21571. this.addListener("keydown", function (type, evt) {
  21572. var range = this.selection.getRange();
  21573. if (!range.collapsed) {
  21574. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21575. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21576. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21577. return node;
  21578. }
  21579. }, true);
  21580. if (tnode) {
  21581. domUtils.removeClasses(tnode, ["ue_t"]);
  21582. }
  21583. }
  21584. }
  21585. });
  21586. };
  21587. // plugins/music.js
  21588. /**
  21589. * 插入音乐命令
  21590. * @file
  21591. */
  21592. UE.plugin.register('music', function (){
  21593. var me = this;
  21594. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21595. return !toEmbed ?
  21596. '<img ' +
  21597. (align && !cssfloat? 'align="' + align + '"' : '') +
  21598. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21599. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21600. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21601. :
  21602. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21603. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21604. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21605. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21606. }
  21607. return {
  21608. outputRule: function(root){
  21609. utils.each(root.getNodesByTagName('img'),function(node){
  21610. var html;
  21611. if(node.getAttr('class') == 'edui-faked-music'){
  21612. var cssfloat = node.getStyle('float');
  21613. var align = node.getAttr('align');
  21614. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21615. var embed = UE.uNode.createElement(html);
  21616. node.parentNode.replaceChild(embed,node);
  21617. }
  21618. })
  21619. },
  21620. inputRule:function(root){
  21621. utils.each(root.getNodesByTagName('embed'),function(node){
  21622. if(node.getAttr('class') == 'edui-faked-music'){
  21623. var cssfloat = node.getStyle('float');
  21624. var align = node.getAttr('align');
  21625. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21626. var img = UE.uNode.createElement(html);
  21627. node.parentNode.replaceChild(img,node);
  21628. }
  21629. })
  21630. },
  21631. commands:{
  21632. /**
  21633. * 插入音乐
  21634. * @command music
  21635. * @method execCommand
  21636. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21637. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21638. * @example
  21639. * ```javascript
  21640. * //editor是编辑器实例
  21641. * //在编辑器里插入一个“植物大战僵尸”的APP
  21642. * editor.execCommand( 'music' , {
  21643. * width: 400,
  21644. * height: 95,
  21645. * align: "center",
  21646. * url: "音乐地址"
  21647. * } );
  21648. * ```
  21649. */
  21650. 'music':{
  21651. execCommand:function (cmd, musicObj) {
  21652. var me = this,
  21653. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21654. me.execCommand("inserthtml",str);
  21655. },
  21656. queryCommandState:function () {
  21657. var me = this,
  21658. img = me.selection.getRange().getClosedNode(),
  21659. flag = img && (img.className == "edui-faked-music");
  21660. return flag ? 1 : 0;
  21661. }
  21662. }
  21663. }
  21664. }
  21665. });
  21666. // plugins/autoupload.js
  21667. /**
  21668. * @description
  21669. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21670. * 2.插入粘贴板的图片,自动上传并插入到选区
  21671. * @author Jinqn
  21672. * @date 2013-10-14
  21673. */
  21674. UE.plugin.register('autoupload', function (){
  21675. var me = this;
  21676. function sendAndInsertFile(file, editor) {
  21677. //模拟数据
  21678. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21679. loadingHtml, errorHandler, successHandler,
  21680. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21681. loadingId = 'loading_' + (+new Date()).toString(36);
  21682. fieldName = editor.getOpt(filetype + 'FieldName');
  21683. urlPrefix = editor.getOpt(filetype + 'UrlPrefix');
  21684. maxSize = editor.getOpt(filetype + 'MaxSize');
  21685. allowFiles = editor.getOpt(filetype + 'AllowFiles');
  21686. actionUrl = editor.getActionUrl(editor.getOpt(filetype + 'ActionName'));
  21687. errorHandler = function(title) {
  21688. var loader = editor.document.getElementById(loadingId);
  21689. if (loader) {
  21690. domUtils.removeClasses(loader, 'loadingclass');
  21691. domUtils.addClass(loader, 'loaderrorclass');
  21692. loader.setAttribute('title', title || '');
  21693. }
  21694. };
  21695. if (filetype == 'image') {
  21696. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21697. editor.options.themePath + editor.options.theme +
  21698. '/images/spacer.gif" title="' + (editor.getLang('autoupload.loading') || '') + '" >';
  21699. successHandler = function(data) {
  21700. var link = urlPrefix + data.url,
  21701. loader = editor.document.getElementById(loadingId);
  21702. if (loader) {
  21703. loader.setAttribute('src', link);
  21704. loader.setAttribute('_src', link);
  21705. loader.setAttribute('title', data.title || '');
  21706. loader.setAttribute('alt', data.original || '');
  21707. loader.removeAttribute('id');
  21708. domUtils.removeClasses(loader, 'loadingclass');
  21709. }
  21710. };
  21711. } else {
  21712. loadingHtml = '<p>' +
  21713. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21714. editor.options.themePath + editor.options.theme +
  21715. '/images/spacer.gif" title="' + (editor.getLang('autoupload.loading') || '') + '" >' +
  21716. '</p>';
  21717. successHandler = function(data) {
  21718. var link = urlPrefix + data.url,
  21719. loader = editor.document.getElementById(loadingId);
  21720. var rng = editor.selection.getRange(),
  21721. bk = rng.createBookmark();
  21722. rng.selectNode(loader).select();
  21723. editor.execCommand('insertfile', {'url': link});
  21724. rng.moveToBookmark(bk).select();
  21725. };
  21726. }
  21727. /* 插入loading的占位符 */
  21728. editor.execCommand('inserthtml', loadingHtml);
  21729. /* 判断文件大小是否超出限制 */
  21730. if(file.size > maxSize) {
  21731. errorHandler(editor.getLang('autoupload.exceedSizeError'));
  21732. return;
  21733. }
  21734. /* 判断文件格式是否超出允许 */
  21735. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21736. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21737. errorHandler(editor.getLang('autoupload.exceedTypeError'));
  21738. return;
  21739. }
  21740. /* 创建Ajax并提交 */
  21741. var xhr = new XMLHttpRequest(),
  21742. fd = new FormData(),
  21743. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21744. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21745. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21746. fd.append('type', 'ajax');
  21747. xhr.open("post", url, true);
  21748. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21749. xhr.addEventListener('load', function (e) {
  21750. try{
  21751. var json = (new Function("return " + utils.trim(e.target.response)))();
  21752. if (json.state == 'SUCCESS' && json.url) {
  21753. successHandler(json);
  21754. } else {
  21755. errorHandler(json.state);
  21756. }
  21757. }catch(er){
  21758. errorHandler(editor.getLang('autoupload.loadError'));
  21759. }
  21760. });
  21761. xhr.send(fd);
  21762. }
  21763. function getPasteImage(e){
  21764. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21765. }
  21766. function getDropImage(e){
  21767. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21768. }
  21769. return {
  21770. outputRule: function(root){
  21771. utils.each(root.getNodesByTagName('img'),function(n){
  21772. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21773. n.parentNode.removeChild(n);
  21774. }
  21775. });
  21776. utils.each(root.getNodesByTagName('p'),function(n){
  21777. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21778. n.parentNode.removeChild(n);
  21779. }
  21780. });
  21781. },
  21782. bindEvents:{
  21783. //插入粘贴板的图片,拖放插入图片
  21784. 'ready':function(e){
  21785. if(window.FormData && window.FileReader) {
  21786. domUtils.on(me.body, 'paste drop', function(e){
  21787. var hasImg = false,
  21788. items;
  21789. //获取粘贴板文件列表或者拖放文件列表
  21790. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21791. if(items){
  21792. var len = items.length,
  21793. file;
  21794. while (len--){
  21795. file = items[len];
  21796. if(file.getAsFile) file = file.getAsFile();
  21797. if(file && file.size > 0) {
  21798. sendAndInsertFile(file, me);
  21799. hasImg = true;
  21800. }
  21801. }
  21802. hasImg && e.preventDefault();
  21803. }
  21804. });
  21805. //取消拖放图片时出现的文字光标位置提示
  21806. domUtils.on(me.body, 'dragover', function (e) {
  21807. if(e.dataTransfer.types[0] == 'Files') {
  21808. e.preventDefault();
  21809. }
  21810. });
  21811. //设置loading的样式
  21812. utils.cssRule('loading',
  21813. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21814. + this.options.themePath
  21815. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21816. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21817. + this.options.themePath
  21818. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21819. '}',
  21820. this.document);
  21821. }
  21822. }
  21823. }
  21824. }
  21825. });
  21826. // plugins/autosave.js
  21827. UE.plugin.register('autosave', function (){
  21828. var me = this,
  21829. //无限循环保护
  21830. lastSaveTime = new Date(),
  21831. //最小保存间隔时间
  21832. MIN_TIME = 20,
  21833. //auto save key
  21834. saveKey = null;
  21835. function save ( editor ) {
  21836. var saveData;
  21837. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21838. return;
  21839. }
  21840. if ( !editor.hasContents() ) {
  21841. //这里不能调用命令来删除, 会造成事件死循环
  21842. saveKey && me.removePreferences( saveKey );
  21843. return;
  21844. }
  21845. lastSaveTime = new Date();
  21846. editor._saveFlag = null;
  21847. saveData = me.body.innerHTML;
  21848. if ( editor.fireEvent( "beforeautosave", {
  21849. content: saveData
  21850. } ) === false ) {
  21851. return;
  21852. }
  21853. me.setPreferences( saveKey, saveData );
  21854. editor.fireEvent( "afterautosave", {
  21855. content: saveData
  21856. } );
  21857. }
  21858. return {
  21859. defaultOptions: {
  21860. //默认间隔时间
  21861. saveInterval: 500
  21862. },
  21863. bindEvents:{
  21864. 'ready':function(){
  21865. var _suffix = "-drafts-data",
  21866. key = null;
  21867. if ( me.key ) {
  21868. key = me.key + _suffix;
  21869. } else {
  21870. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21871. }
  21872. //页面地址+编辑器ID 保持唯一
  21873. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21874. },
  21875. 'contentchange': function () {
  21876. if ( !saveKey ) {
  21877. return;
  21878. }
  21879. if ( me._saveFlag ) {
  21880. window.clearTimeout( me._saveFlag );
  21881. }
  21882. if ( me.options.saveInterval > 0 ) {
  21883. me._saveFlag = window.setTimeout( function () {
  21884. save( me );
  21885. }, me.options.saveInterval );
  21886. } else {
  21887. save(me);
  21888. }
  21889. }
  21890. },
  21891. commands:{
  21892. 'clearlocaldata':{
  21893. execCommand:function (cmd, name) {
  21894. if ( saveKey && me.getPreferences( saveKey ) ) {
  21895. me.removePreferences( saveKey )
  21896. }
  21897. },
  21898. notNeedUndo: true,
  21899. ignoreContentChange:true
  21900. },
  21901. 'getlocaldata':{
  21902. execCommand:function (cmd, name) {
  21903. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21904. },
  21905. notNeedUndo: true,
  21906. ignoreContentChange:true
  21907. },
  21908. 'drafts':{
  21909. execCommand:function (cmd, name) {
  21910. if ( saveKey ) {
  21911. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  21912. me.focus(true);
  21913. }
  21914. },
  21915. queryCommandState: function () {
  21916. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  21917. },
  21918. notNeedUndo: true,
  21919. ignoreContentChange:true
  21920. }
  21921. }
  21922. }
  21923. });
  21924. // plugins/charts.js
  21925. UE.plugin.register('charts', function (){
  21926. var me = this;
  21927. return {
  21928. bindEvents: {
  21929. 'chartserror': function () {
  21930. }
  21931. },
  21932. commands:{
  21933. 'charts': {
  21934. execCommand: function ( cmd, data ) {
  21935. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  21936. flagText = [],
  21937. config = {};
  21938. if ( !tableNode ) {
  21939. return false;
  21940. }
  21941. if ( !validData( tableNode ) ) {
  21942. me.fireEvent( "chartserror" );
  21943. return false;
  21944. }
  21945. config.title = data.title || '';
  21946. config.subTitle = data.subTitle || '';
  21947. config.xTitle = data.xTitle || '';
  21948. config.yTitle = data.yTitle || '';
  21949. config.suffix = data.suffix || '';
  21950. config.tip = data.tip || '';
  21951. //数据对齐方式
  21952. config.dataFormat = data.tableDataFormat || '';
  21953. //图表类型
  21954. config.chartType = data.chartType || 0;
  21955. for ( var key in config ) {
  21956. if ( !config.hasOwnProperty( key ) ) {
  21957. continue;
  21958. }
  21959. flagText.push( key+":"+config[ key ] );
  21960. }
  21961. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  21962. domUtils.addClass( tableNode, "edui-charts-table" );
  21963. },
  21964. queryCommandState: function ( cmd, name ) {
  21965. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  21966. return tableNode && validData( tableNode ) ? 0 : -1;
  21967. }
  21968. }
  21969. },
  21970. inputRule:function(root){
  21971. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21972. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21973. tableNode.setAttr("style");
  21974. }
  21975. })
  21976. },
  21977. outputRule:function(root){
  21978. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21979. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21980. tableNode.setAttr("style", "display: none;");
  21981. }
  21982. })
  21983. }
  21984. }
  21985. function validData ( table ) {
  21986. var firstRows = null,
  21987. cellCount = 0;
  21988. //行数不够
  21989. if ( table.rows.length < 2 ) {
  21990. return false;
  21991. }
  21992. //列数不够
  21993. if ( table.rows[0].cells.length < 2 ) {
  21994. return false;
  21995. }
  21996. //第一行所有cell必须是th
  21997. firstRows = table.rows[ 0 ].cells;
  21998. cellCount = firstRows.length;
  21999. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22000. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22001. return false;
  22002. }
  22003. }
  22004. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22005. //每行单元格数不匹配, 返回false
  22006. if ( row.cells.length != cellCount ) {
  22007. return false;
  22008. }
  22009. //第一列不是th也返回false
  22010. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22011. return false;
  22012. }
  22013. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22014. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22015. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22016. //必须是数字
  22017. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22018. return false;
  22019. }
  22020. }
  22021. }
  22022. return true;
  22023. }
  22024. });
  22025. // plugins/section.js
  22026. /**
  22027. * 目录大纲支持插件
  22028. * @file
  22029. * @since 1.3.0
  22030. */
  22031. UE.plugin.register('section', function (){
  22032. /* 目录节点对象 */
  22033. function Section(option){
  22034. this.tag = '';
  22035. this.level = -1,
  22036. this.dom = null;
  22037. this.nextSection = null;
  22038. this.previousSection = null;
  22039. this.parentSection = null;
  22040. this.startAddress = [];
  22041. this.endAddress = [];
  22042. this.children = [];
  22043. }
  22044. function getSection(option) {
  22045. var section = new Section();
  22046. return utils.extend(section, option);
  22047. }
  22048. function getNodeFromAddress(startAddress, root) {
  22049. var current = root;
  22050. for(var i = 0;i < startAddress.length; i++) {
  22051. if(!current.childNodes) return null;
  22052. current = current.childNodes[startAddress[i]];
  22053. }
  22054. return current;
  22055. }
  22056. var me = this;
  22057. return {
  22058. bindMultiEvents:{
  22059. type: 'aftersetcontent afterscencerestore',
  22060. handler: function(){
  22061. me.fireEvent('updateSections');
  22062. }
  22063. },
  22064. bindEvents:{
  22065. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22066. 'ready': function (){
  22067. me.fireEvent('updateSections');
  22068. domUtils.on(me.body, 'drop paste', function(){
  22069. me.fireEvent('updateSections');
  22070. });
  22071. },
  22072. /* 执行paragraph命令之后 */
  22073. 'afterexeccommand': function (type, cmd) {
  22074. if(cmd == 'paragraph') {
  22075. me.fireEvent('updateSections');
  22076. }
  22077. },
  22078. /* 部分键盘操作,触发updateSections事件 */
  22079. 'keyup': function (type, e) {
  22080. var me = this,
  22081. range = me.selection.getRange();
  22082. if(range.collapsed != true) {
  22083. me.fireEvent('updateSections');
  22084. } else {
  22085. var keyCode = e.keyCode || e.which;
  22086. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22087. me.fireEvent('updateSections');
  22088. }
  22089. }
  22090. }
  22091. },
  22092. commands:{
  22093. 'getsections': {
  22094. execCommand: function (cmd, levels) {
  22095. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22096. for (var i = 0; i < levelFn.length; i++) {
  22097. if (typeof levelFn[i] == 'string') {
  22098. levelFn[i] = function(fn){
  22099. return function(node){
  22100. return node.tagName == fn.toUpperCase()
  22101. };
  22102. }(levelFn[i]);
  22103. } else if (typeof levelFn[i] != 'function') {
  22104. levelFn[i] = function (node) {
  22105. return null;
  22106. }
  22107. }
  22108. }
  22109. function getSectionLevel(node) {
  22110. for (var i = 0; i < levelFn.length; i++) {
  22111. if (levelFn[i](node)) return i;
  22112. }
  22113. return -1;
  22114. }
  22115. var me = this,
  22116. Directory = getSection({'level':-1, 'title':'root'}),
  22117. previous = Directory;
  22118. function traversal(node, Directory) {
  22119. var level,
  22120. tmpSection = null,
  22121. parent,
  22122. child,
  22123. children = node.childNodes;
  22124. for (var i = 0, len = children.length; i < len; i++) {
  22125. child = children[i];
  22126. level = getSectionLevel(child);
  22127. if (level >= 0) {
  22128. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22129. current = getSection({
  22130. 'tag': child.tagName,
  22131. 'title': child.innerText || child.textContent || '',
  22132. 'level': level,
  22133. 'dom': child,
  22134. 'startAddress': utils.clone(address, []),
  22135. 'endAddress': utils.clone(address, []),
  22136. 'children': []
  22137. });
  22138. previous.nextSection = current;
  22139. current.previousSection = previous;
  22140. parent = previous;
  22141. while(level <= parent.level){
  22142. parent = parent.parentSection;
  22143. }
  22144. current.parentSection = parent;
  22145. parent.children.push(current);
  22146. tmpSection = previous = current;
  22147. } else {
  22148. child.nodeType === 1 && traversal(child, Directory);
  22149. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22150. }
  22151. }
  22152. }
  22153. traversal(me.body, Directory);
  22154. return Directory;
  22155. },
  22156. notNeedUndo: true
  22157. },
  22158. 'movesection': {
  22159. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22160. var me = this,
  22161. targetAddress,
  22162. target;
  22163. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22164. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22165. target = getNodeFromAddress(targetAddress, me.body);
  22166. /* 判断目标地址是否被源章节包含 */
  22167. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22168. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22169. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22170. current,
  22171. nextNode;
  22172. if(isAfter) {
  22173. current = endNode;
  22174. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22175. nextNode = current.previousSibling;
  22176. domUtils.insertAfter(target, current);
  22177. if(current == startNode) break;
  22178. current = nextNode;
  22179. }
  22180. } else {
  22181. current = startNode;
  22182. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22183. nextNode = current.nextSibling;
  22184. target.parentNode.insertBefore(current, target);
  22185. if(current == endNode) break;
  22186. current = nextNode;
  22187. }
  22188. }
  22189. me.fireEvent('updateSections');
  22190. /* 获取地址的包含关系 */
  22191. function isContainsAddress(startAddress, endAddress, addressTarget){
  22192. var isAfterStartAddress = false,
  22193. isBeforeEndAddress = false;
  22194. for(var i = 0; i< startAddress.length; i++){
  22195. if(i >= addressTarget.length) break;
  22196. if(addressTarget[i] > startAddress[i]) {
  22197. isAfterStartAddress = true;
  22198. break;
  22199. } else if(addressTarget[i] < startAddress[i]) {
  22200. break;
  22201. }
  22202. }
  22203. for(var i = 0; i< endAddress.length; i++){
  22204. if(i >= addressTarget.length) break;
  22205. if(addressTarget[i] < startAddress[i]) {
  22206. isBeforeEndAddress = true;
  22207. break;
  22208. } else if(addressTarget[i] > startAddress[i]) {
  22209. break;
  22210. }
  22211. }
  22212. return isAfterStartAddress && isBeforeEndAddress;
  22213. }
  22214. }
  22215. },
  22216. 'deletesection': {
  22217. execCommand: function (cmd, section, keepChildren) {
  22218. var me = this;
  22219. if(!section) return;
  22220. function getNodeFromAddress(startAddress) {
  22221. var current = me.body;
  22222. for(var i = 0;i < startAddress.length; i++) {
  22223. if(!current.childNodes) return null;
  22224. current = current.childNodes[startAddress[i]];
  22225. }
  22226. return current;
  22227. }
  22228. var startNode = getNodeFromAddress(section.startAddress),
  22229. endNode = getNodeFromAddress(section.endAddress),
  22230. current = startNode,
  22231. nextNode;
  22232. if(!keepChildren) {
  22233. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22234. nextNode = current.nextSibling;
  22235. domUtils.remove(current);
  22236. current = nextNode;
  22237. }
  22238. } else {
  22239. domUtils.remove(current);
  22240. }
  22241. me.fireEvent('updateSections');
  22242. }
  22243. },
  22244. 'selectsection': {
  22245. execCommand: function (cmd, section) {
  22246. if(!section && !section.dom) return false;
  22247. var me = this,
  22248. range = me.selection.getRange(),
  22249. address = {
  22250. 'startAddress':utils.clone(section.startAddress, []),
  22251. 'endAddress':utils.clone(section.endAddress, [])
  22252. };
  22253. address.endAddress[address.endAddress.length - 1]++;
  22254. range.moveToAddress(address).select().scrollToView();
  22255. return true;
  22256. },
  22257. notNeedUndo: true
  22258. },
  22259. 'scrolltosection': {
  22260. execCommand: function (cmd, section) {
  22261. if(!section && !section.dom) return false;
  22262. var me = this,
  22263. range = me.selection.getRange(),
  22264. address = {
  22265. 'startAddress':section.startAddress,
  22266. 'endAddress':section.endAddress
  22267. };
  22268. address.endAddress[address.endAddress.length - 1]++;
  22269. range.moveToAddress(address).scrollToView();
  22270. return true;
  22271. },
  22272. notNeedUndo: true
  22273. }
  22274. }
  22275. }
  22276. });
  22277. // plugins/simpleupload.js
  22278. /**
  22279. * @description
  22280. * 简单上传:点击按钮,直接选择文件上传
  22281. * @author Jinqn
  22282. * @date 2014-03-31
  22283. */
  22284. UE.plugin.register('simpleupload', function (){
  22285. var me = this,
  22286. isLoaded = false,
  22287. containerBtn;
  22288. function initUploadBtn(){
  22289. var timestrap = (+new Date()).toString(36),
  22290. doc = containerBtn.ownerDocument,
  22291. wrapper = document.createElement('div');
  22292. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22293. 'style="display:block;width:100%;height:100%;border:0;margin:0;padding:0;position:absolute;">' +
  22294. '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
  22295. 'style="background:red;display:block;width:100%;height:100%;border:0;margin:0;padding:0;position:absolute;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;">' +
  22296. '</form>' +
  22297. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" ' +
  22298. 'style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22299. wrapper.className = 'edui-' + me.options.theme;
  22300. wrapper.id = me.ui.id + '_iframeupload';
  22301. containerBtn.appendChild(wrapper);
  22302. var form = doc.getElementById('edui_form_' + timestrap);
  22303. var input = doc.getElementById('edui_input_' + timestrap);
  22304. var iframe = doc.getElementById('edui_iframe_' + timestrap);
  22305. domUtils.on(input, 'change', function(){
  22306. if(!input.value) return;
  22307. var loadingId = 'loading_' + (+new Date()).toString(36);
  22308. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22309. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22310. var allowFiles = me.getOpt('imageAllowFiles');
  22311. me.focus();
  22312. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22313. function callback(){
  22314. try{
  22315. var link, json, loader,
  22316. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22317. result = body.innerText || body.textContent || '';
  22318. json = (new Function("return " + result))();
  22319. link = me.options.imageUrlPrefix + json.url;
  22320. if(json.state == 'SUCCESS' && json.url) {
  22321. loader = me.document.getElementById(loadingId);
  22322. loader.setAttribute('src', link);
  22323. loader.setAttribute('_src', link);
  22324. loader.setAttribute('title', json.title || '');
  22325. loader.setAttribute('alt', json.original || '');
  22326. loader.removeAttribute('id');
  22327. domUtils.removeClasses(loader, 'loadingclass');
  22328. } else {
  22329. showErrorLoader && showErrorLoader(json.state);
  22330. }
  22331. }catch(er){
  22332. showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
  22333. }
  22334. form.reset();
  22335. domUtils.un(iframe, 'load', callback);
  22336. }
  22337. function showErrorLoader(title){
  22338. if(loadingId) {
  22339. var loader = me.document.getElementById(loadingId);
  22340. domUtils.removeClasses(loader, 'loadingclass');
  22341. domUtils.addClass(loader, 'loaderrorclass');
  22342. loader.setAttribute('title', title || '');
  22343. }
  22344. }
  22345. // 判断文件格式是否错误
  22346. var filename = input.value,
  22347. fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22348. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22349. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22350. return;
  22351. }
  22352. domUtils.on(iframe, 'load', callback);
  22353. form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22354. form.submit();
  22355. });
  22356. var stateTimer;
  22357. me.addListener('selectionchange', function () {
  22358. clearTimeout(stateTimer);
  22359. stateTimer = setTimeout(function() {
  22360. var state = me.queryCommandState('simpleupload');
  22361. if (state == -1) {
  22362. input.disabled = 'disabled';
  22363. } else {
  22364. input.disabled = false;
  22365. }
  22366. }, 400);
  22367. });
  22368. isLoaded = true;
  22369. }
  22370. return {
  22371. bindEvents:{
  22372. 'ready': function() {
  22373. //设置loading的样式
  22374. utils.cssRule('loading',
  22375. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22376. + this.options.themePath
  22377. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22378. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22379. + this.options.themePath
  22380. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22381. '}',
  22382. this.document);
  22383. },
  22384. /* 初始化简单上传按钮 */
  22385. 'simpleuploadbtnready': function(type, container) {
  22386. containerBtn = container;
  22387. me.afterConfigReady(initUploadBtn);
  22388. }
  22389. },
  22390. outputRule: function(root){
  22391. utils.each(root.getNodesByTagName('img'),function(n){
  22392. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22393. n.parentNode.removeChild(n);
  22394. }
  22395. });
  22396. },
  22397. commands: {
  22398. 'simpleupload': {
  22399. queryCommandState: function () {
  22400. return isLoaded ? 0:-1;
  22401. }
  22402. }
  22403. }
  22404. }
  22405. });
  22406. // plugins/serverparam.js
  22407. /**
  22408. * 服务器提交的额外参数列表设置插件
  22409. * @file
  22410. * @since 1.2.6.1
  22411. */
  22412. UE.plugin.register('serverparam', function (){
  22413. var me = this,
  22414. serverParam = {};
  22415. return {
  22416. commands:{
  22417. /**
  22418. * 修改服务器提交的额外参数列表,清除所有项
  22419. * @command serverparam
  22420. * @method execCommand
  22421. * @param { String } cmd 命令字符串
  22422. * @example
  22423. * ```javascript
  22424. * editor.execCommand('serverparam');
  22425. * editor.queryCommandValue('serverparam'); //返回空
  22426. * ```
  22427. */
  22428. /**
  22429. * 修改服务器提交的额外参数列表,删除指定项
  22430. * @command serverparam
  22431. * @method execCommand
  22432. * @param { String } cmd 命令字符串
  22433. * @param { String } key 要清除的属性
  22434. * @example
  22435. * ```javascript
  22436. * editor.execCommand('serverparam', 'name'); //删除属性name
  22437. * ```
  22438. */
  22439. /**
  22440. * 修改服务器提交的额外参数列表,使用键值添加项
  22441. * @command serverparam
  22442. * @method execCommand
  22443. * @param { String } cmd 命令字符串
  22444. * @param { String } key 要添加的属性
  22445. * @param { String } value 要添加属性的值
  22446. * @example
  22447. * ```javascript
  22448. * editor.execCommand('serverparam', 'name', 'hello');
  22449. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22450. * ```
  22451. */
  22452. /**
  22453. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22454. * @command serverparam
  22455. * @method execCommand
  22456. * @param { String } cmd 命令字符串
  22457. * @param { Object } key 传入的键值对对象
  22458. * @example
  22459. * ```javascript
  22460. * editor.execCommand('serverparam', {'name': 'hello'});
  22461. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22462. * ```
  22463. */
  22464. /**
  22465. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22466. * @command serverparam
  22467. * @method execCommand
  22468. * @param { String } cmd 命令字符串
  22469. * @param { Function } key 自定义获取参数的函数
  22470. * @example
  22471. * ```javascript
  22472. * editor.execCommand('serverparam', function(editor){
  22473. * return {'key': 'value'};
  22474. * });
  22475. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22476. * ```
  22477. */
  22478. /**
  22479. * 获取服务器提交的额外参数列表
  22480. * @command serverparam
  22481. * @method queryCommandValue
  22482. * @param { String } cmd 命令字符串
  22483. * @example
  22484. * ```javascript
  22485. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22486. * ```
  22487. */
  22488. 'serverparam':{
  22489. execCommand:function (cmd, key, value) {
  22490. if (key === undefined || key === null) { //不传参数,清空列表
  22491. serverParam = {};
  22492. } else if (utils.isString(key)) { //传入键值
  22493. if(value === undefined || value === null) {
  22494. delete serverParam[key];
  22495. } else {
  22496. serverParam[key] = value;
  22497. }
  22498. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22499. utils.extend(serverParam, key, true);
  22500. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22501. utils.extend(serverParam, key(), true);
  22502. }
  22503. },
  22504. queryCommandValue: function(){
  22505. return serverParam || {};
  22506. }
  22507. }
  22508. }
  22509. }
  22510. });
  22511. // plugins/insertfile.js
  22512. /**
  22513. * 插入附件
  22514. */
  22515. UE.plugin.register('insertfile', function (){
  22516. var me = this;
  22517. function getFileIcon(url){
  22518. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22519. maps = {
  22520. "rar":"icon_rar.gif",
  22521. "zip":"icon_rar.gif",
  22522. "tar":"icon_rar.gif",
  22523. "gz":"icon_rar.gif",
  22524. "bz2":"icon_rar.gif",
  22525. "doc":"icon_doc.gif",
  22526. "docx":"icon_doc.gif",
  22527. "pdf":"icon_pdf.gif",
  22528. "mp3":"icon_mp3.gif",
  22529. "xls":"icon_xls.gif",
  22530. "chm":"icon_chm.gif",
  22531. "ppt":"icon_ppt.gif",
  22532. "pptx":"icon_ppt.gif",
  22533. "avi":"icon_mv.gif",
  22534. "rmvb":"icon_mv.gif",
  22535. "wmv":"icon_mv.gif",
  22536. "flv":"icon_mv.gif",
  22537. "swf":"icon_mv.gif",
  22538. "rm":"icon_mv.gif",
  22539. "exe":"icon_exe.gif",
  22540. "psd":"icon_psd.gif",
  22541. "txt":"icon_txt.gif",
  22542. "jpg":"icon_jpg.gif",
  22543. "png":"icon_jpg.gif",
  22544. "jpeg":"icon_jpg.gif",
  22545. "gif":"icon_jpg.gif",
  22546. "ico":"icon_jpg.gif",
  22547. "bmp":"icon_jpg.gif"
  22548. };
  22549. return maps[ext] ? maps[ext]:maps['txt'];
  22550. }
  22551. return {
  22552. commands:{
  22553. 'insertfile': {
  22554. execCommand: function (command, filelist){
  22555. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22556. var i, item, icon, title,
  22557. html = '',
  22558. URL = me.getOpt('UEDITOR_HOME_URL'),
  22559. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22560. for (i = 0; i < filelist.length; i++) {
  22561. item = filelist[i];
  22562. icon = iconDir + getFileIcon(item.url);
  22563. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22564. html += '<p style="line-height: 16px;">' +
  22565. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22566. '<a style="font-size:12px; color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22567. '</p>';
  22568. }
  22569. me.execCommand('insertHtml', html);
  22570. }
  22571. }
  22572. }
  22573. }
  22574. });
  22575. // ui/ui.js
  22576. var baidu = baidu || {};
  22577. baidu.editor = baidu.editor || {};
  22578. UE.ui = baidu.editor.ui = {};
  22579. // ui/uiutils.js
  22580. (function (){
  22581. var browser = baidu.editor.browser,
  22582. domUtils = baidu.editor.dom.domUtils;
  22583. var magic = '$EDITORUI';
  22584. var root = window[magic] = {};
  22585. var uidMagic = 'ID' + magic;
  22586. var uidCount = 0;
  22587. var uiUtils = baidu.editor.ui.uiUtils = {
  22588. uid: function (obj){
  22589. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22590. },
  22591. hook: function ( fn, callback ) {
  22592. var dg;
  22593. if (fn && fn._callbacks) {
  22594. dg = fn;
  22595. } else {
  22596. dg = function (){
  22597. var q;
  22598. if (fn) {
  22599. q = fn.apply(this, arguments);
  22600. }
  22601. var callbacks = dg._callbacks;
  22602. var k = callbacks.length;
  22603. while (k --) {
  22604. var r = callbacks[k].apply(this, arguments);
  22605. if (q === undefined) {
  22606. q = r;
  22607. }
  22608. }
  22609. return q;
  22610. };
  22611. dg._callbacks = [];
  22612. }
  22613. dg._callbacks.push(callback);
  22614. return dg;
  22615. },
  22616. createElementByHtml: function (html){
  22617. var el = document.createElement('div');
  22618. el.innerHTML = html;
  22619. el = el.firstChild;
  22620. el.parentNode.removeChild(el);
  22621. return el;
  22622. },
  22623. getViewportElement: function (){
  22624. return (browser.ie && browser.quirks) ?
  22625. document.body : document.documentElement;
  22626. },
  22627. getClientRect: function (element){
  22628. var bcr;
  22629. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22630. try{
  22631. bcr = element.getBoundingClientRect();
  22632. }catch(e){
  22633. bcr={left:0,top:0,height:0,width:0}
  22634. }
  22635. var rect = {
  22636. left: Math.round(bcr.left),
  22637. top: Math.round(bcr.top),
  22638. height: Math.round(bcr.bottom - bcr.top),
  22639. width: Math.round(bcr.right - bcr.left)
  22640. };
  22641. var doc;
  22642. while ((doc = element.ownerDocument) !== document &&
  22643. (element = domUtils.getWindow(doc).frameElement)) {
  22644. bcr = element.getBoundingClientRect();
  22645. rect.left += bcr.left;
  22646. rect.top += bcr.top;
  22647. }
  22648. rect.bottom = rect.top + rect.height;
  22649. rect.right = rect.left + rect.width;
  22650. return rect;
  22651. },
  22652. getViewportRect: function (){
  22653. var viewportEl = uiUtils.getViewportElement();
  22654. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22655. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22656. return {
  22657. left: 0,
  22658. top: 0,
  22659. height: height,
  22660. width: width,
  22661. bottom: height,
  22662. right: width
  22663. };
  22664. },
  22665. setViewportOffset: function (element, offset){
  22666. var rect;
  22667. var fixedLayer = uiUtils.getFixedLayer();
  22668. if (element.parentNode === fixedLayer) {
  22669. element.style.left = offset.left + 'px';
  22670. element.style.top = offset.top + 'px';
  22671. } else {
  22672. domUtils.setViewportOffset(element, offset);
  22673. }
  22674. },
  22675. getEventOffset: function (evt){
  22676. var el = evt.target || evt.srcElement;
  22677. var rect = uiUtils.getClientRect(el);
  22678. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22679. return {
  22680. left: offset.left - rect.left,
  22681. top: offset.top - rect.top
  22682. };
  22683. },
  22684. getViewportOffsetByEvent: function (evt){
  22685. var el = evt.target || evt.srcElement;
  22686. var frameEl = domUtils.getWindow(el).frameElement;
  22687. var offset = {
  22688. left: evt.clientX,
  22689. top: evt.clientY
  22690. };
  22691. if (frameEl && el.ownerDocument !== document) {
  22692. var rect = uiUtils.getClientRect(frameEl);
  22693. offset.left += rect.left;
  22694. offset.top += rect.top;
  22695. }
  22696. return offset;
  22697. },
  22698. setGlobal: function (id, obj){
  22699. root[id] = obj;
  22700. return magic + '["' + id + '"]';
  22701. },
  22702. unsetGlobal: function (id){
  22703. delete root[id];
  22704. },
  22705. copyAttributes: function (tgt, src){
  22706. var attributes = src.attributes;
  22707. var k = attributes.length;
  22708. while (k --) {
  22709. var attrNode = attributes[k];
  22710. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22711. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22712. }
  22713. }
  22714. if (src.className) {
  22715. domUtils.addClass(tgt,src.className);
  22716. }
  22717. if (src.style.cssText) {
  22718. tgt.style.cssText += ';' + src.style.cssText;
  22719. }
  22720. },
  22721. removeStyle: function (el, styleName){
  22722. if (el.style.removeProperty) {
  22723. el.style.removeProperty(styleName);
  22724. } else if (el.style.removeAttribute) {
  22725. el.style.removeAttribute(styleName);
  22726. } else throw '';
  22727. },
  22728. contains: function (elA, elB){
  22729. return elA && elB && (elA === elB ? false : (
  22730. elA.contains ? elA.contains(elB) :
  22731. elA.compareDocumentPosition(elB) & 16
  22732. ));
  22733. },
  22734. startDrag: function (evt, callbacks,doc){
  22735. var doc = doc || document;
  22736. var startX = evt.clientX;
  22737. var startY = evt.clientY;
  22738. function handleMouseMove(evt){
  22739. var x = evt.clientX - startX;
  22740. var y = evt.clientY - startY;
  22741. callbacks.ondragmove(x, y,evt);
  22742. if (evt.stopPropagation) {
  22743. evt.stopPropagation();
  22744. } else {
  22745. evt.cancelBubble = true;
  22746. }
  22747. }
  22748. if (doc.addEventListener) {
  22749. function handleMouseUp(evt){
  22750. doc.removeEventListener('mousemove', handleMouseMove, true);
  22751. doc.removeEventListener('mouseup', handleMouseUp, true);
  22752. window.removeEventListener('mouseup', handleMouseUp, true);
  22753. callbacks.ondragstop();
  22754. }
  22755. doc.addEventListener('mousemove', handleMouseMove, true);
  22756. doc.addEventListener('mouseup', handleMouseUp, true);
  22757. window.addEventListener('mouseup', handleMouseUp, true);
  22758. evt.preventDefault();
  22759. } else {
  22760. var elm = evt.srcElement;
  22761. elm.setCapture();
  22762. function releaseCaptrue(){
  22763. elm.releaseCapture();
  22764. elm.detachEvent('onmousemove', handleMouseMove);
  22765. elm.detachEvent('onmouseup', releaseCaptrue);
  22766. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  22767. callbacks.ondragstop();
  22768. }
  22769. elm.attachEvent('onmousemove', handleMouseMove);
  22770. elm.attachEvent('onmouseup', releaseCaptrue);
  22771. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  22772. evt.returnValue = false;
  22773. }
  22774. callbacks.ondragstart();
  22775. },
  22776. getFixedLayer: function (){
  22777. var layer = document.getElementById('edui_fixedlayer');
  22778. if (layer == null) {
  22779. layer = document.createElement('div');
  22780. layer.id = 'edui_fixedlayer';
  22781. document.body.appendChild(layer);
  22782. if (browser.ie && browser.version <= 8) {
  22783. layer.style.position = 'absolute';
  22784. bindFixedLayer();
  22785. setTimeout(updateFixedOffset);
  22786. } else {
  22787. layer.style.position = 'fixed';
  22788. }
  22789. layer.style.left = '0';
  22790. layer.style.top = '0';
  22791. layer.style.width = '0';
  22792. layer.style.height = '0';
  22793. }
  22794. return layer;
  22795. },
  22796. makeUnselectable: function (element){
  22797. if (browser.opera || (browser.ie && browser.version < 9)) {
  22798. element.unselectable = 'on';
  22799. if (element.hasChildNodes()) {
  22800. for (var i=0; i<element.childNodes.length; i++) {
  22801. if (element.childNodes[i].nodeType == 1) {
  22802. uiUtils.makeUnselectable(element.childNodes[i]);
  22803. }
  22804. }
  22805. }
  22806. } else {
  22807. if (element.style.MozUserSelect !== undefined) {
  22808. element.style.MozUserSelect = 'none';
  22809. } else if (element.style.WebkitUserSelect !== undefined) {
  22810. element.style.WebkitUserSelect = 'none';
  22811. } else if (element.style.KhtmlUserSelect !== undefined) {
  22812. element.style.KhtmlUserSelect = 'none';
  22813. }
  22814. }
  22815. }
  22816. };
  22817. function updateFixedOffset(){
  22818. var layer = document.getElementById('edui_fixedlayer');
  22819. uiUtils.setViewportOffset(layer, {
  22820. left: 0,
  22821. top: 0
  22822. });
  22823. // layer.style.display = 'none';
  22824. // layer.style.display = 'block';
  22825. //#trace: 1354
  22826. // setTimeout(updateFixedOffset);
  22827. }
  22828. function bindFixedLayer(adjOffset){
  22829. domUtils.on(window, 'scroll', updateFixedOffset);
  22830. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  22831. }
  22832. })();
  22833. // ui/uibase.js
  22834. (function () {
  22835. var utils = baidu.editor.utils,
  22836. uiUtils = baidu.editor.ui.uiUtils,
  22837. EventBase = baidu.editor.EventBase,
  22838. UIBase = baidu.editor.ui.UIBase = function () {
  22839. };
  22840. UIBase.prototype = {
  22841. className:'',
  22842. uiName:'',
  22843. initOptions:function (options) {
  22844. var me = this;
  22845. for (var k in options) {
  22846. me[k] = options[k];
  22847. }
  22848. this.id = this.id || 'edui' + uiUtils.uid();
  22849. },
  22850. initUIBase:function () {
  22851. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  22852. },
  22853. render:function (holder) {
  22854. var html = this.renderHtml();
  22855. var el = uiUtils.createElementByHtml(html);
  22856. //by xuheng 给每个node添加class
  22857. var list = domUtils.getElementsByTagName(el, "*");
  22858. var theme = "edui-" + (this.theme || this.editor.options.theme);
  22859. var layer = document.getElementById('edui_fixedlayer');
  22860. for (var i = 0, node; node = list[i++];) {
  22861. domUtils.addClass(node, theme);
  22862. }
  22863. domUtils.addClass(el, theme);
  22864. if(layer){
  22865. layer.className="";
  22866. domUtils.addClass(layer,theme);
  22867. }
  22868. var seatEl = this.getDom();
  22869. if (seatEl != null) {
  22870. seatEl.parentNode.replaceChild(el, seatEl);
  22871. uiUtils.copyAttributes(el, seatEl);
  22872. } else {
  22873. if (typeof holder == 'string') {
  22874. holder = document.getElementById(holder);
  22875. }
  22876. holder = holder || uiUtils.getFixedLayer();
  22877. domUtils.addClass(holder, theme);
  22878. holder.appendChild(el);
  22879. }
  22880. this.postRender();
  22881. },
  22882. getDom:function (name) {
  22883. if (!name) {
  22884. return document.getElementById(this.id);
  22885. } else {
  22886. return document.getElementById(this.id + '_' + name);
  22887. }
  22888. },
  22889. postRender:function () {
  22890. this.fireEvent('postrender');
  22891. },
  22892. getHtmlTpl:function () {
  22893. return '';
  22894. },
  22895. formatHtml:function (tpl) {
  22896. var prefix = 'edui-' + this.uiName;
  22897. return (tpl
  22898. .replace(/##/g, this.id)
  22899. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  22900. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  22901. .replace(/\$\$/g, this._globalKey));
  22902. },
  22903. renderHtml:function () {
  22904. return this.formatHtml(this.getHtmlTpl());
  22905. },
  22906. dispose:function () {
  22907. var box = this.getDom();
  22908. if (box) baidu.editor.dom.domUtils.remove(box);
  22909. uiUtils.unsetGlobal(this.id);
  22910. }
  22911. };
  22912. utils.inherits(UIBase, EventBase);
  22913. })();
  22914. // ui/separator.js
  22915. (function (){
  22916. var utils = baidu.editor.utils,
  22917. UIBase = baidu.editor.ui.UIBase,
  22918. Separator = baidu.editor.ui.Separator = function (options){
  22919. this.initOptions(options);
  22920. this.initSeparator();
  22921. };
  22922. Separator.prototype = {
  22923. uiName: 'separator',
  22924. initSeparator: function (){
  22925. this.initUIBase();
  22926. },
  22927. getHtmlTpl: function (){
  22928. return '<div id="##" class="edui-box %%"></div>';
  22929. }
  22930. };
  22931. utils.inherits(Separator, UIBase);
  22932. })();
  22933. // ui/mask.js
  22934. ///import core
  22935. ///import uicore
  22936. (function (){
  22937. var utils = baidu.editor.utils,
  22938. domUtils = baidu.editor.dom.domUtils,
  22939. UIBase = baidu.editor.ui.UIBase,
  22940. uiUtils = baidu.editor.ui.uiUtils;
  22941. var Mask = baidu.editor.ui.Mask = function (options){
  22942. this.initOptions(options);
  22943. this.initUIBase();
  22944. };
  22945. Mask.prototype = {
  22946. getHtmlTpl: function (){
  22947. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  22948. },
  22949. postRender: function (){
  22950. var me = this;
  22951. domUtils.on(window, 'resize', function (){
  22952. setTimeout(function (){
  22953. if (!me.isHidden()) {
  22954. me._fill();
  22955. }
  22956. });
  22957. });
  22958. },
  22959. show: function (zIndex){
  22960. this._fill();
  22961. this.getDom().style.display = '';
  22962. this.getDom().style.zIndex = zIndex;
  22963. },
  22964. hide: function (){
  22965. this.getDom().style.display = 'none';
  22966. this.getDom().style.zIndex = '';
  22967. },
  22968. isHidden: function (){
  22969. return this.getDom().style.display == 'none';
  22970. },
  22971. _onMouseDown: function (){
  22972. return false;
  22973. },
  22974. _onClick: function (e, target){
  22975. this.fireEvent('click', e, target);
  22976. },
  22977. _fill: function (){
  22978. var el = this.getDom();
  22979. var vpRect = uiUtils.getViewportRect();
  22980. el.style.width = vpRect.width + 'px';
  22981. el.style.height = vpRect.height + 'px';
  22982. }
  22983. };
  22984. utils.inherits(Mask, UIBase);
  22985. })();
  22986. // ui/popup.js
  22987. ///import core
  22988. ///import uicore
  22989. (function () {
  22990. var utils = baidu.editor.utils,
  22991. uiUtils = baidu.editor.ui.uiUtils,
  22992. domUtils = baidu.editor.dom.domUtils,
  22993. UIBase = baidu.editor.ui.UIBase,
  22994. Popup = baidu.editor.ui.Popup = function (options){
  22995. this.initOptions(options);
  22996. this.initPopup();
  22997. };
  22998. var allPopups = [];
  22999. function closeAllPopup( evt,el ){
  23000. for ( var i = 0; i < allPopups.length; i++ ) {
  23001. var pop = allPopups[i];
  23002. if (!pop.isHidden()) {
  23003. if (pop.queryAutoHide(el) !== false) {
  23004. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23005. pop.hide();
  23006. }
  23007. }
  23008. }
  23009. if(allPopups.length)
  23010. pop.editor.fireEvent("afterhidepop");
  23011. }
  23012. Popup.postHide = closeAllPopup;
  23013. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23014. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23015. Popup.prototype = {
  23016. SHADOW_RADIUS: 5,
  23017. content: null,
  23018. _hidden: false,
  23019. autoRender: true,
  23020. canSideLeft: true,
  23021. canSideUp: true,
  23022. initPopup: function (){
  23023. this.initUIBase();
  23024. allPopups.push( this );
  23025. },
  23026. getHtmlTpl: function (){
  23027. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23028. ' <div id="##_body" class="edui-popup-body">' +
  23029. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23030. ' <div class="edui-shadow"></div>' +
  23031. ' <div id="##_content" class="edui-popup-content">' +
  23032. this.getContentHtmlTpl() +
  23033. ' </div>' +
  23034. ' </div>' +
  23035. '</div>';
  23036. },
  23037. getContentHtmlTpl: function (){
  23038. if(this.content){
  23039. if (typeof this.content == 'string') {
  23040. return this.content;
  23041. }
  23042. return this.content.renderHtml();
  23043. }else{
  23044. return ''
  23045. }
  23046. },
  23047. _UIBase_postRender: UIBase.prototype.postRender,
  23048. postRender: function (){
  23049. if (this.content instanceof UIBase) {
  23050. this.content.postRender();
  23051. }
  23052. //捕获鼠标滚轮
  23053. if( this.captureWheel && !this.captured ) {
  23054. this.captured = true;
  23055. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23056. _height = this.getDom().offsetHeight,
  23057. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23058. content = this.getDom('content'),
  23059. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23060. me = this;
  23061. ifr.length && ( ifr = ifr[0] );
  23062. while( _top + _height > winHeight ) {
  23063. _height -= 30;
  23064. }
  23065. content.style.height = _height + 'px';
  23066. //同步更改iframe高度
  23067. ifr && ( ifr.style.height = _height + 'px' );
  23068. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23069. if( window.XMLHttpRequest ) {
  23070. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23071. if(e.preventDefault) {
  23072. e.preventDefault();
  23073. } else {
  23074. e.returnValue = false;
  23075. }
  23076. if( e.wheelDelta ) {
  23077. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23078. } else {
  23079. content.scrollTop -= ( e.detail / -3 )*60;
  23080. }
  23081. });
  23082. } else {
  23083. //ie6
  23084. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23085. e.returnValue = false;
  23086. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23087. });
  23088. }
  23089. }
  23090. this.fireEvent('postRenderAfter');
  23091. this.hide(true);
  23092. this._UIBase_postRender();
  23093. },
  23094. _doAutoRender: function (){
  23095. if (!this.getDom() && this.autoRender) {
  23096. this.render();
  23097. }
  23098. },
  23099. mesureSize: function (){
  23100. var box = this.getDom('content');
  23101. return uiUtils.getClientRect(box);
  23102. },
  23103. fitSize: function (){
  23104. if( this.captureWheel && this.sized ) {
  23105. return this.__size;
  23106. }
  23107. this.sized = true;
  23108. var popBodyEl = this.getDom('body');
  23109. popBodyEl.style.width = '';
  23110. popBodyEl.style.height = '';
  23111. var size = this.mesureSize();
  23112. if( this.captureWheel ) {
  23113. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23114. var height = parseInt( this.getDom('content').style.height, 10 );
  23115. !window.isNaN( height ) && ( size.height = height );
  23116. } else {
  23117. popBodyEl.style.width = size.width + 'px';
  23118. }
  23119. popBodyEl.style.height = size.height + 'px';
  23120. this.__size = size;
  23121. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23122. return size;
  23123. },
  23124. showAnchor: function ( element, hoz ){
  23125. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23126. },
  23127. showAnchorRect: function ( rect, hoz, adj ){
  23128. this._doAutoRender();
  23129. var vpRect = uiUtils.getViewportRect();
  23130. this.getDom().style.visibility = 'hidden';
  23131. this._show();
  23132. var popSize = this.fitSize();
  23133. var sideLeft, sideUp, left, top;
  23134. if (hoz) {
  23135. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23136. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23137. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23138. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23139. } else {
  23140. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23141. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23142. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23143. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23144. }
  23145. var popEl = this.getDom();
  23146. uiUtils.setViewportOffset(popEl, {
  23147. left: left,
  23148. top: top
  23149. });
  23150. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23151. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23152. if(this.editor){
  23153. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23154. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23155. }
  23156. this.getDom().style.visibility = 'visible';
  23157. },
  23158. showAt: function (offset) {
  23159. var left = offset.left;
  23160. var top = offset.top;
  23161. var rect = {
  23162. left: left,
  23163. top: top,
  23164. right: left,
  23165. bottom: top,
  23166. height: 0,
  23167. width: 0
  23168. };
  23169. this.showAnchorRect(rect, false, true);
  23170. },
  23171. _show: function (){
  23172. if (this._hidden) {
  23173. var box = this.getDom();
  23174. box.style.display = '';
  23175. this._hidden = false;
  23176. // if (box.setActive) {
  23177. // box.setActive();
  23178. // }
  23179. this.fireEvent('show');
  23180. }
  23181. },
  23182. isHidden: function (){
  23183. return this._hidden;
  23184. },
  23185. show: function (){
  23186. this._doAutoRender();
  23187. this._show();
  23188. },
  23189. hide: function (notNofity){
  23190. if (!this._hidden && this.getDom()) {
  23191. this.getDom().style.display = 'none';
  23192. this._hidden = true;
  23193. if (!notNofity) {
  23194. this.fireEvent('hide');
  23195. }
  23196. }
  23197. },
  23198. queryAutoHide: function (el){
  23199. return !el || !uiUtils.contains(this.getDom(), el);
  23200. }
  23201. };
  23202. utils.inherits(Popup, UIBase);
  23203. domUtils.on( document, 'mousedown', function ( evt ) {
  23204. var el = evt.target || evt.srcElement;
  23205. closeAllPopup( evt,el );
  23206. } );
  23207. domUtils.on( window, 'scroll', function (evt,el) {
  23208. closeAllPopup( evt,el );
  23209. } );
  23210. })();
  23211. // ui/colorpicker.js
  23212. ///import core
  23213. ///import uicore
  23214. (function (){
  23215. var utils = baidu.editor.utils,
  23216. UIBase = baidu.editor.ui.UIBase,
  23217. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23218. this.initOptions(options);
  23219. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23220. this.initUIBase();
  23221. };
  23222. ColorPicker.prototype = {
  23223. getHtmlTpl: function (){
  23224. return genColorPicker(this.noColorText,this.editor);
  23225. },
  23226. _onTableClick: function (evt){
  23227. var tgt = evt.target || evt.srcElement;
  23228. var color = tgt.getAttribute('data-color');
  23229. if (color) {
  23230. this.fireEvent('pickcolor', color);
  23231. }
  23232. },
  23233. _onTableOver: function (evt){
  23234. var tgt = evt.target || evt.srcElement;
  23235. var color = tgt.getAttribute('data-color');
  23236. if (color) {
  23237. this.getDom('preview').style.backgroundColor = color;
  23238. }
  23239. },
  23240. _onTableOut: function (){
  23241. this.getDom('preview').style.backgroundColor = '';
  23242. },
  23243. _onPickNoColor: function (){
  23244. this.fireEvent('picknocolor');
  23245. }
  23246. };
  23247. utils.inherits(ColorPicker, UIBase);
  23248. var COLORS = (
  23249. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23250. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23251. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23252. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23253. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23254. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23255. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23256. function genColorPicker(noColorText,editor){
  23257. var html = '<div id="##" class="edui-colorpicker %%">' +
  23258. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23259. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23260. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23261. '</div>' +
  23262. '<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">' +
  23263. '<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>'+
  23264. '<tr class="edui-colorpicker-tablefirstrow" >';
  23265. for (var i=0; i<COLORS.length; i++) {
  23266. if (i && i%10 === 0) {
  23267. 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"':'')+'>';
  23268. }
  23269. 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"' +
  23270. ' data-color="#'+ COLORS[i] +'"'+
  23271. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23272. (i<10 || i>=60?'border-width:1px;':
  23273. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23274. 'border-width:0 1px 0 1px;')+
  23275. '"' +
  23276. '></a></td>':'';
  23277. }
  23278. html += '</tr></table></div>';
  23279. return html;
  23280. }
  23281. })();
  23282. // ui/tablepicker.js
  23283. ///import core
  23284. ///import uicore
  23285. (function (){
  23286. var utils = baidu.editor.utils,
  23287. uiUtils = baidu.editor.ui.uiUtils,
  23288. UIBase = baidu.editor.ui.UIBase;
  23289. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23290. this.initOptions(options);
  23291. this.initTablePicker();
  23292. };
  23293. TablePicker.prototype = {
  23294. defaultNumRows: 10,
  23295. defaultNumCols: 10,
  23296. maxNumRows: 20,
  23297. maxNumCols: 20,
  23298. numRows: 10,
  23299. numCols: 10,
  23300. lengthOfCellSide: 22,
  23301. initTablePicker: function (){
  23302. this.initUIBase();
  23303. },
  23304. getHtmlTpl: function (){
  23305. var me = this;
  23306. return '<div id="##" class="edui-tablepicker %%">' +
  23307. '<div class="edui-tablepicker-body">' +
  23308. '<div class="edui-infoarea">' +
  23309. '<span id="##_label" class="edui-label"></span>' +
  23310. '</div>' +
  23311. '<div class="edui-pickarea"' +
  23312. ' onmousemove="$$._onMouseMove(event, this);"' +
  23313. ' onmouseover="$$._onMouseOver(event, this);"' +
  23314. ' onmouseout="$$._onMouseOut(event, this);"' +
  23315. ' onclick="$$._onClick(event, this);"' +
  23316. '>' +
  23317. '<div id="##_overlay" class="edui-overlay"></div>' +
  23318. '</div>' +
  23319. '</div>' +
  23320. '</div>';
  23321. },
  23322. _UIBase_render: UIBase.prototype.render,
  23323. render: function (holder){
  23324. this._UIBase_render(holder);
  23325. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23326. },
  23327. _track: function (numCols, numRows){
  23328. var style = this.getDom('overlay').style;
  23329. var sideLen = this.lengthOfCellSide;
  23330. style.width = numCols * sideLen + 'px';
  23331. style.height = numRows * sideLen + 'px';
  23332. var label = this.getDom('label');
  23333. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23334. this.numCols = numCols;
  23335. this.numRows = numRows;
  23336. },
  23337. _onMouseOver: function (evt, el){
  23338. var rel = evt.relatedTarget || evt.fromElement;
  23339. if (!uiUtils.contains(el, rel) && el !== rel) {
  23340. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23341. this.getDom('overlay').style.visibility = '';
  23342. }
  23343. },
  23344. _onMouseOut: function (evt, el){
  23345. var rel = evt.relatedTarget || evt.toElement;
  23346. if (!uiUtils.contains(el, rel) && el !== rel) {
  23347. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23348. this.getDom('overlay').style.visibility = 'hidden';
  23349. }
  23350. },
  23351. _onMouseMove: function (evt, el){
  23352. var style = this.getDom('overlay').style;
  23353. var offset = uiUtils.getEventOffset(evt);
  23354. var sideLen = this.lengthOfCellSide;
  23355. var numCols = Math.ceil(offset.left / sideLen);
  23356. var numRows = Math.ceil(offset.top / sideLen);
  23357. this._track(numCols, numRows);
  23358. },
  23359. _onClick: function (){
  23360. this.fireEvent('picktable', this.numCols, this.numRows);
  23361. }
  23362. };
  23363. utils.inherits(TablePicker, UIBase);
  23364. })();
  23365. // ui/stateful.js
  23366. (function (){
  23367. var browser = baidu.editor.browser,
  23368. domUtils = baidu.editor.dom.domUtils,
  23369. uiUtils = baidu.editor.ui.uiUtils;
  23370. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23371. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23372. ( browser.ie ? (
  23373. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23374. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23375. : (
  23376. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23377. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23378. baidu.editor.ui.Stateful = {
  23379. alwalysHoverable: false,
  23380. target:null,//目标元素和this指向dom不一样
  23381. Stateful_init: function (){
  23382. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23383. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23384. },
  23385. Stateful_getHtmlTpl: function (){
  23386. var tpl = this._Stateful_dGetHtmlTpl();
  23387. // 使用function避免$转义
  23388. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23389. },
  23390. Stateful_onMouseEnter: function (evt, el){
  23391. this.target=el;
  23392. if (!this.isDisabled() || this.alwalysHoverable) {
  23393. this.addState('hover');
  23394. this.fireEvent('over');
  23395. }
  23396. },
  23397. Stateful_onMouseLeave: function (evt, el){
  23398. if (!this.isDisabled() || this.alwalysHoverable) {
  23399. this.removeState('hover');
  23400. this.removeState('active');
  23401. this.fireEvent('out');
  23402. }
  23403. },
  23404. Stateful_onMouseOver: function (evt, el){
  23405. var rel = evt.relatedTarget;
  23406. if (!uiUtils.contains(el, rel) && el !== rel) {
  23407. this.Stateful_onMouseEnter(evt, el);
  23408. }
  23409. },
  23410. Stateful_onMouseOut: function (evt, el){
  23411. var rel = evt.relatedTarget;
  23412. if (!uiUtils.contains(el, rel) && el !== rel) {
  23413. this.Stateful_onMouseLeave(evt, el);
  23414. }
  23415. },
  23416. Stateful_onMouseDown: function (evt, el){
  23417. if (!this.isDisabled()) {
  23418. this.addState('active');
  23419. }
  23420. },
  23421. Stateful_onMouseUp: function (evt, el){
  23422. if (!this.isDisabled()) {
  23423. this.removeState('active');
  23424. }
  23425. },
  23426. Stateful_postRender: function (){
  23427. if (this.disabled && !this.hasState('disabled')) {
  23428. this.addState('disabled');
  23429. }
  23430. },
  23431. hasState: function (state){
  23432. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23433. },
  23434. addState: function (state){
  23435. if (!this.hasState(state)) {
  23436. this.getStateDom().className += ' edui-state-' + state;
  23437. }
  23438. },
  23439. removeState: function (state){
  23440. if (this.hasState(state)) {
  23441. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23442. }
  23443. },
  23444. getStateDom: function (){
  23445. return this.getDom('state');
  23446. },
  23447. isChecked: function (){
  23448. return this.hasState('checked');
  23449. },
  23450. setChecked: function (checked){
  23451. if (!this.isDisabled() && checked) {
  23452. this.addState('checked');
  23453. } else {
  23454. this.removeState('checked');
  23455. }
  23456. },
  23457. isDisabled: function (){
  23458. return this.hasState('disabled');
  23459. },
  23460. setDisabled: function (disabled){
  23461. if (disabled) {
  23462. this.removeState('hover');
  23463. this.removeState('checked');
  23464. this.removeState('active');
  23465. this.addState('disabled');
  23466. } else {
  23467. this.removeState('disabled');
  23468. }
  23469. }
  23470. };
  23471. })();
  23472. // ui/button.js
  23473. ///import core
  23474. ///import uicore
  23475. ///import ui/stateful.js
  23476. (function (){
  23477. var utils = baidu.editor.utils,
  23478. UIBase = baidu.editor.ui.UIBase,
  23479. Stateful = baidu.editor.ui.Stateful,
  23480. Button = baidu.editor.ui.Button = function (options){
  23481. if(options.name){
  23482. var btnName = options.name;
  23483. var cssRules = options.cssRules;
  23484. if(!options.className){
  23485. options.className = 'edui-for-' + btnName;
  23486. }
  23487. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23488. }
  23489. this.initOptions(options);
  23490. this.initButton();
  23491. };
  23492. Button.prototype = {
  23493. uiName: 'button',
  23494. label: '',
  23495. title: '',
  23496. showIcon: true,
  23497. showText: true,
  23498. cssRules:'',
  23499. initButton: function (){
  23500. this.initUIBase();
  23501. this.Stateful_init();
  23502. if(this.cssRules){
  23503. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23504. }
  23505. },
  23506. getHtmlTpl: function (){
  23507. return '<div id="##" class="edui-box %%">' +
  23508. '<div id="##_state" stateful>' +
  23509. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23510. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23511. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23512. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23513. '</div>' +
  23514. '</div>' +
  23515. '</div></div>';
  23516. },
  23517. postRender: function (){
  23518. this.Stateful_postRender();
  23519. this.setDisabled(this.disabled)
  23520. },
  23521. _onMouseDown: function (e){
  23522. var target = e.target || e.srcElement;
  23523. if (!(target && target.tagName && (target.tagName.toLowerCase() == 'input' || target.tagName.toLowerCase() == 'object'))) {
  23524. return false;
  23525. }
  23526. },
  23527. _onClick: function (){
  23528. if (!this.isDisabled()) {
  23529. this.fireEvent('click');
  23530. }
  23531. },
  23532. setTitle: function(text){
  23533. var label = this.getDom('label');
  23534. label.innerHTML = text;
  23535. }
  23536. };
  23537. utils.inherits(Button, UIBase);
  23538. utils.extend(Button.prototype, Stateful);
  23539. })();
  23540. // ui/splitbutton.js
  23541. ///import core
  23542. ///import uicore
  23543. ///import ui/stateful.js
  23544. (function (){
  23545. var utils = baidu.editor.utils,
  23546. uiUtils = baidu.editor.ui.uiUtils,
  23547. domUtils = baidu.editor.dom.domUtils,
  23548. UIBase = baidu.editor.ui.UIBase,
  23549. Stateful = baidu.editor.ui.Stateful,
  23550. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23551. this.initOptions(options);
  23552. this.initSplitButton();
  23553. };
  23554. SplitButton.prototype = {
  23555. popup: null,
  23556. uiName: 'splitbutton',
  23557. title: '',
  23558. initSplitButton: function (){
  23559. this.initUIBase();
  23560. this.Stateful_init();
  23561. var me = this;
  23562. if (this.popup != null) {
  23563. var popup = this.popup;
  23564. this.popup = null;
  23565. this.setPopup(popup);
  23566. }
  23567. },
  23568. _UIBase_postRender: UIBase.prototype.postRender,
  23569. postRender: function (){
  23570. this.Stateful_postRender();
  23571. this._UIBase_postRender();
  23572. },
  23573. setPopup: function (popup){
  23574. if (this.popup === popup) return;
  23575. if (this.popup != null) {
  23576. this.popup.dispose();
  23577. }
  23578. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23579. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23580. popup.addListener('postrender', utils.bind(function (){
  23581. popup.getDom('body').appendChild(
  23582. uiUtils.createElementByHtml('<div id="' +
  23583. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23584. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23585. );
  23586. popup.getDom().className += ' ' + this.className;
  23587. }, this));
  23588. this.popup = popup;
  23589. },
  23590. _onPopupShow: function (){
  23591. this.addState('opened');
  23592. },
  23593. _onPopupHide: function (){
  23594. this.removeState('opened');
  23595. },
  23596. getHtmlTpl: function (){
  23597. return '<div id="##" class="edui-box %%">' +
  23598. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23599. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23600. '<div class="edui-box edui-icon"></div>' +
  23601. '</div>' +
  23602. '<div class="edui-box edui-splitborder"></div>' +
  23603. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23604. '</div></div></div>';
  23605. },
  23606. showPopup: function (){
  23607. // 当popup往上弹出的时候,做特殊处理
  23608. var rect = uiUtils.getClientRect(this.getDom());
  23609. rect.top -= this.popup.SHADOW_RADIUS;
  23610. rect.height += this.popup.SHADOW_RADIUS;
  23611. this.popup.showAnchorRect(rect);
  23612. },
  23613. _onArrowClick: function (event, el){
  23614. if (!this.isDisabled()) {
  23615. this.showPopup();
  23616. }
  23617. },
  23618. _onButtonClick: function (){
  23619. if (!this.isDisabled()) {
  23620. this.fireEvent('buttonclick');
  23621. }
  23622. }
  23623. };
  23624. utils.inherits(SplitButton, UIBase);
  23625. utils.extend(SplitButton.prototype, Stateful, true);
  23626. })();
  23627. // ui/colorbutton.js
  23628. ///import core
  23629. ///import uicore
  23630. ///import ui/colorpicker.js
  23631. ///import ui/popup.js
  23632. ///import ui/splitbutton.js
  23633. (function (){
  23634. var utils = baidu.editor.utils,
  23635. uiUtils = baidu.editor.ui.uiUtils,
  23636. ColorPicker = baidu.editor.ui.ColorPicker,
  23637. Popup = baidu.editor.ui.Popup,
  23638. SplitButton = baidu.editor.ui.SplitButton,
  23639. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23640. this.initOptions(options);
  23641. this.initColorButton();
  23642. };
  23643. ColorButton.prototype = {
  23644. initColorButton: function (){
  23645. var me = this;
  23646. this.popup = new Popup({
  23647. content: new ColorPicker({
  23648. noColorText: me.editor.getLang("clearColor"),
  23649. editor:me.editor,
  23650. onpickcolor: function (t, color){
  23651. me._onPickColor(color);
  23652. },
  23653. onpicknocolor: function (t, color){
  23654. me._onPickNoColor(color);
  23655. }
  23656. }),
  23657. editor:me.editor
  23658. });
  23659. this.initSplitButton();
  23660. },
  23661. _SplitButton_postRender: SplitButton.prototype.postRender,
  23662. postRender: function (){
  23663. this._SplitButton_postRender();
  23664. this.getDom('button_body').appendChild(
  23665. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23666. );
  23667. this.getDom().className += ' edui-colorbutton';
  23668. },
  23669. setColor: function (color){
  23670. this.getDom('colorlump').style.backgroundColor = color;
  23671. this.color = color;
  23672. },
  23673. _onPickColor: function (color){
  23674. if (this.fireEvent('pickcolor', color) !== false) {
  23675. this.setColor(color);
  23676. this.popup.hide();
  23677. }
  23678. },
  23679. _onPickNoColor: function (color){
  23680. if (this.fireEvent('picknocolor') !== false) {
  23681. this.popup.hide();
  23682. }
  23683. }
  23684. };
  23685. utils.inherits(ColorButton, SplitButton);
  23686. })();
  23687. // ui/tablebutton.js
  23688. ///import core
  23689. ///import uicore
  23690. ///import ui/popup.js
  23691. ///import ui/tablepicker.js
  23692. ///import ui/splitbutton.js
  23693. (function (){
  23694. var utils = baidu.editor.utils,
  23695. Popup = baidu.editor.ui.Popup,
  23696. TablePicker = baidu.editor.ui.TablePicker,
  23697. SplitButton = baidu.editor.ui.SplitButton,
  23698. TableButton = baidu.editor.ui.TableButton = function (options){
  23699. this.initOptions(options);
  23700. this.initTableButton();
  23701. };
  23702. TableButton.prototype = {
  23703. initTableButton: function (){
  23704. var me = this;
  23705. this.popup = new Popup({
  23706. content: new TablePicker({
  23707. editor:me.editor,
  23708. onpicktable: function (t, numCols, numRows){
  23709. me._onPickTable(numCols, numRows);
  23710. }
  23711. }),
  23712. 'editor':me.editor
  23713. });
  23714. this.initSplitButton();
  23715. },
  23716. _onPickTable: function (numCols, numRows){
  23717. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23718. this.popup.hide();
  23719. }
  23720. }
  23721. };
  23722. utils.inherits(TableButton, SplitButton);
  23723. })();
  23724. // ui/autotypesetpicker.js
  23725. ///import core
  23726. ///import uicore
  23727. (function () {
  23728. var utils = baidu.editor.utils,
  23729. UIBase = baidu.editor.ui.UIBase;
  23730. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23731. this.initOptions(options);
  23732. this.initAutoTypeSetPicker();
  23733. };
  23734. AutoTypeSetPicker.prototype = {
  23735. initAutoTypeSetPicker:function () {
  23736. this.initUIBase();
  23737. },
  23738. getHtmlTpl:function () {
  23739. var me = this.editor,
  23740. opt = me.options.autotypeset,
  23741. lang = me.getLang("autoTypeSet");
  23742. var textAlignInputName = 'textAlignValue' + me.uid,
  23743. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23744. symbolConverInputName = 'symbolConverValue' + me.uid;
  23745. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23746. '<div class="edui-autotypesetpicker-body">' +
  23747. '<table >' +
  23748. '<tr><td nowrap><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' +
  23749. '<tr><td nowrap><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' +
  23750. '<tr>' +
  23751. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  23752. '<td colspan="2" id="' + textAlignInputName + '">' +
  23753. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23754. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23755. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23756. '</td>' +
  23757. '</tr>' +
  23758. '<tr>' +
  23759. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  23760. '<td nowrap id="'+ imageBlockInputName +'">' +
  23761. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  23762. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23763. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23764. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23765. '</td>' +
  23766. '</tr>' +
  23767. '<tr><td nowrap><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' +
  23768. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  23769. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  23770. '<tr>' +
  23771. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  23772. '<td id="' + symbolConverInputName + '">' +
  23773. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  23774. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  23775. '</td>' +
  23776. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  23777. '</tr>' +
  23778. '</table>' +
  23779. '</div>' +
  23780. '</div>';
  23781. },
  23782. _UIBase_render:UIBase.prototype.render
  23783. };
  23784. utils.inherits(AutoTypeSetPicker, UIBase);
  23785. })();
  23786. // ui/autotypesetbutton.js
  23787. ///import core
  23788. ///import uicore
  23789. ///import ui/popup.js
  23790. ///import ui/autotypesetpicker.js
  23791. ///import ui/splitbutton.js
  23792. (function (){
  23793. var utils = baidu.editor.utils,
  23794. Popup = baidu.editor.ui.Popup,
  23795. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  23796. SplitButton = baidu.editor.ui.SplitButton,
  23797. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  23798. this.initOptions(options);
  23799. this.initAutoTypeSetButton();
  23800. };
  23801. function getPara(me){
  23802. var opt = {},
  23803. cont = me.getDom(),
  23804. editorId = me.editor.uid,
  23805. inputType = null,
  23806. attrName = null,
  23807. ipts = domUtils.getElementsByTagName(cont,"input");
  23808. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  23809. inputType = ipt.getAttribute("type");
  23810. if(inputType=="checkbox"){
  23811. attrName = ipt.getAttribute("name");
  23812. opt[attrName] && delete opt[attrName];
  23813. if(ipt.checked){
  23814. var attrValue = document.getElementById( attrName + "Value" + editorId );
  23815. if(attrValue){
  23816. if(/input/ig.test(attrValue.tagName)){
  23817. opt[attrName] = attrValue.value;
  23818. } else {
  23819. var iptChilds = attrValue.getElementsByTagName("input");
  23820. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  23821. if(iptchild.checked){
  23822. opt[attrName] = iptchild.value;
  23823. break;
  23824. }
  23825. }
  23826. }
  23827. } else {
  23828. opt[attrName] = true;
  23829. }
  23830. } else {
  23831. opt[attrName] = false;
  23832. }
  23833. } else {
  23834. opt[ipt.getAttribute("value")] = ipt.checked;
  23835. }
  23836. }
  23837. var selects = domUtils.getElementsByTagName(cont,"select");
  23838. for(var i=0,si;si=selects[i++];){
  23839. var attr = si.getAttribute('name');
  23840. opt[attr] = opt[attr] ? si.value : '';
  23841. }
  23842. utils.extend(me.editor.options.autotypeset,opt);
  23843. me.editor.setPreferences('autotypeset', opt);
  23844. }
  23845. AutoTypeSetButton.prototype = {
  23846. initAutoTypeSetButton: function (){
  23847. var me = this;
  23848. this.popup = new Popup({
  23849. //传入配置参数
  23850. content: new AutoTypeSetPicker({editor:me.editor}),
  23851. 'editor':me.editor,
  23852. hide : function(){
  23853. if (!this._hidden && this.getDom()) {
  23854. getPara(this);
  23855. this.getDom().style.display = 'none';
  23856. this._hidden = true;
  23857. this.fireEvent('hide');
  23858. }
  23859. }
  23860. });
  23861. var flag = 0;
  23862. this.popup.addListener('postRenderAfter',function(){
  23863. var popupUI = this;
  23864. if(flag)return;
  23865. var cont = this.getDom(),
  23866. btn = cont.getElementsByTagName('button')[0];
  23867. btn.onclick = function(){
  23868. getPara(popupUI);
  23869. me.editor.execCommand('autotypeset');
  23870. popupUI.hide()
  23871. };
  23872. domUtils.on(cont, 'click', function(e) {
  23873. var target = e.target || e.srcElement,
  23874. editorId = me.editor.uid;
  23875. if (target && target.tagName == 'INPUT') {
  23876. // 点击图片浮动的checkbox,去除对应的radio
  23877. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  23878. var checked = target.checked,
  23879. radioTd = document.getElementById( target.name + 'Value' + editorId),
  23880. radios = radioTd.getElementsByTagName('input'),
  23881. defalutSelect = {
  23882. 'imageBlockLine': 'none',
  23883. 'textAlign': 'left',
  23884. 'symbolConver': 'tobdc'
  23885. };
  23886. for (var i = 0; i < radios.length; i++) {
  23887. if (checked) {
  23888. if (radios[i].value == defalutSelect[target.name]) {
  23889. radios[i].checked = 'checked';
  23890. }
  23891. } else {
  23892. radios[i].checked = false;
  23893. }
  23894. }
  23895. }
  23896. // 点击radio,选中对应的checkbox
  23897. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  23898. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  23899. checkboxs && (checkboxs[0].checked = true);
  23900. }
  23901. getPara(popupUI);
  23902. }
  23903. });
  23904. flag = 1;
  23905. });
  23906. this.initSplitButton();
  23907. }
  23908. };
  23909. utils.inherits(AutoTypeSetButton, SplitButton);
  23910. })();
  23911. // ui/cellalignpicker.js
  23912. ///import core
  23913. ///import uicore
  23914. (function () {
  23915. var utils = baidu.editor.utils,
  23916. Popup = baidu.editor.ui.Popup,
  23917. Stateful = baidu.editor.ui.Stateful,
  23918. UIBase = baidu.editor.ui.UIBase;
  23919. /**
  23920. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  23921. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  23922. * @update 2013/4/2 hancong03@baidu.com
  23923. */
  23924. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  23925. this.initOptions(options);
  23926. this.initSelected();
  23927. this.initCellAlignPicker();
  23928. };
  23929. CellAlignPicker.prototype = {
  23930. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  23931. initSelected: function(){
  23932. var status = {
  23933. valign: {
  23934. top: 0,
  23935. middle: 1,
  23936. bottom: 2
  23937. },
  23938. align: {
  23939. left: 0,
  23940. center: 1,
  23941. right: 2
  23942. },
  23943. count: 3
  23944. },
  23945. result = -1;
  23946. if( this.selected ) {
  23947. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  23948. }
  23949. },
  23950. initCellAlignPicker:function () {
  23951. this.initUIBase();
  23952. this.Stateful_init();
  23953. },
  23954. getHtmlTpl:function () {
  23955. var alignType = [ 'left', 'center', 'right' ],
  23956. COUNT = 9,
  23957. tempClassName = null,
  23958. tempIndex = -1,
  23959. tmpl = [];
  23960. for( var i= 0; i<COUNT; i++ ) {
  23961. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  23962. tempIndex = i % 3;
  23963. tempIndex === 0 && tmpl.push('<tr>');
  23964. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  23965. tempIndex === 2 && tmpl.push('</tr>');
  23966. }
  23967. return '<div id="##" class="edui-cellalignpicker %%">' +
  23968. '<div class="edui-cellalignpicker-body">' +
  23969. '<table onclick="$$._onClick(event);">' +
  23970. tmpl.join('') +
  23971. '</table>' +
  23972. '</div>' +
  23973. '</div>';
  23974. },
  23975. getStateDom: function (){
  23976. return this.target;
  23977. },
  23978. _onClick: function (evt){
  23979. var target= evt.target || evt.srcElement;
  23980. if(/icon/.test(target.className)){
  23981. this.items[target.parentNode.getAttribute("index")].onclick();
  23982. Popup.postHide(evt);
  23983. }
  23984. },
  23985. _UIBase_render:UIBase.prototype.render
  23986. };
  23987. utils.inherits(CellAlignPicker, UIBase);
  23988. utils.extend(CellAlignPicker.prototype, Stateful,true);
  23989. })();
  23990. // ui/pastepicker.js
  23991. ///import core
  23992. ///import uicore
  23993. (function () {
  23994. var utils = baidu.editor.utils,
  23995. Stateful = baidu.editor.ui.Stateful,
  23996. uiUtils = baidu.editor.ui.uiUtils,
  23997. UIBase = baidu.editor.ui.UIBase;
  23998. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  23999. this.initOptions(options);
  24000. this.initPastePicker();
  24001. };
  24002. PastePicker.prototype = {
  24003. initPastePicker:function () {
  24004. this.initUIBase();
  24005. this.Stateful_init();
  24006. },
  24007. getHtmlTpl:function () {
  24008. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24009. '<div class="edui-pastecontainer">' +
  24010. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24011. '<div class="edui-button">' +
  24012. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24013. '<div class="edui-richtxticon"></div></div>' +
  24014. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24015. '<div class="edui-tagicon"></div></div>' +
  24016. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24017. '<div class="edui-plaintxticon"></div></div>' +
  24018. '</div>' +
  24019. '</div>' +
  24020. '</div>'
  24021. },
  24022. getStateDom:function () {
  24023. return this.target;
  24024. },
  24025. format:function (param) {
  24026. this.editor.ui._isTransfer = true;
  24027. this.editor.fireEvent('pasteTransfer', param);
  24028. },
  24029. _onClick:function (cur) {
  24030. var node = domUtils.getNextDomNode(cur),
  24031. screenHt = uiUtils.getViewportRect().height,
  24032. subPop = uiUtils.getClientRect(node);
  24033. if ((subPop.top + subPop.height) > screenHt)
  24034. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24035. else
  24036. node.style.top = "";
  24037. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24038. node.style.visibility = "visible";
  24039. domUtils.addClass(cur, "edui-state-opened");
  24040. } else {
  24041. node.style.visibility = "hidden";
  24042. domUtils.removeClasses(cur, "edui-state-opened")
  24043. }
  24044. },
  24045. _UIBase_render:UIBase.prototype.render
  24046. };
  24047. utils.inherits(PastePicker, UIBase);
  24048. utils.extend(PastePicker.prototype, Stateful, true);
  24049. })();
  24050. // ui/toolbar.js
  24051. (function (){
  24052. var utils = baidu.editor.utils,
  24053. uiUtils = baidu.editor.ui.uiUtils,
  24054. UIBase = baidu.editor.ui.UIBase,
  24055. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24056. this.initOptions(options);
  24057. this.initToolbar();
  24058. };
  24059. Toolbar.prototype = {
  24060. items: null,
  24061. initToolbar: function (){
  24062. this.items = this.items || [];
  24063. this.initUIBase();
  24064. },
  24065. add: function (item,index){
  24066. if(index === undefined){
  24067. this.items.push(item);
  24068. }else{
  24069. this.items.splice(index,0,item)
  24070. }
  24071. },
  24072. getHtmlTpl: function (){
  24073. var buff = [];
  24074. for (var i=0; i<this.items.length; i++) {
  24075. buff[i] = this.items[i].renderHtml();
  24076. }
  24077. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24078. buff.join('') +
  24079. '</div>'
  24080. },
  24081. postRender: function (){
  24082. var box = this.getDom();
  24083. for (var i=0; i<this.items.length; i++) {
  24084. this.items[i].postRender();
  24085. }
  24086. uiUtils.makeUnselectable(box);
  24087. },
  24088. _onMouseDown: function (e){
  24089. var target = e.target || e.srcElement;
  24090. if (!(target && target.tagName && (target.tagName.toLowerCase() == 'input' || target.tagName.toLowerCase() == 'object'))) {
  24091. return false;
  24092. }
  24093. }
  24094. };
  24095. utils.inherits(Toolbar, UIBase);
  24096. })();
  24097. // ui/menu.js
  24098. ///import core
  24099. ///import uicore
  24100. ///import ui\popup.js
  24101. ///import ui\stateful.js
  24102. (function () {
  24103. var utils = baidu.editor.utils,
  24104. domUtils = baidu.editor.dom.domUtils,
  24105. uiUtils = baidu.editor.ui.uiUtils,
  24106. UIBase = baidu.editor.ui.UIBase,
  24107. Popup = baidu.editor.ui.Popup,
  24108. Stateful = baidu.editor.ui.Stateful,
  24109. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24110. Menu = baidu.editor.ui.Menu = function (options) {
  24111. this.initOptions(options);
  24112. this.initMenu();
  24113. };
  24114. var menuSeparator = {
  24115. renderHtml:function () {
  24116. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24117. },
  24118. postRender:function () {
  24119. },
  24120. queryAutoHide:function () {
  24121. return true;
  24122. }
  24123. };
  24124. Menu.prototype = {
  24125. items:null,
  24126. uiName:'menu',
  24127. initMenu:function () {
  24128. this.items = this.items || [];
  24129. this.initPopup();
  24130. this.initItems();
  24131. },
  24132. initItems:function () {
  24133. for (var i = 0; i < this.items.length; i++) {
  24134. var item = this.items[i];
  24135. if (item == '-') {
  24136. this.items[i] = this.getSeparator();
  24137. } else if (!(item instanceof MenuItem)) {
  24138. item.editor = this.editor;
  24139. item.theme = this.editor.options.theme;
  24140. this.items[i] = this.createItem(item);
  24141. }
  24142. }
  24143. },
  24144. getSeparator:function () {
  24145. return menuSeparator;
  24146. },
  24147. createItem:function (item) {
  24148. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24149. item.menu = this;
  24150. return new MenuItem(item);
  24151. },
  24152. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24153. getContentHtmlTpl:function () {
  24154. if (this.items.length == 0) {
  24155. return this._Popup_getContentHtmlTpl();
  24156. }
  24157. var buff = [];
  24158. for (var i = 0; i < this.items.length; i++) {
  24159. var item = this.items[i];
  24160. buff[i] = item.renderHtml();
  24161. }
  24162. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24163. },
  24164. _Popup_postRender:Popup.prototype.postRender,
  24165. postRender:function () {
  24166. var me = this;
  24167. for (var i = 0; i < this.items.length; i++) {
  24168. var item = this.items[i];
  24169. item.ownerMenu = this;
  24170. item.postRender();
  24171. }
  24172. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24173. evt = evt || event;
  24174. var rel = evt.relatedTarget || evt.fromElement;
  24175. var el = me.getDom();
  24176. if (!uiUtils.contains(el, rel) && el !== rel) {
  24177. me.fireEvent('over');
  24178. }
  24179. });
  24180. this._Popup_postRender();
  24181. },
  24182. queryAutoHide:function (el) {
  24183. if (el) {
  24184. if (uiUtils.contains(this.getDom(), el)) {
  24185. return false;
  24186. }
  24187. for (var i = 0; i < this.items.length; i++) {
  24188. var item = this.items[i];
  24189. if (item.queryAutoHide(el) === false) {
  24190. return false;
  24191. }
  24192. }
  24193. }
  24194. },
  24195. clearItems:function () {
  24196. for (var i = 0; i < this.items.length; i++) {
  24197. var item = this.items[i];
  24198. clearTimeout(item._showingTimer);
  24199. clearTimeout(item._closingTimer);
  24200. if (item.subMenu) {
  24201. item.subMenu.destroy();
  24202. }
  24203. }
  24204. this.items = [];
  24205. },
  24206. destroy:function () {
  24207. if (this.getDom()) {
  24208. domUtils.remove(this.getDom());
  24209. }
  24210. this.clearItems();
  24211. },
  24212. dispose:function () {
  24213. this.destroy();
  24214. }
  24215. };
  24216. utils.inherits(Menu, Popup);
  24217. /**
  24218. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24219. * @type {Function}
  24220. */
  24221. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24222. this.initOptions(options);
  24223. this.initUIBase();
  24224. this.Stateful_init();
  24225. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24226. if (options.className && options.className.indexOf("aligntd") != -1) {
  24227. var me = this;
  24228. //获取单元格对齐初始状态
  24229. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24230. this.subMenu = new Popup({
  24231. content:new CellAlignPicker(this.subMenu),
  24232. parentMenu:me,
  24233. editor:me.editor,
  24234. destroy:function () {
  24235. if (this.getDom()) {
  24236. domUtils.remove(this.getDom());
  24237. }
  24238. }
  24239. });
  24240. this.subMenu.addListener("postRenderAfter", function () {
  24241. domUtils.on(this.getDom(), "mouseover", function () {
  24242. me.addState('opened');
  24243. });
  24244. });
  24245. } else {
  24246. this.subMenu = new Menu(this.subMenu);
  24247. }
  24248. }
  24249. };
  24250. MenuItem.prototype = {
  24251. label:'',
  24252. subMenu:null,
  24253. ownerMenu:null,
  24254. uiName:'menuitem',
  24255. alwalysHoverable:true,
  24256. getHtmlTpl:function () {
  24257. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24258. '<div class="%%-body">' +
  24259. this.renderLabelHtml() +
  24260. '</div>' +
  24261. '</div>';
  24262. },
  24263. postRender:function () {
  24264. var me = this;
  24265. this.addListener('over', function () {
  24266. me.ownerMenu.fireEvent('submenuover', me);
  24267. if (me.subMenu) {
  24268. me.delayShowSubMenu();
  24269. }
  24270. });
  24271. if (this.subMenu) {
  24272. this.getDom().className += ' edui-hassubmenu';
  24273. this.subMenu.render();
  24274. this.addListener('out', function () {
  24275. me.delayHideSubMenu();
  24276. });
  24277. this.subMenu.addListener('over', function () {
  24278. clearTimeout(me._closingTimer);
  24279. me._closingTimer = null;
  24280. me.addState('opened');
  24281. });
  24282. this.ownerMenu.addListener('hide', function () {
  24283. me.hideSubMenu();
  24284. });
  24285. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24286. if (subMenu !== me) {
  24287. me.delayHideSubMenu();
  24288. }
  24289. });
  24290. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24291. this.subMenu.queryAutoHide = function (el) {
  24292. if (el && uiUtils.contains(me.getDom(), el)) {
  24293. return false;
  24294. }
  24295. return this._bakQueryAutoHide(el);
  24296. };
  24297. }
  24298. this.getDom().style.tabIndex = '-1';
  24299. uiUtils.makeUnselectable(this.getDom());
  24300. this.Stateful_postRender();
  24301. },
  24302. delayShowSubMenu:function () {
  24303. var me = this;
  24304. if (!me.isDisabled()) {
  24305. me.addState('opened');
  24306. clearTimeout(me._showingTimer);
  24307. clearTimeout(me._closingTimer);
  24308. me._closingTimer = null;
  24309. me._showingTimer = setTimeout(function () {
  24310. me.showSubMenu();
  24311. }, 250);
  24312. }
  24313. },
  24314. delayHideSubMenu:function () {
  24315. var me = this;
  24316. if (!me.isDisabled()) {
  24317. me.removeState('opened');
  24318. clearTimeout(me._showingTimer);
  24319. if (!me._closingTimer) {
  24320. me._closingTimer = setTimeout(function () {
  24321. if (!me.hasState('opened')) {
  24322. me.hideSubMenu();
  24323. }
  24324. me._closingTimer = null;
  24325. }, 400);
  24326. }
  24327. }
  24328. },
  24329. renderLabelHtml:function () {
  24330. return '<div class="edui-arrow"></div>' +
  24331. '<div class="edui-box edui-icon"></div>' +
  24332. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24333. },
  24334. getStateDom:function () {
  24335. return this.getDom();
  24336. },
  24337. queryAutoHide:function (el) {
  24338. if (this.subMenu && this.hasState('opened')) {
  24339. return this.subMenu.queryAutoHide(el);
  24340. }
  24341. },
  24342. _onClick:function (event, this_) {
  24343. if (this.hasState('disabled')) return;
  24344. if (this.fireEvent('click', event, this_) !== false) {
  24345. if (this.subMenu) {
  24346. this.showSubMenu();
  24347. } else {
  24348. Popup.postHide(event);
  24349. }
  24350. }
  24351. },
  24352. showSubMenu:function () {
  24353. var rect = uiUtils.getClientRect(this.getDom());
  24354. rect.right -= 5;
  24355. rect.left += 2;
  24356. rect.width -= 7;
  24357. rect.top -= 4;
  24358. rect.bottom += 4;
  24359. rect.height += 8;
  24360. this.subMenu.showAnchorRect(rect, true, true);
  24361. },
  24362. hideSubMenu:function () {
  24363. this.subMenu.hide();
  24364. }
  24365. };
  24366. utils.inherits(MenuItem, UIBase);
  24367. utils.extend(MenuItem.prototype, Stateful, true);
  24368. })();
  24369. // ui/combox.js
  24370. ///import core
  24371. ///import uicore
  24372. ///import ui/menu.js
  24373. ///import ui/splitbutton.js
  24374. (function (){
  24375. // todo: menu和item提成通用list
  24376. var utils = baidu.editor.utils,
  24377. uiUtils = baidu.editor.ui.uiUtils,
  24378. Menu = baidu.editor.ui.Menu,
  24379. SplitButton = baidu.editor.ui.SplitButton,
  24380. Combox = baidu.editor.ui.Combox = function (options){
  24381. this.initOptions(options);
  24382. this.initCombox();
  24383. };
  24384. Combox.prototype = {
  24385. uiName: 'combox',
  24386. onbuttonclick:function () {
  24387. this.showPopup();
  24388. },
  24389. initCombox: function (){
  24390. var me = this;
  24391. this.items = this.items || [];
  24392. for (var i=0; i<this.items.length; i++) {
  24393. var item = this.items[i];
  24394. item.uiName = 'listitem';
  24395. item.index = i;
  24396. item.onclick = function (){
  24397. me.selectByIndex(this.index);
  24398. };
  24399. }
  24400. this.popup = new Menu({
  24401. items: this.items,
  24402. uiName: 'list',
  24403. editor:this.editor,
  24404. captureWheel: true,
  24405. combox: this
  24406. });
  24407. this.initSplitButton();
  24408. },
  24409. _SplitButton_postRender: SplitButton.prototype.postRender,
  24410. postRender: function (){
  24411. this._SplitButton_postRender();
  24412. this.setLabel(this.label || '');
  24413. this.setValue(this.initValue || '');
  24414. },
  24415. showPopup: function (){
  24416. var rect = uiUtils.getClientRect(this.getDom());
  24417. rect.top += 1;
  24418. rect.bottom -= 1;
  24419. rect.height -= 2;
  24420. this.popup.showAnchorRect(rect);
  24421. },
  24422. getValue: function (){
  24423. return this.value;
  24424. },
  24425. setValue: function (value){
  24426. var index = this.indexByValue(value);
  24427. if (index != -1) {
  24428. this.selectedIndex = index;
  24429. this.setLabel(this.items[index].label);
  24430. this.value = this.items[index].value;
  24431. } else {
  24432. this.selectedIndex = -1;
  24433. this.setLabel(this.getLabelForUnknowValue(value));
  24434. this.value = value;
  24435. }
  24436. },
  24437. setLabel: function (label){
  24438. this.getDom('button_body').innerHTML = label;
  24439. this.label = label;
  24440. },
  24441. getLabelForUnknowValue: function (value){
  24442. return value;
  24443. },
  24444. indexByValue: function (value){
  24445. for (var i=0; i<this.items.length; i++) {
  24446. if (value == this.items[i].value) {
  24447. return i;
  24448. }
  24449. }
  24450. return -1;
  24451. },
  24452. getItem: function (index){
  24453. return this.items[index];
  24454. },
  24455. selectByIndex: function (index){
  24456. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24457. this.selectedIndex = index;
  24458. this.value = this.items[index].value;
  24459. this.setLabel(this.items[index].label);
  24460. }
  24461. }
  24462. };
  24463. utils.inherits(Combox, SplitButton);
  24464. })();
  24465. // ui/dialog.js
  24466. ///import core
  24467. ///import uicore
  24468. ///import ui/mask.js
  24469. ///import ui/button.js
  24470. (function (){
  24471. var utils = baidu.editor.utils,
  24472. domUtils = baidu.editor.dom.domUtils,
  24473. uiUtils = baidu.editor.ui.uiUtils,
  24474. Mask = baidu.editor.ui.Mask,
  24475. UIBase = baidu.editor.ui.UIBase,
  24476. Button = baidu.editor.ui.Button,
  24477. Dialog = baidu.editor.ui.Dialog = function (options){
  24478. if(options.name){
  24479. var name = options.name;
  24480. var cssRules = options.cssRules;
  24481. if(!options.className){
  24482. options.className = 'edui-for-' + name;
  24483. }
  24484. if(cssRules){
  24485. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24486. }
  24487. }
  24488. this.initOptions(utils.extend({
  24489. autoReset: true,
  24490. draggable: true,
  24491. onok: function (){},
  24492. oncancel: function (){},
  24493. onclose: function (t, ok){
  24494. return ok ? this.onok() : this.oncancel();
  24495. },
  24496. //是否控制dialog中的scroll事件, 默认为不阻止
  24497. holdScroll: false
  24498. },options));
  24499. this.initDialog();
  24500. };
  24501. var modalMask;
  24502. var dragMask;
  24503. var activeDialog;
  24504. Dialog.prototype = {
  24505. draggable: false,
  24506. uiName: 'dialog',
  24507. initDialog: function (){
  24508. var me = this,
  24509. theme=this.editor.options.theme;
  24510. if(this.cssRules){
  24511. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24512. }
  24513. this.initUIBase();
  24514. this.modalMask = (modalMask || (modalMask = new Mask({
  24515. className: 'edui-dialog-modalmask',
  24516. theme:theme,
  24517. onclick: function (){
  24518. activeDialog && activeDialog.close(false);
  24519. }
  24520. })));
  24521. this.dragMask = (dragMask || (dragMask = new Mask({
  24522. className: 'edui-dialog-dragmask',
  24523. theme:theme
  24524. })));
  24525. this.closeButton = new Button({
  24526. className: 'edui-dialog-closebutton',
  24527. title: me.closeDialog,
  24528. theme:theme,
  24529. onclick: function (){
  24530. me.close(false);
  24531. }
  24532. });
  24533. this.fullscreen && this.initResizeEvent();
  24534. if (this.buttons) {
  24535. for (var i=0; i<this.buttons.length; i++) {
  24536. if (!(this.buttons[i] instanceof Button)) {
  24537. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24538. editor : this.editor
  24539. },true));
  24540. }
  24541. }
  24542. }
  24543. },
  24544. initResizeEvent: function () {
  24545. var me = this;
  24546. domUtils.on( window, "resize", function () {
  24547. if ( me._hidden || me._hidden === undefined ) {
  24548. return;
  24549. }
  24550. if ( me.__resizeTimer ) {
  24551. window.clearTimeout( me.__resizeTimer );
  24552. }
  24553. me.__resizeTimer = window.setTimeout( function () {
  24554. me.__resizeTimer = null;
  24555. var dialogWrapNode = me.getDom(),
  24556. contentNode = me.getDom('content'),
  24557. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24558. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24559. vpRect = uiUtils.getViewportRect();
  24560. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24561. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24562. dialogWrapNode.style.width = vpRect.width + "px";
  24563. dialogWrapNode.style.height = vpRect.height + "px";
  24564. me.fireEvent( "resize" );
  24565. }, 100 );
  24566. } );
  24567. },
  24568. fitSize: function (){
  24569. var popBodyEl = this.getDom('body');
  24570. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24571. // uiUtils.removeStyle(popBodyEl, 'width');
  24572. // uiUtils.removeStyle(popBodyEl, 'height');
  24573. // }
  24574. var size = this.mesureSize();
  24575. popBodyEl.style.width = size.width + 'px';
  24576. popBodyEl.style.height = size.height + 'px';
  24577. return size;
  24578. },
  24579. safeSetOffset: function (offset){
  24580. var me = this;
  24581. var el = me.getDom();
  24582. var vpRect = uiUtils.getViewportRect();
  24583. var rect = uiUtils.getClientRect(el);
  24584. var left = offset.left;
  24585. if (left + rect.width > vpRect.right) {
  24586. left = vpRect.right - rect.width;
  24587. }
  24588. var top = offset.top;
  24589. if (top + rect.height > vpRect.bottom) {
  24590. top = vpRect.bottom - rect.height;
  24591. }
  24592. el.style.left = Math.max(left, 0) + 'px';
  24593. el.style.top = Math.max(top, 0) + 'px';
  24594. },
  24595. showAtCenter: function (){
  24596. var vpRect = uiUtils.getViewportRect();
  24597. if ( !this.fullscreen ) {
  24598. this.getDom().style.display = '';
  24599. var popSize = this.fitSize();
  24600. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24601. var left = vpRect.width / 2 - popSize.width / 2;
  24602. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24603. var popEl = this.getDom();
  24604. this.safeSetOffset({
  24605. left: Math.max(left | 0, 0),
  24606. top: Math.max(top | 0, 0)
  24607. });
  24608. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24609. popEl.className += ' edui-state-centered';
  24610. }
  24611. } else {
  24612. var dialogWrapNode = this.getDom(),
  24613. contentNode = this.getDom('content');
  24614. dialogWrapNode.style.display = "block";
  24615. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24616. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24617. dialogWrapNode.style.left = "-100000px";
  24618. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24619. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24620. dialogWrapNode.style.width = vpRect.width + "px";
  24621. dialogWrapNode.style.height = vpRect.height + "px";
  24622. dialogWrapNode.style.left = 0;
  24623. //保存环境的overflow值
  24624. this._originalContext = {
  24625. html: {
  24626. overflowX: document.documentElement.style.overflowX,
  24627. overflowY: document.documentElement.style.overflowY
  24628. },
  24629. body: {
  24630. overflowX: document.body.style.overflowX,
  24631. overflowY: document.body.style.overflowY
  24632. }
  24633. };
  24634. document.documentElement.style.overflowX = 'hidden';
  24635. document.documentElement.style.overflowY = 'hidden';
  24636. document.body.style.overflowX = 'hidden';
  24637. document.body.style.overflowY = 'hidden';
  24638. }
  24639. this._show();
  24640. },
  24641. getContentHtml: function (){
  24642. var contentHtml = '';
  24643. if (typeof this.content == 'string') {
  24644. contentHtml = this.content;
  24645. } else if (this.iframeUrl) {
  24646. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24647. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24648. }
  24649. return contentHtml;
  24650. },
  24651. getHtmlTpl: function (){
  24652. var footHtml = '';
  24653. if (this.buttons) {
  24654. var buff = [];
  24655. for (var i=0; i<this.buttons.length; i++) {
  24656. buff[i] = this.buttons[i].renderHtml();
  24657. }
  24658. footHtml = '<div class="%%-foot">' +
  24659. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24660. '</div>';
  24661. }
  24662. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24663. '<div class="%%-shadow"></div>' +
  24664. '<div id="##_titlebar" class="%%-titlebar">' +
  24665. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24666. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24667. '</div>' +
  24668. this.closeButton.renderHtml() +
  24669. '</div>' +
  24670. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24671. footHtml +
  24672. '</div></div></div>';
  24673. },
  24674. postRender: function (){
  24675. // todo: 保持居中/记住上次关闭位置选项
  24676. if (!this.modalMask.getDom()) {
  24677. this.modalMask.render();
  24678. this.modalMask.hide();
  24679. }
  24680. if (!this.dragMask.getDom()) {
  24681. this.dragMask.render();
  24682. this.dragMask.hide();
  24683. }
  24684. var me = this;
  24685. this.addListener('show', function (){
  24686. me.modalMask.show(this.getDom().style.zIndex - 2);
  24687. });
  24688. this.addListener('hide', function (){
  24689. me.modalMask.hide();
  24690. });
  24691. if (this.buttons) {
  24692. for (var i=0; i<this.buttons.length; i++) {
  24693. this.buttons[i].postRender();
  24694. }
  24695. }
  24696. domUtils.on(window, 'resize', function (){
  24697. setTimeout(function (){
  24698. if (!me.isHidden()) {
  24699. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24700. }
  24701. });
  24702. });
  24703. //hold住scroll事件,防止dialog的滚动影响页面
  24704. // if( this.holdScroll ) {
  24705. //
  24706. // if( !me.iframeUrl ) {
  24707. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24708. // domUtils.preventDefault(e);
  24709. // } );
  24710. // } else {
  24711. // me.addListener('dialogafterreset', function(){
  24712. // window.setTimeout(function(){
  24713. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24714. //
  24715. // if( browser.ie ) {
  24716. //
  24717. // var timer = window.setInterval(function(){
  24718. //
  24719. // if( iframeWindow.document && iframeWindow.document.body ) {
  24720. // window.clearInterval( timer );
  24721. // timer = null;
  24722. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24723. // domUtils.preventDefault(e);
  24724. // } );
  24725. // }
  24726. //
  24727. // }, 100);
  24728. //
  24729. // } else {
  24730. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24731. // domUtils.preventDefault(e);
  24732. // } );
  24733. // }
  24734. //
  24735. // }, 1);
  24736. // });
  24737. // }
  24738. //
  24739. // }
  24740. this._hide();
  24741. },
  24742. mesureSize: function (){
  24743. var body = this.getDom('body');
  24744. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24745. var dialogBodyStyle = body.style;
  24746. dialogBodyStyle.width = width;
  24747. return uiUtils.getClientRect(body);
  24748. },
  24749. _onTitlebarMouseDown: function (evt, el){
  24750. if (this.draggable) {
  24751. var rect;
  24752. var vpRect = uiUtils.getViewportRect();
  24753. var me = this;
  24754. uiUtils.startDrag(evt, {
  24755. ondragstart: function (){
  24756. rect = uiUtils.getClientRect(me.getDom());
  24757. me.getDom('contmask').style.visibility = 'visible';
  24758. me.dragMask.show(me.getDom().style.zIndex - 1);
  24759. },
  24760. ondragmove: function (x, y){
  24761. var left = rect.left + x;
  24762. var top = rect.top + y;
  24763. me.safeSetOffset({
  24764. left: left,
  24765. top: top
  24766. });
  24767. },
  24768. ondragstop: function (){
  24769. me.getDom('contmask').style.visibility = 'hidden';
  24770. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  24771. me.dragMask.hide();
  24772. }
  24773. });
  24774. }
  24775. },
  24776. reset: function (){
  24777. this.getDom('content').innerHTML = this.getContentHtml();
  24778. this.fireEvent('dialogafterreset');
  24779. },
  24780. _show: function (){
  24781. if (this._hidden) {
  24782. this.getDom().style.display = '';
  24783. //要高过编辑器的zindxe
  24784. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  24785. this._hidden = false;
  24786. this.fireEvent('show');
  24787. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  24788. }
  24789. },
  24790. isHidden: function (){
  24791. return this._hidden;
  24792. },
  24793. _hide: function (){
  24794. if (!this._hidden) {
  24795. var wrapNode = this.getDom();
  24796. wrapNode.style.display = 'none';
  24797. wrapNode.style.zIndex = '';
  24798. wrapNode.style.width = '';
  24799. wrapNode.style.height = '';
  24800. this._hidden = true;
  24801. this.fireEvent('hide');
  24802. }
  24803. },
  24804. open: function (){
  24805. if (this.autoReset) {
  24806. //有可能还没有渲染
  24807. try{
  24808. this.reset();
  24809. }catch(e){
  24810. this.render();
  24811. this.open()
  24812. }
  24813. }
  24814. this.showAtCenter();
  24815. if (this.iframeUrl) {
  24816. try {
  24817. this.getDom('iframe').focus();
  24818. } catch(ex){}
  24819. }
  24820. activeDialog = this;
  24821. },
  24822. _onCloseButtonClick: function (evt, el){
  24823. this.close(false);
  24824. },
  24825. close: function (ok){
  24826. if (this.fireEvent('close', ok) !== false) {
  24827. //还原环境
  24828. if ( this.fullscreen ) {
  24829. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  24830. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  24831. document.body.style.overflowX = this._originalContext.body.overflowX;
  24832. document.body.style.overflowY = this._originalContext.body.overflowY;
  24833. delete this._originalContext;
  24834. }
  24835. this._hide();
  24836. //销毁content
  24837. var content = this.getDom('content');
  24838. var iframe = this.getDom('iframe');
  24839. if (content && iframe) {
  24840. var doc = iframe.contentDocument || iframe.contentWindow.document;
  24841. doc && (doc.body.innerHTML = '');
  24842. domUtils.remove(content);
  24843. }
  24844. }
  24845. }
  24846. };
  24847. utils.inherits(Dialog, UIBase);
  24848. })();
  24849. // ui/menubutton.js
  24850. ///import core
  24851. ///import uicore
  24852. ///import ui/menu.js
  24853. ///import ui/splitbutton.js
  24854. (function (){
  24855. var utils = baidu.editor.utils,
  24856. Menu = baidu.editor.ui.Menu,
  24857. SplitButton = baidu.editor.ui.SplitButton,
  24858. MenuButton = baidu.editor.ui.MenuButton = function (options){
  24859. this.initOptions(options);
  24860. this.initMenuButton();
  24861. };
  24862. MenuButton.prototype = {
  24863. initMenuButton: function (){
  24864. var me = this;
  24865. this.uiName = "menubutton";
  24866. this.popup = new Menu({
  24867. items: me.items,
  24868. className: me.className,
  24869. editor:me.editor
  24870. });
  24871. this.popup.addListener('show', function (){
  24872. var list = this;
  24873. for (var i=0; i<list.items.length; i++) {
  24874. list.items[i].removeState('checked');
  24875. if (list.items[i].value == me._value) {
  24876. list.items[i].addState('checked');
  24877. this.value = me._value;
  24878. }
  24879. }
  24880. });
  24881. this.initSplitButton();
  24882. },
  24883. setValue : function(value){
  24884. this._value = value;
  24885. }
  24886. };
  24887. utils.inherits(MenuButton, SplitButton);
  24888. })();
  24889. // ui/multiMenu.js
  24890. ///import core
  24891. ///import uicore
  24892. ///commands 表情
  24893. (function(){
  24894. var utils = baidu.editor.utils,
  24895. Popup = baidu.editor.ui.Popup,
  24896. SplitButton = baidu.editor.ui.SplitButton,
  24897. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  24898. this.initOptions(options);
  24899. this.initMultiMenu();
  24900. };
  24901. MultiMenuPop.prototype = {
  24902. initMultiMenu: function (){
  24903. var me = this;
  24904. this.popup = new Popup({
  24905. content: '',
  24906. editor : me.editor,
  24907. iframe_rendered: false,
  24908. onshow: function (){
  24909. if (!this.iframe_rendered) {
  24910. this.iframe_rendered = true;
  24911. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  24912. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  24913. }
  24914. }
  24915. // canSideUp:false,
  24916. // canSideLeft:false
  24917. });
  24918. this.onbuttonclick = function(){
  24919. this.showPopup();
  24920. };
  24921. this.initSplitButton();
  24922. }
  24923. };
  24924. utils.inherits(MultiMenuPop, SplitButton);
  24925. })();
  24926. // ui/shortcutmenu.js
  24927. (function () {
  24928. var UI = baidu.editor.ui,
  24929. UIBase = UI.UIBase,
  24930. uiUtils = UI.uiUtils,
  24931. utils = baidu.editor.utils,
  24932. domUtils = baidu.editor.dom.domUtils;
  24933. var allMenus = [],//存储所有快捷菜单
  24934. timeID,
  24935. isSubMenuShow = false;//是否有子pop显示
  24936. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  24937. this.initOptions (options);
  24938. this.initShortCutMenu ();
  24939. };
  24940. ShortCutMenu.postHide = hideAllMenu;
  24941. ShortCutMenu.prototype = {
  24942. isHidden : true ,
  24943. SPACE : 5 ,
  24944. initShortCutMenu : function () {
  24945. this.items = this.items || [];
  24946. this.initUIBase ();
  24947. this.initItems ();
  24948. this.initEvent ();
  24949. allMenus.push (this);
  24950. } ,
  24951. initEvent : function () {
  24952. var me = this,
  24953. doc = me.editor.document;
  24954. domUtils.on (doc , "mousemove" , function (e) {
  24955. if (me.isHidden === false) {
  24956. //有pop显示就不隐藏快捷菜单
  24957. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  24958. var flag = true,
  24959. el = me.getDom (),
  24960. wt = el.offsetWidth,
  24961. ht = el.offsetHeight,
  24962. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  24963. distanceY = ht / 2,//距离中心Y标准
  24964. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  24965. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  24966. clearTimeout (timeID);
  24967. timeID = setTimeout (function () {
  24968. if (y > 0 && y < distanceY) {
  24969. me.setOpacity (el , "1");
  24970. } else if (y > distanceY && y < distanceY + 70) {
  24971. me.setOpacity (el , "0.5");
  24972. flag = false;
  24973. } else if (y > distanceY + 70 && y < distanceY + 140) {
  24974. me.hide ();
  24975. }
  24976. if (flag && x > 0 && x < distanceX) {
  24977. me.setOpacity (el , "1")
  24978. } else if (x > distanceX && x < distanceX + 70) {
  24979. me.setOpacity (el , "0.5")
  24980. } else if (x > distanceX + 70 && x < distanceX + 140) {
  24981. me.hide ();
  24982. }
  24983. });
  24984. }
  24985. });
  24986. //ie\ff下 mouseout不准
  24987. if (browser.chrome) {
  24988. domUtils.on (doc , "mouseout" , function (e) {
  24989. var relatedTgt = e.relatedTarget || e.toElement;
  24990. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  24991. me.hide ();
  24992. }
  24993. });
  24994. }
  24995. me.editor.addListener ("afterhidepop" , function () {
  24996. if (!me.isHidden) {
  24997. isSubMenuShow = true;
  24998. }
  24999. });
  25000. } ,
  25001. initItems : function () {
  25002. if (utils.isArray (this.items)) {
  25003. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25004. var item = this.items[i].toLowerCase ();
  25005. if (UI[item]) {
  25006. this.items[i] = new UI[item] (this.editor);
  25007. this.items[i].className += " edui-shortcutsubmenu ";
  25008. }
  25009. }
  25010. }
  25011. } ,
  25012. setOpacity : function (el , value) {
  25013. if (browser.ie && browser.version < 9) {
  25014. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25015. } else {
  25016. el.style.opacity = value;
  25017. }
  25018. } ,
  25019. getSubMenuMark : function () {
  25020. isSubMenuShow = false;
  25021. var layerEle = uiUtils.getFixedLayer ();
  25022. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25023. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25024. });
  25025. for (var i = 0, node ; node = list[i++] ;) {
  25026. if (node.style.display != "none") {
  25027. isSubMenuShow = true;
  25028. }
  25029. }
  25030. return isSubMenuShow;
  25031. } ,
  25032. show : function (e , hasContextmenu) {
  25033. var me = this,
  25034. offset = {},
  25035. el = this.getDom (),
  25036. fixedlayer = uiUtils.getFixedLayer ();
  25037. function setPos (offset) {
  25038. if (offset.left < 0) {
  25039. offset.left = 0;
  25040. }
  25041. if (offset.top < 0) {
  25042. offset.top = 0;
  25043. }
  25044. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25045. }
  25046. function setPosByCxtMenu (menu) {
  25047. if (!menu.tagName) {
  25048. menu = menu.getDom ();
  25049. }
  25050. offset.left = parseInt (menu.style.left);
  25051. offset.top = parseInt (menu.style.top);
  25052. offset.top -= el.offsetHeight + 15;
  25053. setPos (offset);
  25054. }
  25055. me.eventType = e.type;
  25056. el.style.cssText = "display:block;left:-9999px";
  25057. if (e.type == "contextmenu" && hasContextmenu) {
  25058. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25059. if (menu) {
  25060. setPosByCxtMenu (menu)
  25061. } else {
  25062. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25063. setPosByCxtMenu (menu);
  25064. });
  25065. }
  25066. } else {
  25067. offset = uiUtils.getViewportOffsetByEvent (e);
  25068. offset.top -= el.offsetHeight + me.SPACE;
  25069. offset.left += me.SPACE + 20;
  25070. setPos (offset);
  25071. me.setOpacity (el , 0.2);
  25072. }
  25073. me.isHidden = false;
  25074. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25075. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25076. if (me.editor) {
  25077. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25078. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25079. }
  25080. } ,
  25081. hide : function () {
  25082. if (this.getDom ()) {
  25083. this.getDom ().style.display = "none";
  25084. }
  25085. this.isHidden = true;
  25086. } ,
  25087. postRender : function () {
  25088. if (utils.isArray (this.items)) {
  25089. for (var i = 0, item ; item = this.items[i++] ;) {
  25090. item.postRender ();
  25091. }
  25092. }
  25093. } ,
  25094. getHtmlTpl : function () {
  25095. var buff;
  25096. if (utils.isArray (this.items)) {
  25097. buff = [];
  25098. for (var i = 0 ; i < this.items.length ; i++) {
  25099. buff[i] = this.items[i].renderHtml ();
  25100. }
  25101. buff = buff.join ("");
  25102. } else {
  25103. buff = this.items;
  25104. }
  25105. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25106. buff +
  25107. '</div>';
  25108. }
  25109. };
  25110. utils.inherits (ShortCutMenu , UIBase);
  25111. function hideAllMenu (e) {
  25112. var tgt = e.target || e.srcElement,
  25113. cur = domUtils.findParent (tgt , function (node) {
  25114. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25115. } , true);
  25116. if (!cur) {
  25117. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25118. menu.hide ()
  25119. }
  25120. }
  25121. }
  25122. domUtils.on (document , 'mousedown' , function (e) {
  25123. hideAllMenu (e);
  25124. });
  25125. domUtils.on (window , 'scroll' , function (e) {
  25126. hideAllMenu (e);
  25127. });
  25128. }) ();
  25129. // ui/breakline.js
  25130. (function (){
  25131. var utils = baidu.editor.utils,
  25132. UIBase = baidu.editor.ui.UIBase,
  25133. Breakline = baidu.editor.ui.Breakline = function (options){
  25134. this.initOptions(options);
  25135. this.initSeparator();
  25136. };
  25137. Breakline.prototype = {
  25138. uiName: 'Breakline',
  25139. initSeparator: function (){
  25140. this.initUIBase();
  25141. },
  25142. getHtmlTpl: function (){
  25143. return '<br/>';
  25144. }
  25145. };
  25146. utils.inherits(Breakline, UIBase);
  25147. })();
  25148. // adapter/editorui.js
  25149. //ui跟编辑器的适配層
  25150. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25151. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25152. (function () {
  25153. var utils = baidu.editor.utils;
  25154. var editorui = baidu.editor.ui;
  25155. var _Dialog = editorui.Dialog;
  25156. editorui.buttons = {};
  25157. editorui.Dialog = function (options) {
  25158. var dialog = new _Dialog(options);
  25159. dialog.addListener('hide', function () {
  25160. if (dialog.editor) {
  25161. var editor = dialog.editor;
  25162. try {
  25163. if (browser.gecko) {
  25164. var y = editor.window.scrollY,
  25165. x = editor.window.scrollX;
  25166. editor.body.focus();
  25167. editor.window.scrollTo(x, y);
  25168. } else {
  25169. editor.focus();
  25170. }
  25171. } catch (ex) {
  25172. }
  25173. }
  25174. });
  25175. return dialog;
  25176. };
  25177. var iframeUrlMap = {
  25178. 'anchor':'~/dialogs/anchor/anchor.html',
  25179. 'insertimage':'~/dialogs/image/image.html',
  25180. 'link':'~/dialogs/link/link.html',
  25181. 'spechars':'~/dialogs/spechars/spechars.html',
  25182. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25183. 'map':'~/dialogs/map/map.html',
  25184. 'gmap':'~/dialogs/gmap/gmap.html',
  25185. 'insertvideo':'~/dialogs/video/video.html',
  25186. 'help':'~/dialogs/help/help.html',
  25187. 'preview':'~/dialogs/preview/preview.html',
  25188. 'emotion':'~/dialogs/emotion/emotion.html',
  25189. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25190. 'attachment':'~/dialogs/attachment/attachment.html',
  25191. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25192. 'edittip':'~/dialogs/table/edittip.html',
  25193. 'edittable':'~/dialogs/table/edittable.html',
  25194. 'edittd':'~/dialogs/table/edittd.html',
  25195. 'webapp':'~/dialogs/webapp/webapp.html',
  25196. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25197. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25198. 'music':'~/dialogs/music/music.html',
  25199. 'template':'~/dialogs/template/template.html',
  25200. 'background':'~/dialogs/background/background.html',
  25201. 'charts': '~/dialogs/charts/charts.html'
  25202. };
  25203. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25204. var btnCmds = ['undo', 'redo', 'formatmatch',
  25205. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25206. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25207. 'blockquote', 'pasteplain', 'pagebreak',
  25208. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25209. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25210. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25211. for (var i = 0, ci; ci = btnCmds[i++];) {
  25212. ci = ci.toLowerCase();
  25213. editorui[ci] = function (cmd) {
  25214. return function (editor) {
  25215. var ui = new editorui.Button({
  25216. className:'edui-for-' + cmd,
  25217. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25218. onclick:function () {
  25219. editor.execCommand(cmd);
  25220. },
  25221. theme:editor.options.theme,
  25222. showText:false
  25223. });
  25224. editorui.buttons[cmd] = ui;
  25225. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25226. var state = editor.queryCommandState(cmd);
  25227. if (state == -1) {
  25228. ui.setDisabled(true);
  25229. ui.setChecked(false);
  25230. } else {
  25231. if (!uiReady) {
  25232. ui.setDisabled(false);
  25233. ui.setChecked(state);
  25234. }
  25235. }
  25236. });
  25237. return ui;
  25238. };
  25239. }(ci);
  25240. }
  25241. //清除文档
  25242. editorui.cleardoc = function (editor) {
  25243. var ui = new editorui.Button({
  25244. className:'edui-for-cleardoc',
  25245. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25246. theme:editor.options.theme,
  25247. onclick:function () {
  25248. if (confirm(editor.getLang("confirmClear"))) {
  25249. editor.execCommand('cleardoc');
  25250. }
  25251. }
  25252. });
  25253. editorui.buttons["cleardoc"] = ui;
  25254. editor.addListener('selectionchange', function () {
  25255. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25256. });
  25257. return ui;
  25258. };
  25259. //排版,图片排版,文字方向
  25260. var typeset = {
  25261. 'justify':['left', 'right', 'center', 'justify'],
  25262. 'imagefloat':['none', 'left', 'center', 'right'],
  25263. 'directionality':['ltr', 'rtl']
  25264. };
  25265. for (var p in typeset) {
  25266. (function (cmd, val) {
  25267. for (var i = 0, ci; ci = val[i++];) {
  25268. (function (cmd2) {
  25269. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25270. var ui = new editorui.Button({
  25271. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25272. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25273. theme:editor.options.theme,
  25274. onclick:function () {
  25275. editor.execCommand(cmd, cmd2);
  25276. }
  25277. });
  25278. editorui.buttons[cmd] = ui;
  25279. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25280. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25281. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25282. });
  25283. return ui;
  25284. };
  25285. })(ci)
  25286. }
  25287. })(p, typeset[p])
  25288. }
  25289. //字体颜色和背景颜色
  25290. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25291. editorui[ci] = function (cmd) {
  25292. return function (editor) {
  25293. var ui = new editorui.ColorButton({
  25294. className:'edui-for-' + cmd,
  25295. color:'default',
  25296. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25297. editor:editor,
  25298. onpickcolor:function (t, color) {
  25299. editor.execCommand(cmd, color);
  25300. },
  25301. onpicknocolor:function () {
  25302. editor.execCommand(cmd, 'default');
  25303. this.setColor('transparent');
  25304. this.color = 'default';
  25305. },
  25306. onbuttonclick:function () {
  25307. editor.execCommand(cmd, this.color);
  25308. }
  25309. });
  25310. editorui.buttons[cmd] = ui;
  25311. editor.addListener('selectionchange', function () {
  25312. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25313. });
  25314. return ui;
  25315. };
  25316. }(ci);
  25317. }
  25318. var dialogBtns = {
  25319. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25320. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25321. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25322. };
  25323. for (var p in dialogBtns) {
  25324. (function (type, vals) {
  25325. for (var i = 0, ci; ci = vals[i++];) {
  25326. //todo opera下存在问题
  25327. if (browser.opera && ci === "searchreplace") {
  25328. continue;
  25329. }
  25330. (function (cmd) {
  25331. editorui[cmd] = function (editor, iframeUrl, title) {
  25332. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25333. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25334. var dialog;
  25335. //没有iframeUrl不创建dialog
  25336. if (iframeUrl) {
  25337. dialog = new editorui.Dialog(utils.extend({
  25338. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25339. editor:editor,
  25340. className:'edui-for-' + cmd,
  25341. title:title,
  25342. holdScroll: cmd === 'insertimage',
  25343. fullscreen: /charts|preview/.test(cmd),
  25344. closeDialog:editor.getLang("closeDialog")
  25345. }, type == 'ok' ? {
  25346. buttons:[
  25347. {
  25348. className:'edui-okbutton',
  25349. label:editor.getLang("ok"),
  25350. editor:editor,
  25351. onclick:function () {
  25352. dialog.close(true);
  25353. }
  25354. },
  25355. {
  25356. className:'edui-cancelbutton',
  25357. label:editor.getLang("cancel"),
  25358. editor:editor,
  25359. onclick:function () {
  25360. dialog.close(false);
  25361. }
  25362. }
  25363. ]
  25364. } : {}));
  25365. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25366. }
  25367. var ui = new editorui.Button({
  25368. className:'edui-for-' + cmd,
  25369. title:title,
  25370. onclick:function () {
  25371. if (dialog) {
  25372. switch (cmd) {
  25373. case "wordimage":
  25374. var images = editor.execCommand("wordimage");
  25375. if (images && images.length) {
  25376. dialog.render();
  25377. dialog.open();
  25378. }
  25379. break;
  25380. case "scrawl":
  25381. if (editor.queryCommandState("scrawl") != -1) {
  25382. dialog.render();
  25383. dialog.open();
  25384. }
  25385. break;
  25386. default:
  25387. dialog.render();
  25388. dialog.open();
  25389. }
  25390. }
  25391. },
  25392. theme:editor.options.theme,
  25393. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25394. });
  25395. editorui.buttons[cmd] = ui;
  25396. editor.addListener('selectionchange', function () {
  25397. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25398. var unNeedCheckState = {'edittable':1};
  25399. if (cmd in unNeedCheckState)return;
  25400. var state = editor.queryCommandState(cmd);
  25401. if (ui.getDom()) {
  25402. ui.setDisabled(state == -1);
  25403. ui.setChecked(state);
  25404. }
  25405. });
  25406. return ui;
  25407. };
  25408. })(ci.toLowerCase())
  25409. }
  25410. })(p, dialogBtns[p]);
  25411. }
  25412. editorui.snapscreen = function (editor, iframeUrl, title) {
  25413. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25414. var ui = new editorui.Button({
  25415. className:'edui-for-snapscreen',
  25416. title:title,
  25417. onclick:function () {
  25418. editor.execCommand("snapscreen");
  25419. },
  25420. theme:editor.options.theme
  25421. });
  25422. editorui.buttons['snapscreen'] = ui;
  25423. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25424. if (iframeUrl) {
  25425. var dialog = new editorui.Dialog({
  25426. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25427. editor:editor,
  25428. className:'edui-for-snapscreen',
  25429. title:title,
  25430. buttons:[
  25431. {
  25432. className:'edui-okbutton',
  25433. label:editor.getLang("ok"),
  25434. editor:editor,
  25435. onclick:function () {
  25436. dialog.close(true);
  25437. }
  25438. },
  25439. {
  25440. className:'edui-cancelbutton',
  25441. label:editor.getLang("cancel"),
  25442. editor:editor,
  25443. onclick:function () {
  25444. dialog.close(false);
  25445. }
  25446. }
  25447. ]
  25448. });
  25449. dialog.render();
  25450. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25451. }
  25452. editor.addListener('selectionchange', function () {
  25453. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25454. });
  25455. return ui;
  25456. };
  25457. editorui.insertcode = function (editor, list, title) {
  25458. list = editor.options['insertcode'] || [];
  25459. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25460. // if (!list.length) return;
  25461. var items = [];
  25462. utils.each(list,function(key,val){
  25463. items.push({
  25464. label:key,
  25465. value:val,
  25466. theme:editor.options.theme,
  25467. renderLabelHtml:function () {
  25468. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25469. }
  25470. });
  25471. });
  25472. var ui = new editorui.Combox({
  25473. editor:editor,
  25474. items:items,
  25475. onselect:function (t, index) {
  25476. editor.execCommand('insertcode', this.items[index].value);
  25477. },
  25478. onbuttonclick:function () {
  25479. this.showPopup();
  25480. },
  25481. title:title,
  25482. initValue:title,
  25483. className:'edui-for-insertcode',
  25484. indexByValue:function (value) {
  25485. if (value) {
  25486. for (var i = 0, ci; ci = this.items[i]; i++) {
  25487. if (ci.value.indexOf(value) != -1)
  25488. return i;
  25489. }
  25490. }
  25491. return -1;
  25492. }
  25493. });
  25494. editorui.buttons['insertcode'] = ui;
  25495. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25496. if (!uiReady) {
  25497. var state = editor.queryCommandState('insertcode');
  25498. if (state == -1) {
  25499. ui.setDisabled(true);
  25500. } else {
  25501. ui.setDisabled(false);
  25502. var value = editor.queryCommandValue('insertcode');
  25503. if(!value){
  25504. ui.setValue(title);
  25505. return;
  25506. }
  25507. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25508. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25509. ui.setValue(value);
  25510. }
  25511. }
  25512. });
  25513. return ui;
  25514. };
  25515. editorui.fontfamily = function (editor, list, title) {
  25516. list = editor.options['fontfamily'] || [];
  25517. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25518. if (!list.length) return;
  25519. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25520. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25521. (function (key, val) {
  25522. items.push({
  25523. label:key,
  25524. value:val,
  25525. theme:editor.options.theme,
  25526. renderLabelHtml:function () {
  25527. return '<div class="edui-label %%-label" style="font-family:' +
  25528. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25529. }
  25530. });
  25531. })(ci.label || langLabel, ci.val)
  25532. }
  25533. var ui = new editorui.Combox({
  25534. editor:editor,
  25535. items:items,
  25536. onselect:function (t, index) {
  25537. editor.execCommand('FontFamily', this.items[index].value);
  25538. },
  25539. onbuttonclick:function () {
  25540. this.showPopup();
  25541. },
  25542. title:title,
  25543. initValue:title,
  25544. className:'edui-for-fontfamily',
  25545. indexByValue:function (value) {
  25546. if (value) {
  25547. for (var i = 0, ci; ci = this.items[i]; i++) {
  25548. if (ci.value.indexOf(value) != -1)
  25549. return i;
  25550. }
  25551. }
  25552. return -1;
  25553. }
  25554. });
  25555. editorui.buttons['fontfamily'] = ui;
  25556. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25557. if (!uiReady) {
  25558. var state = editor.queryCommandState('FontFamily');
  25559. if (state == -1) {
  25560. ui.setDisabled(true);
  25561. } else {
  25562. ui.setDisabled(false);
  25563. var value = editor.queryCommandValue('FontFamily');
  25564. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25565. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25566. ui.setValue(value);
  25567. }
  25568. }
  25569. });
  25570. return ui;
  25571. };
  25572. editorui.fontsize = function (editor, list, title) {
  25573. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25574. list = list || editor.options['fontsize'] || [];
  25575. if (!list.length) return;
  25576. var items = [];
  25577. for (var i = 0; i < list.length; i++) {
  25578. var size = list[i] + 'px';
  25579. items.push({
  25580. label:size,
  25581. value:size,
  25582. theme:editor.options.theme,
  25583. renderLabelHtml:function () {
  25584. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25585. this.value + '">' + (this.label || '') + '</div>';
  25586. }
  25587. });
  25588. }
  25589. var ui = new editorui.Combox({
  25590. editor:editor,
  25591. items:items,
  25592. title:title,
  25593. initValue:title,
  25594. onselect:function (t, index) {
  25595. editor.execCommand('FontSize', this.items[index].value);
  25596. },
  25597. onbuttonclick:function () {
  25598. this.showPopup();
  25599. },
  25600. className:'edui-for-fontsize'
  25601. });
  25602. editorui.buttons['fontsize'] = ui;
  25603. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25604. if (!uiReady) {
  25605. var state = editor.queryCommandState('FontSize');
  25606. if (state == -1) {
  25607. ui.setDisabled(true);
  25608. } else {
  25609. ui.setDisabled(false);
  25610. ui.setValue(editor.queryCommandValue('FontSize'));
  25611. }
  25612. }
  25613. });
  25614. return ui;
  25615. };
  25616. editorui.paragraph = function (editor, list, title) {
  25617. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25618. list = editor.options['paragraph'] || [];
  25619. if (utils.isEmptyObject(list)) return;
  25620. var items = [];
  25621. for (var i in list) {
  25622. items.push({
  25623. value:i,
  25624. label:list[i] || editor.getLang("paragraph")[i],
  25625. theme:editor.options.theme,
  25626. renderLabelHtml:function () {
  25627. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25628. }
  25629. })
  25630. }
  25631. var ui = new editorui.Combox({
  25632. editor:editor,
  25633. items:items,
  25634. title:title,
  25635. initValue:title,
  25636. className:'edui-for-paragraph',
  25637. onselect:function (t, index) {
  25638. editor.execCommand('Paragraph', this.items[index].value);
  25639. },
  25640. onbuttonclick:function () {
  25641. this.showPopup();
  25642. }
  25643. });
  25644. editorui.buttons['paragraph'] = ui;
  25645. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25646. if (!uiReady) {
  25647. var state = editor.queryCommandState('Paragraph');
  25648. if (state == -1) {
  25649. ui.setDisabled(true);
  25650. } else {
  25651. ui.setDisabled(false);
  25652. var value = editor.queryCommandValue('Paragraph');
  25653. var index = ui.indexByValue(value);
  25654. if (index != -1) {
  25655. ui.setValue(value);
  25656. } else {
  25657. ui.setValue(ui.initValue);
  25658. }
  25659. }
  25660. }
  25661. });
  25662. return ui;
  25663. };
  25664. //自定义标题
  25665. editorui.customstyle = function (editor) {
  25666. var list = editor.options['customstyle'] || [],
  25667. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25668. if (!list.length)return;
  25669. var langCs = editor.getLang('customstyle');
  25670. for (var i = 0, items = [], t; t = list[i++];) {
  25671. (function (t) {
  25672. var ck = {};
  25673. ck.label = t.label ? t.label : langCs[t.name];
  25674. ck.style = t.style;
  25675. ck.className = t.className;
  25676. ck.tag = t.tag;
  25677. items.push({
  25678. label:ck.label,
  25679. value:ck,
  25680. theme:editor.options.theme,
  25681. renderLabelHtml:function () {
  25682. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  25683. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  25684. + '</div>';
  25685. }
  25686. });
  25687. })(t);
  25688. }
  25689. var ui = new editorui.Combox({
  25690. editor:editor,
  25691. items:items,
  25692. title:title,
  25693. initValue:title,
  25694. className:'edui-for-customstyle',
  25695. onselect:function (t, index) {
  25696. editor.execCommand('customstyle', this.items[index].value);
  25697. },
  25698. onbuttonclick:function () {
  25699. this.showPopup();
  25700. },
  25701. indexByValue:function (value) {
  25702. for (var i = 0, ti; ti = this.items[i++];) {
  25703. if (ti.label == value) {
  25704. return i - 1
  25705. }
  25706. }
  25707. return -1;
  25708. }
  25709. });
  25710. editorui.buttons['customstyle'] = ui;
  25711. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25712. if (!uiReady) {
  25713. var state = editor.queryCommandState('customstyle');
  25714. if (state == -1) {
  25715. ui.setDisabled(true);
  25716. } else {
  25717. ui.setDisabled(false);
  25718. var value = editor.queryCommandValue('customstyle');
  25719. var index = ui.indexByValue(value);
  25720. if (index != -1) {
  25721. ui.setValue(value);
  25722. } else {
  25723. ui.setValue(ui.initValue);
  25724. }
  25725. }
  25726. }
  25727. });
  25728. return ui;
  25729. };
  25730. editorui.inserttable = function (editor, iframeUrl, title) {
  25731. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  25732. var ui = new editorui.TableButton({
  25733. editor:editor,
  25734. title:title,
  25735. className:'edui-for-inserttable',
  25736. onpicktable:function (t, numCols, numRows) {
  25737. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  25738. },
  25739. onbuttonclick:function () {
  25740. this.showPopup();
  25741. }
  25742. });
  25743. editorui.buttons['inserttable'] = ui;
  25744. editor.addListener('selectionchange', function () {
  25745. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  25746. });
  25747. return ui;
  25748. };
  25749. editorui.lineheight = function (editor) {
  25750. var val = editor.options.lineheight || [];
  25751. if (!val.length)return;
  25752. for (var i = 0, ci, items = []; ci = val[i++];) {
  25753. items.push({
  25754. //todo:写死了
  25755. label:ci,
  25756. value:ci,
  25757. theme:editor.options.theme,
  25758. onclick:function () {
  25759. editor.execCommand("lineheight", this.value);
  25760. }
  25761. })
  25762. }
  25763. var ui = new editorui.MenuButton({
  25764. editor:editor,
  25765. className:'edui-for-lineheight',
  25766. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  25767. items:items,
  25768. onbuttonclick:function () {
  25769. var value = editor.queryCommandValue('LineHeight') || this.value;
  25770. editor.execCommand("LineHeight", value);
  25771. }
  25772. });
  25773. editorui.buttons['lineheight'] = ui;
  25774. editor.addListener('selectionchange', function () {
  25775. var state = editor.queryCommandState('LineHeight');
  25776. if (state == -1) {
  25777. ui.setDisabled(true);
  25778. } else {
  25779. ui.setDisabled(false);
  25780. var value = editor.queryCommandValue('LineHeight');
  25781. value && ui.setValue((value + '').replace(/cm/, ''));
  25782. ui.setChecked(state)
  25783. }
  25784. });
  25785. return ui;
  25786. };
  25787. var rowspacings = ['top', 'bottom'];
  25788. for (var r = 0, ri; ri = rowspacings[r++];) {
  25789. (function (cmd) {
  25790. editorui['rowspacing' + cmd] = function (editor) {
  25791. var val = editor.options['rowspacing' + cmd] || [];
  25792. if (!val.length) return null;
  25793. for (var i = 0, ci, items = []; ci = val[i++];) {
  25794. items.push({
  25795. label:ci,
  25796. value:ci,
  25797. theme:editor.options.theme,
  25798. onclick:function () {
  25799. editor.execCommand("rowspacing", this.value, cmd);
  25800. }
  25801. })
  25802. }
  25803. var ui = new editorui.MenuButton({
  25804. editor:editor,
  25805. className:'edui-for-rowspacing' + cmd,
  25806. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  25807. items:items,
  25808. onbuttonclick:function () {
  25809. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  25810. editor.execCommand("rowspacing", value, cmd);
  25811. }
  25812. });
  25813. editorui.buttons[cmd] = ui;
  25814. editor.addListener('selectionchange', function () {
  25815. var state = editor.queryCommandState('rowspacing', cmd);
  25816. if (state == -1) {
  25817. ui.setDisabled(true);
  25818. } else {
  25819. ui.setDisabled(false);
  25820. var value = editor.queryCommandValue('rowspacing', cmd);
  25821. value && ui.setValue((value + '').replace(/%/, ''));
  25822. ui.setChecked(state)
  25823. }
  25824. });
  25825. return ui;
  25826. }
  25827. })(ri)
  25828. }
  25829. //有序,无序列表
  25830. var lists = ['insertorderedlist', 'insertunorderedlist'];
  25831. for (var l = 0, cl; cl = lists[l++];) {
  25832. (function (cmd) {
  25833. editorui[cmd] = function (editor) {
  25834. var vals = editor.options[cmd],
  25835. _onMenuClick = function () {
  25836. editor.execCommand(cmd, this.value);
  25837. }, items = [];
  25838. for (var i in vals) {
  25839. items.push({
  25840. label:vals[i] || editor.getLang()[cmd][i] || "",
  25841. value:i,
  25842. theme:editor.options.theme,
  25843. onclick:_onMenuClick
  25844. })
  25845. }
  25846. var ui = new editorui.MenuButton({
  25847. editor:editor,
  25848. className:'edui-for-' + cmd,
  25849. title:editor.getLang("labelMap." + cmd) || '',
  25850. 'items':items,
  25851. onbuttonclick:function () {
  25852. var value = editor.queryCommandValue(cmd) || this.value;
  25853. editor.execCommand(cmd, value);
  25854. }
  25855. });
  25856. editorui.buttons[cmd] = ui;
  25857. editor.addListener('selectionchange', function () {
  25858. var state = editor.queryCommandState(cmd);
  25859. if (state == -1) {
  25860. ui.setDisabled(true);
  25861. } else {
  25862. ui.setDisabled(false);
  25863. var value = editor.queryCommandValue(cmd);
  25864. ui.setValue(value);
  25865. ui.setChecked(state)
  25866. }
  25867. });
  25868. return ui;
  25869. };
  25870. })(cl)
  25871. }
  25872. editorui.fullscreen = function (editor, title) {
  25873. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  25874. var ui = new editorui.Button({
  25875. className:'edui-for-fullscreen',
  25876. title:title,
  25877. theme:editor.options.theme,
  25878. onclick:function () {
  25879. if (editor.ui) {
  25880. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  25881. }
  25882. this.setChecked(editor.ui.isFullScreen());
  25883. }
  25884. });
  25885. editorui.buttons['fullscreen'] = ui;
  25886. editor.addListener('selectionchange', function () {
  25887. var state = editor.queryCommandState('fullscreen');
  25888. ui.setDisabled(state == -1);
  25889. ui.setChecked(editor.ui.isFullScreen());
  25890. });
  25891. return ui;
  25892. };
  25893. // 表情
  25894. editorui["emotion"] = function (editor, iframeUrl) {
  25895. var cmd = "emotion";
  25896. var ui = new editorui.MultiMenuPop({
  25897. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  25898. editor:editor,
  25899. className:'edui-for-' + cmd,
  25900. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  25901. });
  25902. editorui.buttons[cmd] = ui;
  25903. editor.addListener('selectionchange', function () {
  25904. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  25905. });
  25906. return ui;
  25907. };
  25908. editorui.autotypeset = function (editor) {
  25909. var ui = new editorui.AutoTypeSetButton({
  25910. editor:editor,
  25911. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  25912. className:'edui-for-autotypeset',
  25913. onbuttonclick:function () {
  25914. editor.execCommand('autotypeset')
  25915. }
  25916. });
  25917. editorui.buttons['autotypeset'] = ui;
  25918. editor.addListener('selectionchange', function () {
  25919. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  25920. });
  25921. return ui;
  25922. };
  25923. /* 简单上传插件 */
  25924. editorui["simpleupload"] = function (editor) {
  25925. var name = 'simpleupload',
  25926. ui = new editorui.Button({
  25927. className:'edui-for-' + name,
  25928. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  25929. onclick:function () {},
  25930. theme:editor.options.theme,
  25931. showText:false
  25932. });
  25933. editorui.buttons[name] = ui;
  25934. editor.addListener('ready', function() {
  25935. var b = ui.getDom('body'),
  25936. iconSpan = b.children[0];
  25937. editor.fireEvent('simpleuploadbtnready', iconSpan);
  25938. });
  25939. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25940. var state = editor.queryCommandState(name);
  25941. if (state == -1) {
  25942. ui.setDisabled(true);
  25943. ui.setChecked(false);
  25944. } else {
  25945. if (!uiReady) {
  25946. ui.setDisabled(false);
  25947. ui.setChecked(state);
  25948. }
  25949. }
  25950. });
  25951. return ui;
  25952. };
  25953. })();
  25954. // adapter/editor.js
  25955. ///import core
  25956. ///commands 全屏
  25957. ///commandsName FullScreen
  25958. ///commandsTitle 全屏
  25959. (function () {
  25960. var utils = baidu.editor.utils,
  25961. uiUtils = baidu.editor.ui.uiUtils,
  25962. UIBase = baidu.editor.ui.UIBase,
  25963. domUtils = baidu.editor.dom.domUtils;
  25964. var nodeStack = [];
  25965. function EditorUI(options) {
  25966. this.initOptions(options);
  25967. this.initEditorUI();
  25968. }
  25969. EditorUI.prototype = {
  25970. uiName:'editor',
  25971. initEditorUI:function () {
  25972. this.editor.ui = this;
  25973. this._dialogs = {};
  25974. this.initUIBase();
  25975. this._initToolbars();
  25976. var editor = this.editor,
  25977. me = this;
  25978. editor.addListener('ready', function () {
  25979. //提供getDialog方法
  25980. editor.getDialog = function (name) {
  25981. return editor.ui._dialogs[name + "Dialog"];
  25982. };
  25983. domUtils.on(editor.window, 'scroll', function (evt) {
  25984. baidu.editor.ui.Popup.postHide(evt);
  25985. });
  25986. //提供编辑器实时宽高(全屏时宽高不变化)
  25987. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  25988. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  25989. //display bottom-bar label based on config
  25990. if (editor.options.elementPathEnabled) {
  25991. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  25992. }
  25993. if (editor.options.wordCount) {
  25994. function countFn() {
  25995. setCount(editor,me);
  25996. domUtils.un(editor.document, "click", arguments.callee);
  25997. }
  25998. domUtils.on(editor.document, "click", countFn);
  25999. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26000. }
  26001. editor.ui._scale();
  26002. if (editor.options.scaleEnabled) {
  26003. if (editor.autoHeightEnabled) {
  26004. editor.disableAutoHeight();
  26005. }
  26006. me.enableScale();
  26007. } else {
  26008. me.disableScale();
  26009. }
  26010. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26011. editor.ui.getDom('elementpath').style.display = "none";
  26012. editor.ui.getDom('wordcount').style.display = "none";
  26013. editor.ui.getDom('scale').style.display = "none";
  26014. }
  26015. if (!editor.selection.isFocus())return;
  26016. editor.fireEvent('selectionchange', false, true);
  26017. });
  26018. editor.addListener('mousedown', function (t, evt) {
  26019. var el = evt.target || evt.srcElement;
  26020. baidu.editor.ui.Popup.postHide(evt, el);
  26021. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26022. });
  26023. editor.addListener("delcells", function () {
  26024. if (UE.ui['edittip']) {
  26025. new UE.ui['edittip'](editor);
  26026. }
  26027. editor.getDialog('edittip').open();
  26028. });
  26029. var pastePop, isPaste = false, timer;
  26030. editor.addListener("afterpaste", function () {
  26031. if(editor.queryCommandState('pasteplain'))
  26032. return;
  26033. if(baidu.editor.ui.PastePicker){
  26034. pastePop = new baidu.editor.ui.Popup({
  26035. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26036. editor:editor,
  26037. className:'edui-wordpastepop'
  26038. });
  26039. pastePop.render();
  26040. }
  26041. isPaste = true;
  26042. });
  26043. editor.addListener("afterinserthtml", function () {
  26044. clearTimeout(timer);
  26045. timer = setTimeout(function () {
  26046. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26047. if(pastePop.isHidden()){
  26048. var span = domUtils.createElement(editor.document, 'span', {
  26049. 'style':"line-height:0px;",
  26050. 'innerHTML':'\ufeff'
  26051. }),
  26052. range = editor.selection.getRange();
  26053. range.insertNode(span);
  26054. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26055. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26056. domUtils.remove(span);
  26057. }else{
  26058. pastePop.show();
  26059. }
  26060. delete editor.ui._isTransfer;
  26061. isPaste = false;
  26062. }
  26063. }, 200)
  26064. });
  26065. editor.addListener('contextmenu', function (t, evt) {
  26066. baidu.editor.ui.Popup.postHide(evt);
  26067. });
  26068. editor.addListener('keydown', function (t, evt) {
  26069. if (pastePop) pastePop.dispose(evt);
  26070. var keyCode = evt.keyCode || evt.which;
  26071. if(evt.altKey&&keyCode==90){
  26072. UE.ui.buttons['fullscreen'].onclick();
  26073. }
  26074. });
  26075. editor.addListener('wordcount', function (type) {
  26076. setCount(this,me);
  26077. });
  26078. function setCount(editor,ui) {
  26079. editor.setOpt({
  26080. wordCount:true,
  26081. maximumWords:10000,
  26082. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26083. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26084. });
  26085. var opt = editor.options,
  26086. max = opt.maximumWords,
  26087. msg = opt.wordCountMsg ,
  26088. errMsg = opt.wordOverFlowMsg,
  26089. countDom = ui.getDom('wordcount');
  26090. if (!opt.wordCount) {
  26091. return;
  26092. }
  26093. var count = editor.getContentLength(true);
  26094. if (count > max) {
  26095. countDom.innerHTML = errMsg;
  26096. editor.fireEvent("wordcountoverflow");
  26097. } else {
  26098. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26099. }
  26100. }
  26101. editor.addListener('selectionchange', function () {
  26102. if (editor.options.elementPathEnabled) {
  26103. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26104. }
  26105. if (editor.options.scaleEnabled) {
  26106. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26107. }
  26108. });
  26109. var popup = new baidu.editor.ui.Popup({
  26110. editor:editor,
  26111. content:'',
  26112. className:'edui-bubble',
  26113. _onEditButtonClick:function () {
  26114. this.hide();
  26115. editor.ui._dialogs.linkDialog.open();
  26116. },
  26117. _onImgEditButtonClick:function (name) {
  26118. this.hide();
  26119. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26120. },
  26121. _onImgSetFloat:function (value) {
  26122. this.hide();
  26123. editor.execCommand("imagefloat", value);
  26124. },
  26125. _setIframeAlign:function (value) {
  26126. var frame = popup.anchorEl;
  26127. var newFrame = frame.cloneNode(true);
  26128. switch (value) {
  26129. case -2:
  26130. newFrame.setAttribute("align", "");
  26131. break;
  26132. case -1:
  26133. newFrame.setAttribute("align", "left");
  26134. break;
  26135. case 1:
  26136. newFrame.setAttribute("align", "right");
  26137. break;
  26138. }
  26139. frame.parentNode.insertBefore(newFrame, frame);
  26140. domUtils.remove(frame);
  26141. popup.anchorEl = newFrame;
  26142. popup.showAnchor(popup.anchorEl);
  26143. },
  26144. _updateIframe:function () {
  26145. var frame = editor._iframe = popup.anchorEl;
  26146. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26147. editor.selection.getRange().selectNode(frame).select();
  26148. editor.ui._dialogs.mapDialog.open();
  26149. popup.hide();
  26150. } else {
  26151. editor.ui._dialogs.insertframeDialog.open();
  26152. popup.hide();
  26153. }
  26154. },
  26155. _onRemoveButtonClick:function (cmdName) {
  26156. editor.execCommand(cmdName);
  26157. this.hide();
  26158. },
  26159. queryAutoHide:function (el) {
  26160. if (el && el.ownerDocument == editor.document) {
  26161. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26162. return el !== popup.anchorEl;
  26163. }
  26164. }
  26165. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26166. }
  26167. });
  26168. popup.render();
  26169. if (editor.options.imagePopup) {
  26170. editor.addListener('mouseover', function (t, evt) {
  26171. evt = evt || window.event;
  26172. var el = evt.target || evt.srcElement;
  26173. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26174. var html = popup.formatHtml(
  26175. '<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;' +
  26176. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26177. if (html) {
  26178. popup.getDom('content').innerHTML = html;
  26179. popup.anchorEl = el;
  26180. popup.showAnchor(popup.anchorEl);
  26181. } else {
  26182. popup.hide();
  26183. }
  26184. }
  26185. });
  26186. editor.addListener('selectionchange', function (t, causeByUi) {
  26187. if (!causeByUi) return;
  26188. var html = '', str = "",
  26189. img = editor.selection.getRange().getClosedNode(),
  26190. dialogs = editor.ui._dialogs;
  26191. if (img && img.tagName == 'IMG') {
  26192. var dialogName = 'insertimageDialog';
  26193. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26194. dialogName = "insertvideoDialog"
  26195. }
  26196. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26197. dialogName = "webappDialog"
  26198. }
  26199. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26200. dialogName = "mapDialog"
  26201. }
  26202. if (img.className.indexOf("edui-faked-music") != -1) {
  26203. dialogName = "musicDialog"
  26204. }
  26205. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26206. dialogName = "gmapDialog"
  26207. }
  26208. if (img.getAttribute("anchorname")) {
  26209. dialogName = "anchorDialog";
  26210. html = popup.formatHtml(
  26211. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26212. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26213. }
  26214. if (img.getAttribute("word_img")) {
  26215. //todo 放到dialog去做查询
  26216. editor.word_img = [img.getAttribute("word_img")];
  26217. dialogName = "wordimageDialog"
  26218. }
  26219. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26220. dialogName = "";
  26221. }
  26222. if (!dialogs[dialogName]) {
  26223. return;
  26224. }
  26225. str = '<nobr>' + editor.getLang("property") + ': '+
  26226. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26227. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26228. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26229. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26230. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26231. !html && (html = popup.formatHtml(str))
  26232. }
  26233. if (editor.ui._dialogs.linkDialog) {
  26234. var link = editor.queryCommandValue('link');
  26235. var url;
  26236. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26237. var txt = url;
  26238. if (url.length > 30) {
  26239. txt = url.substring(0, 20) + "...";
  26240. }
  26241. if (html) {
  26242. html += '<div style="height:5px;"></div>'
  26243. }
  26244. html += popup.formatHtml(
  26245. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26246. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26247. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26248. popup.showAnchor(link);
  26249. }
  26250. }
  26251. if (html) {
  26252. popup.getDom('content').innerHTML = html;
  26253. popup.anchorEl = img || link;
  26254. popup.showAnchor(popup.anchorEl);
  26255. } else {
  26256. popup.hide();
  26257. }
  26258. });
  26259. }
  26260. },
  26261. _initToolbars:function () {
  26262. var editor = this.editor;
  26263. var toolbars = this.toolbars || [];
  26264. var toolbarUis = [];
  26265. for (var i = 0; i < toolbars.length; i++) {
  26266. var toolbar = toolbars[i];
  26267. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26268. for (var j = 0; j < toolbar.length; j++) {
  26269. var toolbarItem = toolbar[j];
  26270. var toolbarItemUi = null;
  26271. if (typeof toolbarItem == 'string') {
  26272. toolbarItem = toolbarItem.toLowerCase();
  26273. if (toolbarItem == '|') {
  26274. toolbarItem = 'Separator';
  26275. }
  26276. if(toolbarItem == '||'){
  26277. toolbarItem = 'Breakline';
  26278. }
  26279. if (baidu.editor.ui[toolbarItem]) {
  26280. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26281. }
  26282. //fullscreen这里单独处理一下,放到首行去
  26283. if (toolbarItem == 'fullscreen') {
  26284. if (toolbarUis && toolbarUis[0]) {
  26285. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26286. } else {
  26287. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26288. }
  26289. continue;
  26290. }
  26291. } else {
  26292. toolbarItemUi = toolbarItem;
  26293. }
  26294. if (toolbarItemUi && toolbarItemUi.id) {
  26295. toolbarUi.add(toolbarItemUi);
  26296. }
  26297. }
  26298. toolbarUis[i] = toolbarUi;
  26299. }
  26300. //接受外部定制的UI
  26301. utils.each(UE._customizeUI,function(obj,key){
  26302. var itemUI,index;
  26303. if(obj.id && obj.id != editor.key){
  26304. return false;
  26305. }
  26306. itemUI = obj.execFn.call(editor,editor,key);
  26307. if(itemUI){
  26308. index = obj.index;
  26309. if(index === undefined){
  26310. index = toolbarUi.items.length;
  26311. }
  26312. toolbarUi.add(itemUI,index)
  26313. }
  26314. });
  26315. this.toolbars = toolbarUis;
  26316. },
  26317. getHtmlTpl:function () {
  26318. return '<div id="##" class="%%">' +
  26319. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26320. (this.toolbars.length ?
  26321. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26322. this.renderToolbarBoxHtml() +
  26323. '</div></div>' : '') +
  26324. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26325. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26326. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26327. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26328. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26329. '</div>' +
  26330. '</div>' +
  26331. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  26332. //modify wdcount by matao
  26333. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26334. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26335. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26336. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26337. '</tr></table></div>' +
  26338. '<div id="##_scalelayer"></div>' +
  26339. '</div>';
  26340. },
  26341. showWordImageDialog:function () {
  26342. this._dialogs['wordimageDialog'].open();
  26343. },
  26344. renderToolbarBoxHtml:function () {
  26345. var buff = [];
  26346. for (var i = 0; i < this.toolbars.length; i++) {
  26347. buff.push(this.toolbars[i].renderHtml());
  26348. }
  26349. return buff.join('');
  26350. },
  26351. setFullScreen:function (fullscreen) {
  26352. var editor = this.editor,
  26353. container = editor.container.parentNode.parentNode;
  26354. if (this._fullscreen != fullscreen) {
  26355. this._fullscreen = fullscreen;
  26356. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26357. if (baidu.editor.browser.gecko) {
  26358. var bk = editor.selection.getRange().createBookmark();
  26359. }
  26360. if (fullscreen) {
  26361. while (container.tagName != "BODY") {
  26362. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26363. nodeStack.push(position);
  26364. container.style.position = "static";
  26365. container = container.parentNode;
  26366. }
  26367. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26368. this._bakBodyOverflow = document.body.style.overflow;
  26369. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26370. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26371. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26372. if (this._bakAutoHeight) {
  26373. //当全屏时不能执行自动长高
  26374. editor.autoHeightEnabled = false;
  26375. this.editor.disableAutoHeight();
  26376. }
  26377. document.documentElement.style.overflow = 'hidden';
  26378. //修复,滚动条不收起的问题
  26379. window.scrollTo(0,window.scrollY);
  26380. this._bakCssText = this.getDom().style.cssText;
  26381. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26382. editor.iframe.parentNode.style.width = '';
  26383. this._updateFullScreen();
  26384. } else {
  26385. while (container.tagName != "BODY") {
  26386. container.style.position = nodeStack.shift();
  26387. container = container.parentNode;
  26388. }
  26389. this.getDom().style.cssText = this._bakCssText;
  26390. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26391. if (this._bakAutoHeight) {
  26392. editor.autoHeightEnabled = true;
  26393. this.editor.enableAutoHeight();
  26394. }
  26395. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26396. document.body.style.overflow = this._bakBodyOverflow;
  26397. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26398. window.scrollTo(0, this._bakScrollTop);
  26399. }
  26400. if (browser.gecko && editor.body.contentEditable === 'true') {
  26401. var input = document.createElement('input');
  26402. document.body.appendChild(input);
  26403. editor.body.contentEditable = false;
  26404. setTimeout(function () {
  26405. input.focus();
  26406. setTimeout(function () {
  26407. editor.body.contentEditable = true;
  26408. editor.fireEvent('fullscreenchanged', fullscreen);
  26409. editor.selection.getRange().moveToBookmark(bk).select(true);
  26410. baidu.editor.dom.domUtils.remove(input);
  26411. fullscreen && window.scroll(0, 0);
  26412. }, 0)
  26413. }, 0)
  26414. }
  26415. if(editor.body.contentEditable === 'true'){
  26416. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26417. this.triggerLayout();
  26418. }
  26419. }
  26420. },
  26421. _updateFullScreen:function () {
  26422. if (this._fullscreen) {
  26423. var vpRect = uiUtils.getViewportRect();
  26424. 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);
  26425. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26426. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26427. //不手动调一下,会导致全屏失效
  26428. if(browser.gecko){
  26429. try{
  26430. window.onresize();
  26431. }catch(e){
  26432. }
  26433. }
  26434. }
  26435. },
  26436. _updateElementPath:function () {
  26437. var bottom = this.getDom('elementpath'), list;
  26438. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26439. var buff = [];
  26440. for (var i = 0, ci; ci = list[i]; i++) {
  26441. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26442. }
  26443. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26444. } else {
  26445. bottom.style.display = 'none'
  26446. }
  26447. },
  26448. disableElementPath:function () {
  26449. var bottom = this.getDom('elementpath');
  26450. bottom.innerHTML = '';
  26451. bottom.style.display = 'none';
  26452. this.elementPathEnabled = false;
  26453. },
  26454. enableElementPath:function () {
  26455. var bottom = this.getDom('elementpath');
  26456. bottom.style.display = '';
  26457. this.elementPathEnabled = true;
  26458. this._updateElementPath();
  26459. },
  26460. _scale:function () {
  26461. var doc = document,
  26462. editor = this.editor,
  26463. editorHolder = editor.container,
  26464. editorDocument = editor.document,
  26465. toolbarBox = this.getDom("toolbarbox"),
  26466. bottombar = this.getDom("bottombar"),
  26467. scale = this.getDom("scale"),
  26468. scalelayer = this.getDom("scalelayer");
  26469. var isMouseMove = false,
  26470. position = null,
  26471. minEditorHeight = 0,
  26472. minEditorWidth = editor.options.minFrameWidth,
  26473. pageX = 0,
  26474. pageY = 0,
  26475. scaleWidth = 0,
  26476. scaleHeight = 0;
  26477. function down() {
  26478. position = domUtils.getXY(editorHolder);
  26479. if (!minEditorHeight) {
  26480. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26481. }
  26482. 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:"
  26483. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26484. domUtils.on(doc, "mousemove", move);
  26485. domUtils.on(editorDocument, "mouseup", up);
  26486. domUtils.on(doc, "mouseup", up);
  26487. }
  26488. var me = this;
  26489. //by xuheng 全屏时关掉缩放
  26490. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26491. if (fullScreen) {
  26492. me.disableScale();
  26493. } else {
  26494. if (me.editor.options.scaleEnabled) {
  26495. me.enableScale();
  26496. var tmpNode = me.editor.document.createElement('span');
  26497. me.editor.body.appendChild(tmpNode);
  26498. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26499. domUtils.remove(tmpNode)
  26500. }
  26501. }
  26502. });
  26503. function move(event) {
  26504. clearSelection();
  26505. var e = event || window.event;
  26506. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26507. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26508. scaleWidth = pageX - position.x;
  26509. scaleHeight = pageY - position.y;
  26510. if (scaleWidth >= minEditorWidth) {
  26511. isMouseMove = true;
  26512. scalelayer.style.width = scaleWidth + 'px';
  26513. }
  26514. if (scaleHeight >= minEditorHeight) {
  26515. isMouseMove = true;
  26516. scalelayer.style.height = scaleHeight + "px";
  26517. }
  26518. }
  26519. function up() {
  26520. if (isMouseMove) {
  26521. isMouseMove = false;
  26522. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26523. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26524. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26525. }
  26526. if (scalelayer) {
  26527. scalelayer.style.display = "none";
  26528. }
  26529. clearSelection();
  26530. domUtils.un(doc, "mousemove", move);
  26531. domUtils.un(editorDocument, "mouseup", up);
  26532. domUtils.un(doc, "mouseup", up);
  26533. }
  26534. function clearSelection() {
  26535. if (browser.ie)
  26536. doc.selection.clear();
  26537. else
  26538. window.getSelection().removeAllRanges();
  26539. }
  26540. this.enableScale = function () {
  26541. //trace:2868
  26542. if (editor.queryCommandState("source") == 1) return;
  26543. scale.style.display = "";
  26544. this.scaleEnabled = true;
  26545. domUtils.on(scale, "mousedown", down);
  26546. };
  26547. this.disableScale = function () {
  26548. scale.style.display = "none";
  26549. this.scaleEnabled = false;
  26550. domUtils.un(scale, "mousedown", down);
  26551. };
  26552. },
  26553. isFullScreen:function () {
  26554. return this._fullscreen;
  26555. },
  26556. postRender:function () {
  26557. UIBase.prototype.postRender.call(this);
  26558. for (var i = 0; i < this.toolbars.length; i++) {
  26559. this.toolbars[i].postRender();
  26560. }
  26561. var me = this;
  26562. var timerId,
  26563. domUtils = baidu.editor.dom.domUtils,
  26564. updateFullScreenTime = function () {
  26565. clearTimeout(timerId);
  26566. timerId = setTimeout(function () {
  26567. me._updateFullScreen();
  26568. });
  26569. };
  26570. domUtils.on(window, 'resize', updateFullScreenTime);
  26571. me.addListener('destroy', function () {
  26572. domUtils.un(window, 'resize', updateFullScreenTime);
  26573. clearTimeout(timerId);
  26574. })
  26575. },
  26576. showToolbarMsg:function (msg, flag) {
  26577. this.getDom('toolbarmsg_label').innerHTML = msg;
  26578. this.getDom('toolbarmsg').style.display = '';
  26579. //
  26580. if (!flag) {
  26581. var w = this.getDom('upload_dialog');
  26582. w.style.display = 'none';
  26583. }
  26584. },
  26585. hideToolbarMsg:function () {
  26586. this.getDom('toolbarmsg').style.display = 'none';
  26587. },
  26588. mapUrl:function (url) {
  26589. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26590. },
  26591. triggerLayout:function () {
  26592. var dom = this.getDom();
  26593. if (dom.style.zoom == '1') {
  26594. dom.style.zoom = '100%';
  26595. } else {
  26596. dom.style.zoom = '1';
  26597. }
  26598. }
  26599. };
  26600. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26601. var instances = {};
  26602. UE.ui.Editor = function (options) {
  26603. var editor = new UE.Editor(options);
  26604. editor.options.editor = editor;
  26605. utils.loadFile(document, {
  26606. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26607. tag:"link",
  26608. type:"text/css",
  26609. rel:"stylesheet"
  26610. });
  26611. var oldRender = editor.render;
  26612. editor.render = function (holder) {
  26613. if (holder.constructor === String) {
  26614. editor.key = holder;
  26615. instances[holder] = editor;
  26616. }
  26617. utils.domReady(function () {
  26618. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26619. function renderUI() {
  26620. editor.setOpt({
  26621. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26622. });
  26623. new EditorUI(editor.options);
  26624. if (holder) {
  26625. if (holder.constructor === String) {
  26626. holder = document.getElementById(holder);
  26627. }
  26628. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26629. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26630. var newDiv = document.createElement('div');
  26631. holder.parentNode.insertBefore(newDiv, holder);
  26632. var cont = holder.value || holder.innerHTML;
  26633. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26634. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26635. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26636. .replace(/>[\n\r\t]+</g, '><');
  26637. holder.className && (newDiv.className = holder.className);
  26638. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26639. if (/textarea/i.test(holder.tagName)) {
  26640. editor.textarea = holder;
  26641. editor.textarea.style.display = 'none';
  26642. } else {
  26643. holder.parentNode.removeChild(holder);
  26644. holder.id && (newDiv.id = holder.id);
  26645. }
  26646. holder = newDiv;
  26647. holder.innerHTML = '';
  26648. }
  26649. }
  26650. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26651. editor.ui.render(holder);
  26652. var opt = editor.options;
  26653. //给实例添加一个编辑器的容器引用
  26654. editor.container = editor.ui.getDom();
  26655. var parents = domUtils.findParents(holder,true);
  26656. var displays = [];
  26657. for(var i = 0 ,ci;ci=parents[i];i++){
  26658. displays[i] = ci.style.display;
  26659. ci.style.display = 'block'
  26660. }
  26661. if (opt.initialFrameWidth) {
  26662. opt.minFrameWidth = opt.initialFrameWidth;
  26663. } else {
  26664. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  26665. var styleWidth = holder.style.width;
  26666. if(/%$/.test(styleWidth)) {
  26667. opt.initialFrameWidth = styleWidth;
  26668. }
  26669. }
  26670. if (opt.initialFrameHeight) {
  26671. opt.minFrameHeight = opt.initialFrameHeight;
  26672. } else {
  26673. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  26674. }
  26675. for(var i = 0 ,ci;ci=parents[i];i++){
  26676. ci.style.display = displays[i]
  26677. }
  26678. //编辑器最外容器设置了高度,会导致,编辑器不占位
  26679. //todo 先去掉,没有找到原因
  26680. if(holder.style.height){
  26681. holder.style.height = ''
  26682. }
  26683. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  26684. editor.container.style.zIndex = opt.zIndex;
  26685. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  26686. editor.fireEvent("afteruiready");
  26687. }
  26688. })
  26689. };
  26690. return editor;
  26691. };
  26692. /**
  26693. * @file
  26694. * @name UE
  26695. * @short UE
  26696. * @desc UEditor的顶部命名空间
  26697. */
  26698. /**
  26699. * @name getEditor
  26700. * @since 1.2.4+
  26701. * @grammar UE.getEditor(id,[opt]) => Editor实例
  26702. * @desc 提供一个全局的方法得到编辑器实例
  26703. *
  26704. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  26705. * * ''opt'' 编辑器的可选参数
  26706. * @example
  26707. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  26708. * this.setContent('hello')
  26709. * }});
  26710. * UE.getEditor('containerId'); //返回刚创建的实例
  26711. *
  26712. */
  26713. UE.getEditor = function (id, opt) {
  26714. var editor = instances[id];
  26715. if (!editor) {
  26716. editor = instances[id] = new UE.ui.Editor(opt);
  26717. editor.render(id);
  26718. }
  26719. return editor;
  26720. };
  26721. UE.delEditor = function (id) {
  26722. var editor;
  26723. if (editor = instances[id]) {
  26724. editor.key && editor.destroy();
  26725. delete instances[id]
  26726. }
  26727. };
  26728. UE.registerUI = function(uiName,fn,index,editorId){
  26729. utils.each(uiName.split(/\s+/), function (name) {
  26730. UE._customizeUI[name] = {
  26731. id : editorId,
  26732. execFn:fn,
  26733. index:index
  26734. };
  26735. })
  26736. }
  26737. })();
  26738. })();