ueditor.all.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Wed Dec 26 2018 17:24:52 GMT+0800 (CST)
  5. */
  6. (function(){
  7. // editor.js
  8. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  9. var baidu = window.baidu || {};
  10. window.baidu = baidu;
  11. window.UE = baidu.editor = window.UE || {};
  12. UE.plugins = {};
  13. UE.commands = {};
  14. UE.instants = {};
  15. UE.I18N = {};
  16. UE._customizeUI = {};
  17. UE.version = "1.4.3";
  18. var dom = UE.dom = {};
  19. // core/browser.js
  20. /**
  21. * 浏览器判断模块
  22. * @file
  23. * @module UE.browser
  24. * @since 1.2.6.1
  25. */
  26. /**
  27. * 提供浏览器检测的模块
  28. * @unfile
  29. * @module UE.browser
  30. */
  31. var browser = UE.browser = function(){
  32. var agent = navigator.userAgent.toLowerCase(),
  33. opera = window.opera,
  34. browser = {
  35. /**
  36. * @property {boolean} ie 检测当前浏览器是否为IE
  37. * @example
  38. * ```javascript
  39. * if ( UE.browser.ie ) {
  40. * console.log( '当前浏览器是IE' );
  41. * }
  42. * ```
  43. */
  44. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  45. /**
  46. * @property {boolean} opera 检测当前浏览器是否为Opera
  47. * @example
  48. * ```javascript
  49. * if ( UE.browser.opera ) {
  50. * console.log( '当前浏览器是Opera' );
  51. * }
  52. * ```
  53. */
  54. opera : ( !!opera && opera.version ),
  55. /**
  56. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  57. * @example
  58. * ```javascript
  59. * if ( UE.browser.webkit ) {
  60. * console.log( '当前浏览器是webkit内核浏览器' );
  61. * }
  62. * ```
  63. */
  64. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  65. /**
  66. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  67. * @example
  68. * ```javascript
  69. * if ( UE.browser.mac ) {
  70. * console.log( '当前浏览器运行在mac平台下' );
  71. * }
  72. * ```
  73. */
  74. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  75. /**
  76. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  77. * @example
  78. * ```javascript
  79. * if ( UE.browser.quirks ) {
  80. * console.log( '当前浏览器运行处于“怪异模式”' );
  81. * }
  82. * ```
  83. */
  84. quirks : ( document.compatMode == 'BackCompat' )
  85. };
  86. /**
  87. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  88. * @example
  89. * ```javascript
  90. * if ( UE.browser.gecko ) {
  91. * console.log( '当前浏览器内核是gecko内核' );
  92. * }
  93. * ```
  94. */
  95. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  96. var version = 0;
  97. // Internet Explorer 6.0+
  98. if ( browser.ie ){
  99. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  100. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  101. if(v1 && v2 && v1[1] && v2[1]){
  102. version = Math.max(v1[1]*1,v2[1]*1);
  103. }else if(v1 && v1[1]){
  104. version = v1[1]*1;
  105. }else if(v2 && v2[1]){
  106. version = v2[1]*1;
  107. }else{
  108. version = 0;
  109. }
  110. browser.ie11Compat = document.documentMode == 11;
  111. /**
  112. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  113. * @warning 如果浏览器不是IE, 则该值为undefined
  114. * @example
  115. * ```javascript
  116. * if ( UE.browser.ie9Compat ) {
  117. * console.log( '当前浏览器运行在IE9兼容模式下' );
  118. * }
  119. * ```
  120. */
  121. browser.ie9Compat = document.documentMode == 9;
  122. /**
  123. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  124. * @warning 如果浏览器不是IE, 则该值为undefined
  125. * @example
  126. * ```javascript
  127. * if ( UE.browser.ie8 ) {
  128. * console.log( '当前浏览器是IE8浏览器' );
  129. * }
  130. * ```
  131. */
  132. browser.ie8 = !!document.documentMode;
  133. /**
  134. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  135. * @warning 如果浏览器不是IE, 则该值为undefined
  136. * @example
  137. * ```javascript
  138. * if ( UE.browser.ie8Compat ) {
  139. * console.log( '当前浏览器运行在IE8兼容模式下' );
  140. * }
  141. * ```
  142. */
  143. browser.ie8Compat = document.documentMode == 8;
  144. /**
  145. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  146. * @warning 如果浏览器不是IE, 则该值为undefined
  147. * @example
  148. * ```javascript
  149. * if ( UE.browser.ie7Compat ) {
  150. * console.log( '当前浏览器运行在IE7兼容模式下' );
  151. * }
  152. * ```
  153. */
  154. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  155. || document.documentMode == 7 );
  156. /**
  157. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  158. * @warning 如果浏览器不是IE, 则该值为undefined
  159. * @example
  160. * ```javascript
  161. * if ( UE.browser.ie6Compat ) {
  162. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  163. * }
  164. * ```
  165. */
  166. browser.ie6Compat = ( version < 7 || browser.quirks );
  167. browser.ie9above = version > 8;
  168. browser.ie9below = version < 9;
  169. browser.ie11above = version > 10;
  170. browser.ie11below = version < 11;
  171. }
  172. // Gecko.
  173. if ( browser.gecko ){
  174. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  175. if ( geckoRelease )
  176. {
  177. geckoRelease = geckoRelease[1].split( '.' );
  178. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  179. }
  180. }
  181. /**
  182. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  183. * @warning 如果浏览器不是chrome, 则该值为undefined
  184. * @example
  185. * ```javascript
  186. * if ( UE.browser.chrome ) {
  187. * console.log( '当前浏览器是Chrome' );
  188. * }
  189. * ```
  190. */
  191. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  192. browser.chrome = + RegExp['\x241'];
  193. }
  194. /**
  195. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  196. * @warning 如果浏览器不是safari, 则该值为undefined
  197. * @example
  198. * ```javascript
  199. * if ( UE.browser.safari ) {
  200. * console.log( '当前浏览器是Safari' );
  201. * }
  202. * ```
  203. */
  204. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  205. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  206. }
  207. // Opera 9.50+
  208. if ( browser.opera )
  209. version = parseFloat( opera.version() );
  210. // WebKit 522+ (Safari 3+)
  211. if ( browser.webkit )
  212. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  213. /**
  214. * @property { Number } version 检测当前浏览器版本号
  215. * @remind
  216. * <ul>
  217. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  218. * <li>gecko系列会返回10900,158900等</li>
  219. * <li>webkit系列会返回其build号 (如 522等)</li>
  220. * </ul>
  221. * @example
  222. * ```javascript
  223. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  224. * ```
  225. */
  226. browser.version = version;
  227. /**
  228. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  229. * @example
  230. * ```javascript
  231. * if ( UE.browser.isCompatible ) {
  232. * console.log( '浏览器与UEditor能够良好兼容' );
  233. * }
  234. * ```
  235. */
  236. browser.isCompatible =
  237. !browser.mobile && (
  238. ( browser.ie && version >= 6 ) ||
  239. ( browser.gecko && version >= 10801 ) ||
  240. ( browser.opera && version >= 9.5 ) ||
  241. ( browser.air && version >= 1 ) ||
  242. ( browser.webkit && version >= 522 ) ||
  243. false );
  244. return browser;
  245. }();
  246. //快捷方式
  247. var ie = browser.ie,
  248. webkit = browser.webkit,
  249. gecko = browser.gecko,
  250. opera = browser.opera;
  251. // core/utils.js
  252. /**
  253. * 工具函数包
  254. * @file
  255. * @module UE.utils
  256. * @since 1.2.6.1
  257. */
  258. /**
  259. * UEditor封装使用的静态工具函数
  260. * @module UE.utils
  261. * @unfile
  262. */
  263. var utils = UE.utils = {
  264. /**
  265. * 用给定的迭代器遍历对象
  266. * @method each
  267. * @param { Object } obj 需要遍历的对象
  268. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  269. * @example
  270. * ```javascript
  271. * var demoObj = {
  272. * key1: 1,
  273. * key2: 2
  274. * };
  275. *
  276. * //output: key1: 1, key2: 2
  277. * UE.utils.each( demoObj, funciton ( value, key ) {
  278. *
  279. * console.log( key + ":" + value );
  280. *
  281. * } );
  282. * ```
  283. */
  284. /**
  285. * 用给定的迭代器遍历数组或类数组对象
  286. * @method each
  287. * @param { Array } array 需要遍历的数组或者类数组
  288. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  289. * @example
  290. * ```javascript
  291. * var divs = document.getElmentByTagNames( "div" );
  292. *
  293. * //output: 0: DIV, 1: DIV ...
  294. * UE.utils.each( divs, funciton ( value, key ) {
  295. *
  296. * console.log( key + ":" + value.tagName );
  297. *
  298. * } );
  299. * ```
  300. */
  301. each : function(obj, iterator, context) {
  302. if (obj == null) return;
  303. if (obj.length === +obj.length) {
  304. for (var i = 0, l = obj.length; i < l; i++) {
  305. if(iterator.call(context, obj[i], i, obj) === false)
  306. return false;
  307. }
  308. } else {
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. if(iterator.call(context, obj[key], key, obj) === false)
  312. return false;
  313. }
  314. }
  315. }
  316. },
  317. /**
  318. * 以给定对象作为原型创建一个新对象
  319. * @method makeInstance
  320. * @param { Object } protoObject 该对象将作为新创建对象的原型
  321. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  322. * @example
  323. * ```javascript
  324. *
  325. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  326. *
  327. * var newObject = UE.utils.makeInstance( protoObject );
  328. * //output: Hello UEditor!
  329. * newObject.sayHello();
  330. * ```
  331. */
  332. makeInstance:function (obj) {
  333. var noop = new Function();
  334. noop.prototype = obj;
  335. obj = new noop;
  336. noop.prototype = null;
  337. return obj;
  338. },
  339. /**
  340. * 将source对象中的属性扩展到target对象上
  341. * @method extend
  342. * @remind 该方法将强制把source对象上的属性复制到target对象上
  343. * @see UE.utils.extend(Object,Object,Boolean)
  344. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  345. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  346. * @return { Object } 返回target对象
  347. * @example
  348. * ```javascript
  349. *
  350. * var target = { name: 'target', sex: 1 },
  351. * source = { name: 'source', age: 17 };
  352. *
  353. * UE.utils.extend( target, source );
  354. *
  355. * //output: { name: 'source', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. /**
  361. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  362. * 源对象属性名相同的属性值。
  363. * @method extend
  364. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  365. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  366. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  367. * @return { Object } 返回target对象
  368. * @example
  369. * ```javascript
  370. *
  371. * var target = { name: 'target', sex: 1 },
  372. * source = { name: 'source', age: 17 };
  373. *
  374. * UE.utils.extend( target, source, true );
  375. *
  376. * //output: { name: 'target', sex: 1, age: 17 }
  377. * console.log( target );
  378. *
  379. * ```
  380. */
  381. extend:function (t, s, b) {
  382. if (s) {
  383. for (var k in s) {
  384. if (!b || !t.hasOwnProperty(k)) {
  385. t[k] = s[k];
  386. }
  387. }
  388. }
  389. return t;
  390. },
  391. /**
  392. * 将给定的多个对象的属性复制到目标对象target上
  393. * @method extend2
  394. * @remind 该方法将强制把源对象上的属性复制到target对象上
  395. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  396. * 将会覆盖掉之前的值。
  397. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  398. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  399. * @return { Object } 返回target对象
  400. * @example
  401. * ```javascript
  402. *
  403. * var target = {},
  404. * source1 = { name: 'source', age: 17 },
  405. * source2 = { title: 'dev' };
  406. *
  407. * UE.utils.extend2( target, source1, source2 );
  408. *
  409. * //output: { name: 'source', age: 17, title: 'dev' }
  410. * console.log( target );
  411. *
  412. * ```
  413. */
  414. extend2:function (t) {
  415. var a = arguments;
  416. for (var i = 1; i < a.length; i++) {
  417. var x = a[i];
  418. for (var k in x) {
  419. if (!t.hasOwnProperty(k)) {
  420. t[k] = x[k];
  421. }
  422. }
  423. }
  424. return t;
  425. },
  426. /**
  427. * 模拟继承机制, 使得subClass继承自superClass
  428. * @method inherits
  429. * @param { Object } subClass 子类对象
  430. * @param { Object } superClass 超类对象
  431. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  432. * @return { Object } 继承superClass后的子类对象
  433. * @example
  434. * ```javascript
  435. * function SuperClass(){
  436. * this.name = "小李";
  437. * }
  438. *
  439. * SuperClass.prototype = {
  440. * hello:function(str){
  441. * console.log(this.name + str);
  442. * }
  443. * }
  444. *
  445. * function SubClass(){
  446. * this.name = "小张";
  447. * }
  448. *
  449. * UE.utils.inherits(SubClass,SuperClass);
  450. *
  451. * var sub = new SubClass();
  452. * //output: '小张早上好!
  453. * sub.hello("早上好!");
  454. * ```
  455. */
  456. inherits:function (subClass, superClass) {
  457. var oldP = subClass.prototype,
  458. newP = utils.makeInstance(superClass.prototype);
  459. utils.extend(newP, oldP, true);
  460. subClass.prototype = newP;
  461. return (newP.constructor = subClass);
  462. },
  463. /**
  464. * 用指定的context对象作为函数fn的上下文
  465. * @method bind
  466. * @param { Function } fn 需要绑定上下文的函数对象
  467. * @param { Object } content 函数fn新的上下文对象
  468. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  469. * @example
  470. * ```javascript
  471. *
  472. * var name = 'window',
  473. * newTest = null;
  474. *
  475. * function test () {
  476. * console.log( this.name );
  477. * }
  478. *
  479. * newTest = UE.utils.bind( test, { name: 'object' } );
  480. *
  481. * //output: object
  482. * newTest();
  483. *
  484. * //output: window
  485. * test();
  486. *
  487. * ```
  488. */
  489. bind:function (fn, context) {
  490. return function () {
  491. return fn.apply(context, arguments);
  492. };
  493. },
  494. /**
  495. * 创建延迟指定时间后执行的函数fn
  496. * @method defer
  497. * @param { Function } fn 需要延迟执行的函数对象
  498. * @param { int } delay 延迟的时间, 单位是毫秒
  499. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  500. * 而不能保证刚好到达延迟时间时执行。
  501. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  502. * @example
  503. * ```javascript
  504. * var start = 0;
  505. *
  506. * function test(){
  507. * console.log( new Date() - start );
  508. * }
  509. *
  510. * var testDefer = UE.utils.defer( test, 1000 );
  511. * //
  512. * start = new Date();
  513. * //output: (大约在1000毫秒之后输出) 1000
  514. * testDefer();
  515. * ```
  516. */
  517. /**
  518. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  519. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  520. * @method defer
  521. * @param { Function } fn 需要延迟执行的函数对象
  522. * @param { int } delay 延迟的时间, 单位是毫秒
  523. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  524. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  525. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  526. * 而不能保证刚好到达延迟时间时执行。
  527. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  528. * @example
  529. * ```javascript
  530. *
  531. * function test(){
  532. * console.log(1);
  533. * }
  534. *
  535. * var testDefer = UE.utils.defer( test, 1000, true );
  536. *
  537. * //output: (两次调用仅有一次输出) 1
  538. * testDefer();
  539. * testDefer();
  540. * ```
  541. */
  542. defer:function (fn, delay, exclusion) {
  543. var timerID;
  544. return function () {
  545. if (exclusion) {
  546. clearTimeout(timerID);
  547. }
  548. timerID = setTimeout(fn, delay);
  549. };
  550. },
  551. /**
  552. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  558. * @example
  559. * ```javascript
  560. * var item = 1,
  561. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  562. *
  563. * //output: 4
  564. * console.log( UE.utils.indexOf( arr, item ) );
  565. * ```
  566. */
  567. /**
  568. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  569. * @method indexOf
  570. * @remind 该方法的匹配过程使用的是恒等“===”
  571. * @param { Array } array 需要查找的数组对象
  572. * @param { * } item 需要在目标数组中查找的值
  573. * @param { int } start 搜索的起始位置
  574. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  575. * @example
  576. * ```javascript
  577. * var item = 1,
  578. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  579. *
  580. * //output: 9
  581. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  582. * ```
  583. */
  584. indexOf:function (array, item, start) {
  585. var index = -1;
  586. start = this.isNumber(start) ? start : 0;
  587. this.each(array, function (v, i) {
  588. if (i >= start && v === item) {
  589. index = i;
  590. return false;
  591. }
  592. });
  593. return index;
  594. },
  595. /**
  596. * 移除数组array中所有的元素item
  597. * @method removeItem
  598. * @param { Array } array 要移除元素的目标数组
  599. * @param { * } item 将要被移除的元素
  600. * @remind 该方法的匹配过程使用的是恒等“===”
  601. * @example
  602. * ```javascript
  603. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  604. *
  605. * UE.utils.removeItem( arr, 4 );
  606. * //output: [ 5, 7, 1, 3, 6 ]
  607. * console.log( arr );
  608. *
  609. * ```
  610. */
  611. removeItem:function (array, item) {
  612. for (var i = 0, l = array.length; i < l; i++) {
  613. if (array[i] === item) {
  614. array.splice(i, 1);
  615. i--;
  616. }
  617. }
  618. },
  619. /**
  620. * 删除字符串str的首尾空格
  621. * @method trim
  622. * @param { String } str 需要删除首尾空格的字符串
  623. * @return { String } 删除了首尾的空格后的字符串
  624. * @example
  625. * ```javascript
  626. *
  627. * var str = " UEdtior ";
  628. *
  629. * //output: 9
  630. * console.log( str.length );
  631. *
  632. * //output: 7
  633. * console.log( UE.utils.trim( " UEdtior " ).length );
  634. *
  635. * //output: 9
  636. * console.log( str.length );
  637. *
  638. * ```
  639. */
  640. trim:function (str) {
  641. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  642. },
  643. /**
  644. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  645. * @method listToMap
  646. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  647. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  648. * @return { Object } 转化之后的hash对象
  649. * @example
  650. * ```javascript
  651. *
  652. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  653. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  654. *
  655. * ```
  656. */
  657. /**
  658. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  659. * @method listToMap
  660. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  661. * @param { Array } arr 字符串数组
  662. * @return { Object } 转化之后的hash对象
  663. * @example
  664. * ```javascript
  665. *
  666. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  667. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  668. *
  669. * ```
  670. */
  671. listToMap:function (list) {
  672. if (!list)return {};
  673. list = utils.isArray(list) ? list : list.split(',');
  674. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  675. obj[ci.toUpperCase()] = obj[ci] = 1;
  676. }
  677. return obj;
  678. },
  679. /**
  680. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  681. * @method unhtml
  682. * @param { String } str 需要转义的字符串
  683. * @return { String } 转义后的字符串
  684. * @example
  685. * ```javascript
  686. * var html = '<body>&</body>';
  687. *
  688. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  689. * console.log( UE.utils.unhtml( html ) );
  690. *
  691. * ```
  692. */
  693. unhtml:function (str, reg) {
  694. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  695. if (b) {
  696. return a;
  697. } else {
  698. return {
  699. '<':'&lt;',
  700. '&':'&amp;',
  701. '"':'&quot;',
  702. '>':'&gt;',
  703. "'":'&#39;'
  704. }[a]
  705. }
  706. }) : '';
  707. },
  708. /**
  709. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  710. * @param { String } str 需要转义的字符串
  711. * @param { RegExp } reg 自定义的正则
  712. * @return { String } 转义后的字符串
  713. */
  714. unhtmlForUrl:function (str, reg) {
  715. return str ? str.replace(reg || /[<">']/g, function (a) {
  716. return {
  717. '<':'&lt;',
  718. '&':'&amp;',
  719. '"':'&quot;',
  720. '>':'&gt;',
  721. "'":'&#39;'
  722. }[a]
  723. }) : '';
  724. },
  725. /**
  726. * 将str中的转义字符还原成html字符
  727. * @see UE.utils.unhtml(String);
  728. * @method html
  729. * @param { String } str 需要逆转义的字符串
  730. * @return { String } 逆转义后的字符串
  731. * @example
  732. * ```javascript
  733. *
  734. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  735. *
  736. * //output: <body>&</body>
  737. * console.log( UE.utils.html( str ) );
  738. *
  739. * ```
  740. */
  741. html:function (str) {
  742. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  743. return {
  744. '&lt;':'<',
  745. '&amp;':'&',
  746. '&quot;':'"',
  747. '&gt;':'>',
  748. '&#39;':"'",
  749. '&nbsp;':' '
  750. }[m]
  751. }) : '';
  752. },
  753. /**
  754. * 将css样式转换为驼峰的形式
  755. * @method cssStyleToDomStyle
  756. * @param { String } cssName 需要转换的css样式名
  757. * @return { String } 转换成驼峰形式后的css样式名
  758. * @example
  759. * ```javascript
  760. *
  761. * var str = 'border-top';
  762. *
  763. * //output: borderTop
  764. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  765. *
  766. * ```
  767. */
  768. cssStyleToDomStyle:function () {
  769. var test = document.createElement('div').style,
  770. cache = {
  771. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  772. };
  773. return function (cssName) {
  774. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  775. return match.charAt(1).toUpperCase();
  776. }));
  777. };
  778. }(),
  779. /**
  780. * 动态加载文件到doc中
  781. * @method loadFile
  782. * @param { DomDocument } document 需要加载资源文件的文档对象
  783. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  784. * @example
  785. * ```javascript
  786. *
  787. * UE.utils.loadFile( document, {
  788. * src:"test.js",
  789. * tag:"script",
  790. * type:"text/javascript",
  791. * defer:"defer"
  792. * } );
  793. *
  794. * ```
  795. */
  796. /**
  797. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  798. * @method loadFile
  799. * @param { DomDocument } document 需要加载资源文件的文档对象
  800. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  801. * @param { Function } fn 资源文件加载成功之后执行的回调
  802. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  803. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  804. * @example
  805. * ```javascript
  806. *
  807. * UE.utils.loadFile( document, {
  808. * src:"test.js",
  809. * tag:"script",
  810. * type:"text/javascript",
  811. * defer:"defer"
  812. * }, function () {
  813. * console.log('加载成功');
  814. * } );
  815. *
  816. * ```
  817. */
  818. loadFile:function () {
  819. var tmpList = [];
  820. function getItem(doc, obj) {
  821. try {
  822. for (var i = 0, ci; ci = tmpList[i++];) {
  823. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  824. return ci;
  825. }
  826. }
  827. } catch (e) {
  828. return null;
  829. }
  830. }
  831. return function (doc, obj, fn) {
  832. var item = getItem(doc, obj);
  833. if (item) {
  834. if (item.ready) {
  835. fn && fn();
  836. } else {
  837. item.funs.push(fn)
  838. }
  839. return;
  840. }
  841. tmpList.push({
  842. doc:doc,
  843. url:obj.src || obj.href,
  844. funs:[fn]
  845. });
  846. if (!doc.body) {
  847. var html = [];
  848. for (var p in obj) {
  849. if (p == 'tag')continue;
  850. html.push(p + '="' + obj[p] + '"')
  851. }
  852. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  853. return;
  854. }
  855. if (obj.id && doc.getElementById(obj.id)) {
  856. return;
  857. }
  858. var element = doc.createElement(obj.tag);
  859. delete obj.tag;
  860. for (var p in obj) {
  861. element.setAttribute(p, obj[p]);
  862. }
  863. element.onload = element.onreadystatechange = function () {
  864. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  865. item = getItem(doc, obj);
  866. if (item.funs.length > 0) {
  867. item.ready = 1;
  868. for (var fi; fi = item.funs.pop();) {
  869. fi();
  870. }
  871. }
  872. element.onload = element.onreadystatechange = null;
  873. }
  874. };
  875. element.onerror = function () {
  876. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  877. };
  878. doc.getElementsByTagName("head")[0].appendChild(element);
  879. }
  880. }(),
  881. /**
  882. * 判断obj对象是否为空
  883. * @method isEmptyObject
  884. * @param { * } obj 需要判断的对象
  885. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  886. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  887. * @return { Boolean } 对象是否为空
  888. * @example
  889. * ```javascript
  890. *
  891. * //output: true
  892. * console.log( UE.utils.isEmptyObject( {} ) );
  893. *
  894. * //output: true
  895. * console.log( UE.utils.isEmptyObject( [] ) );
  896. *
  897. * //output: true
  898. * console.log( UE.utils.isEmptyObject( "" ) );
  899. *
  900. * //output: false
  901. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  902. *
  903. * //output: false
  904. * console.log( UE.utils.isEmptyObject( [1] ) );
  905. *
  906. * //output: false
  907. * console.log( UE.utils.isEmptyObject( "1" ) );
  908. *
  909. * ```
  910. */
  911. isEmptyObject:function (obj) {
  912. if (obj == null) return true;
  913. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  914. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  915. return true;
  916. },
  917. /**
  918. * 把rgb格式的颜色值转换成16进制格式
  919. * @method fixColor
  920. * @param { String } rgb格式的颜色值
  921. * @param { String }
  922. * @example
  923. * rgb(255,255,255) => "#ffffff"
  924. */
  925. fixColor:function (name, value) {
  926. if (/color/i.test(name) && /rgba?/.test(value)) {
  927. var array = value.split(",");
  928. if (array.length > 3)
  929. return "";
  930. value = "#";
  931. for (var i = 0, color; color = array[i++];) {
  932. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  933. value += color.length == 1 ? "0" + color : color;
  934. }
  935. value = value.toUpperCase();
  936. }
  937. return value;
  938. },
  939. /**
  940. * 只针对border,padding,margin做了处理,因为性能问题
  941. * @public
  942. * @function
  943. * @param {String} val style字符串
  944. */
  945. optCss:function (val) {
  946. var padding, margin, border;
  947. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  948. if (val.split(' ').length == 1) {
  949. switch (key) {
  950. case 'padding':
  951. !padding && (padding = {});
  952. padding[name] = val;
  953. return '';
  954. case 'margin':
  955. !margin && (margin = {});
  956. margin[name] = val;
  957. return '';
  958. case 'border':
  959. return val == 'initial' ? '' : str;
  960. }
  961. }
  962. return str;
  963. });
  964. function opt(obj, name) {
  965. if (!obj) {
  966. return '';
  967. }
  968. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  969. if (!t || !l || !b || !r) {
  970. for (var p in obj) {
  971. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  972. }
  973. } else {
  974. val += ';' + name + ':' +
  975. (t == b && b == l && l == r ? t :
  976. t == b && l == r ? (t + ' ' + l) :
  977. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  978. }
  979. return val;
  980. }
  981. val += opt(padding, 'padding') + opt(margin, 'margin');
  982. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  983. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  984. return b ? b + ";;" : ';'
  985. });
  986. },
  987. /**
  988. * 克隆对象
  989. * @method clone
  990. * @param { Object } source 源对象
  991. * @return { Object } source的一个副本
  992. */
  993. /**
  994. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  995. * @method clone
  996. * @param { Object } source 源对象
  997. * @param { Object } target 目标对象
  998. * @return { Object } 附加了source对象所有属性的target对象
  999. */
  1000. clone:function (source, target) {
  1001. var tmp;
  1002. target = target || {};
  1003. for (var i in source) {
  1004. if (source.hasOwnProperty(i)) {
  1005. tmp = source[i];
  1006. if (typeof tmp == 'object') {
  1007. target[i] = utils.isArray(tmp) ? [] : {};
  1008. utils.clone(source[i], target[i])
  1009. } else {
  1010. target[i] = tmp;
  1011. }
  1012. }
  1013. }
  1014. return target;
  1015. },
  1016. /**
  1017. * 把cm/pt为单位的值转换为px为单位的值
  1018. * @method transUnitToPx
  1019. * @param { String } 待转换的带单位的字符串
  1020. * @return { String } 转换为px为计量单位的值的字符串
  1021. * @example
  1022. * ```javascript
  1023. *
  1024. * //output: 500px
  1025. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1026. *
  1027. * //output: 27px
  1028. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1029. *
  1030. * ```
  1031. */
  1032. transUnitToPx:function (val) {
  1033. if (!/(pt|cm)/.test(val)) {
  1034. return val
  1035. }
  1036. var unit;
  1037. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1038. val = v;
  1039. unit = u;
  1040. });
  1041. switch (unit) {
  1042. case 'cm':
  1043. val = parseFloat(val) * 25;
  1044. break;
  1045. case 'pt':
  1046. val = Math.round(parseFloat(val) * 96 / 72);
  1047. }
  1048. return val + (val ? 'px' : '');
  1049. },
  1050. /**
  1051. * 在dom树ready之后执行给定的回调函数
  1052. * @method domReady
  1053. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1054. * @param { Function } fn dom树ready之后的回调函数
  1055. * @example
  1056. * ```javascript
  1057. *
  1058. * UE.utils.domReady( function () {
  1059. *
  1060. * console.log('123');
  1061. *
  1062. * } );
  1063. *
  1064. * ```
  1065. */
  1066. domReady:function () {
  1067. var fnArr = [];
  1068. function doReady(doc) {
  1069. //确保onready只执行一次
  1070. doc.isReady = true;
  1071. for (var ci; ci = fnArr.pop(); ci()) {
  1072. }
  1073. }
  1074. return function (onready, win) {
  1075. win = win || window;
  1076. var doc = win.document;
  1077. onready && fnArr.push(onready);
  1078. if (doc.readyState === "complete") {
  1079. doReady(doc);
  1080. } else {
  1081. doc.isReady && doReady(doc);
  1082. if (browser.ie && browser.version != 11) {
  1083. (function () {
  1084. if (doc.isReady) return;
  1085. try {
  1086. doc.documentElement.doScroll("left");
  1087. } catch (error) {
  1088. setTimeout(arguments.callee, 0);
  1089. return;
  1090. }
  1091. doReady(doc);
  1092. })();
  1093. win.attachEvent('onload', function () {
  1094. doReady(doc)
  1095. });
  1096. } else {
  1097. doc.addEventListener("DOMContentLoaded", function () {
  1098. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1099. doReady(doc);
  1100. }, false);
  1101. win.addEventListener('load', function () {
  1102. doReady(doc)
  1103. }, false);
  1104. }
  1105. }
  1106. }
  1107. }(),
  1108. /**
  1109. * 动态添加css样式
  1110. * @method cssRule
  1111. * @param { String } 节点名称
  1112. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1113. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1114. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1115. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1116. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1117. */
  1118. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1119. var indexList, index;
  1120. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1121. //获取样式
  1122. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1123. indexList = doc.indexList || (doc.indexList = {});
  1124. index = indexList[key];
  1125. if(index !== undefined){
  1126. return doc.styleSheets[index].cssText
  1127. }
  1128. return undefined;
  1129. }
  1130. doc = doc || document;
  1131. indexList = doc.indexList || (doc.indexList = {});
  1132. index = indexList[key];
  1133. //清除样式
  1134. if(style === ''){
  1135. if(index!== undefined){
  1136. doc.styleSheets[index].cssText = '';
  1137. delete indexList[key];
  1138. return true
  1139. }
  1140. return false;
  1141. }
  1142. //添加样式
  1143. if(index!== undefined){
  1144. sheetStyle = doc.styleSheets[index];
  1145. }else{
  1146. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1147. indexList[key] = index;
  1148. }
  1149. sheetStyle.cssText = style;
  1150. }: function (key, style, doc) {
  1151. var head, node;
  1152. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1153. //获取样式
  1154. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1155. node = doc.getElementById(key);
  1156. return node ? node.innerHTML : undefined;
  1157. }
  1158. doc = doc || document;
  1159. node = doc.getElementById(key);
  1160. //清除样式
  1161. if(style === ''){
  1162. if(node){
  1163. node.parentNode.removeChild(node);
  1164. return true
  1165. }
  1166. return false;
  1167. }
  1168. //添加样式
  1169. if(node){
  1170. node.innerHTML = style;
  1171. }else{
  1172. node = doc.createElement('style');
  1173. node.id = key;
  1174. node.innerHTML = style;
  1175. doc.getElementsByTagName('head')[0].appendChild(node);
  1176. }
  1177. },
  1178. sort:function(array,compareFn){
  1179. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1180. for(var i= 0,len = array.length; i<len; i++){
  1181. for(var j = i,length = array.length; j<length; j++){
  1182. if(compareFn(array[i], array[j]) > 0){
  1183. var t = array[i];
  1184. array[i] = array[j];
  1185. array[j] = t;
  1186. }
  1187. }
  1188. }
  1189. return array;
  1190. },
  1191. serializeParam:function (json) {
  1192. var strArr = [];
  1193. for (var i in json) {
  1194. //忽略默认的几个参数
  1195. if(i=="method" || i=="timeout" || i=="async") continue;
  1196. //传递过来的对象和函数不在提交之列
  1197. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1198. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1199. } else if (utils.isArray(json[i])) {
  1200. //支持传数组内容
  1201. for(var j = 0; j < json[i].length; j++) {
  1202. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1203. }
  1204. }
  1205. }
  1206. return strArr.join("&");
  1207. },
  1208. formatUrl:function (url) {
  1209. var u = url.replace(/&&/g, '&');
  1210. u = u.replace(/\?&/g, '?');
  1211. u = u.replace(/&$/g, '');
  1212. u = u.replace(/&#/g, '#');
  1213. u = u.replace(/&+/g, '&');
  1214. return u;
  1215. },
  1216. isCrossDomainUrl:function (url) {
  1217. var a = document.createElement('a');
  1218. a.href = url;
  1219. if (browser.ie) {
  1220. a.href = a.href;
  1221. }
  1222. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1223. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1224. },
  1225. clearEmptyAttrs : function(obj){
  1226. for(var p in obj){
  1227. if(obj[p] === ''){
  1228. delete obj[p]
  1229. }
  1230. }
  1231. return obj;
  1232. },
  1233. str2json : function(s){
  1234. if (!utils.isString(s)) return null;
  1235. if (window.JSON) {
  1236. return JSON.parse(s);
  1237. } else {
  1238. return (new Function("return " + utils.trim(s || '')))();
  1239. }
  1240. },
  1241. json2str : (function(){
  1242. if (window.JSON) {
  1243. return JSON.stringify;
  1244. } else {
  1245. var escapeMap = {
  1246. "\b": '\\b',
  1247. "\t": '\\t',
  1248. "\n": '\\n',
  1249. "\f": '\\f',
  1250. "\r": '\\r',
  1251. '"' : '\\"',
  1252. "\\": '\\\\'
  1253. };
  1254. function encodeString(source) {
  1255. if (/["\\\x00-\x1f]/.test(source)) {
  1256. source = source.replace(
  1257. /["\\\x00-\x1f]/g,
  1258. function (match) {
  1259. var c = escapeMap[match];
  1260. if (c) {
  1261. return c;
  1262. }
  1263. c = match.charCodeAt();
  1264. return "\\u00"
  1265. + Math.floor(c / 16).toString(16)
  1266. + (c % 16).toString(16);
  1267. });
  1268. }
  1269. return '"' + source + '"';
  1270. }
  1271. function encodeArray(source) {
  1272. var result = ["["],
  1273. l = source.length,
  1274. preComma, i, item;
  1275. for (i = 0; i < l; i++) {
  1276. item = source[i];
  1277. switch (typeof item) {
  1278. case "undefined":
  1279. case "function":
  1280. case "unknown":
  1281. break;
  1282. default:
  1283. if(preComma) {
  1284. result.push(',');
  1285. }
  1286. result.push(utils.json2str(item));
  1287. preComma = 1;
  1288. }
  1289. }
  1290. result.push("]");
  1291. return result.join("");
  1292. }
  1293. function pad(source) {
  1294. return source < 10 ? '0' + source : source;
  1295. }
  1296. function encodeDate(source){
  1297. return '"' + source.getFullYear() + "-"
  1298. + pad(source.getMonth() + 1) + "-"
  1299. + pad(source.getDate()) + "T"
  1300. + pad(source.getHours()) + ":"
  1301. + pad(source.getMinutes()) + ":"
  1302. + pad(source.getSeconds()) + '"';
  1303. }
  1304. return function (value) {
  1305. switch (typeof value) {
  1306. case 'undefined':
  1307. return 'undefined';
  1308. case 'number':
  1309. return isFinite(value) ? String(value) : "null";
  1310. case 'string':
  1311. return encodeString(value);
  1312. case 'boolean':
  1313. return String(value);
  1314. default:
  1315. if (value === null) {
  1316. return 'null';
  1317. } else if (utils.isArray(value)) {
  1318. return encodeArray(value);
  1319. } else if (utils.isDate(value)) {
  1320. return encodeDate(value);
  1321. } else {
  1322. var result = ['{'],
  1323. encode = utils.json2str,
  1324. preComma,
  1325. item;
  1326. for (var key in value) {
  1327. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1328. item = value[key];
  1329. switch (typeof item) {
  1330. case 'undefined':
  1331. case 'unknown':
  1332. case 'function':
  1333. break;
  1334. default:
  1335. if (preComma) {
  1336. result.push(',');
  1337. }
  1338. preComma = 1;
  1339. result.push(encode(key) + ':' + encode(item));
  1340. }
  1341. }
  1342. }
  1343. result.push('}');
  1344. return result.join('');
  1345. }
  1346. }
  1347. };
  1348. }
  1349. })()
  1350. };
  1351. /**
  1352. * 判断给定的对象是否是字符串
  1353. * @method isString
  1354. * @param { * } object 需要判断的对象
  1355. * @return { Boolean } 给定的对象是否是字符串
  1356. */
  1357. /**
  1358. * 判断给定的对象是否是数组
  1359. * @method isArray
  1360. * @param { * } object 需要判断的对象
  1361. * @return { Boolean } 给定的对象是否是数组
  1362. */
  1363. /**
  1364. * 判断给定的对象是否是一个Function
  1365. * @method isFunction
  1366. * @param { * } object 需要判断的对象
  1367. * @return { Boolean } 给定的对象是否是Function
  1368. */
  1369. /**
  1370. * 判断给定的对象是否是Number
  1371. * @method isNumber
  1372. * @param { * } object 需要判断的对象
  1373. * @return { Boolean } 给定的对象是否是Number
  1374. */
  1375. /**
  1376. * 判断给定的对象是否是一个正则表达式
  1377. * @method isRegExp
  1378. * @param { * } object 需要判断的对象
  1379. * @return { Boolean } 给定的对象是否是正则表达式
  1380. */
  1381. /**
  1382. * 判断给定的对象是否是一个普通对象
  1383. * @method isObject
  1384. * @param { * } object 需要判断的对象
  1385. * @return { Boolean } 给定的对象是否是普通对象
  1386. */
  1387. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1388. UE.utils['is' + v] = function (obj) {
  1389. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1390. }
  1391. });
  1392. // core/EventBase.js
  1393. /**
  1394. * UE采用的事件基类
  1395. * @file
  1396. * @module UE
  1397. * @class EventBase
  1398. * @since 1.2.6.1
  1399. */
  1400. /**
  1401. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1402. * @unfile
  1403. * @module UE
  1404. */
  1405. /**
  1406. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1407. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1408. * @unfile
  1409. * @module UE
  1410. * @class EventBase
  1411. */
  1412. /**
  1413. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1414. * @constructor
  1415. * @example
  1416. * ```javascript
  1417. * UE.EventBase.call(editor);
  1418. * ```
  1419. */
  1420. var EventBase = UE.EventBase = function () {};
  1421. EventBase.prototype = {
  1422. /**
  1423. * 注册事件监听器
  1424. * @method addListener
  1425. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1426. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1427. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1428. * @example
  1429. * ```javascript
  1430. * editor.addListener('selectionchange',function(){
  1431. * console.log("选区已经变化!");
  1432. * })
  1433. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1434. * if(type == 'beforegetcontent'){
  1435. * //do something
  1436. * }else{
  1437. * //do something
  1438. * }
  1439. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1440. * })
  1441. * ```
  1442. * @see UE.EventBase:fireEvent(String)
  1443. */
  1444. addListener:function (types, listener) {
  1445. types = utils.trim(types).split(/\s+/);
  1446. for (var i = 0, ti; ti = types[i++];) {
  1447. getListener(this, ti, true).push(listener);
  1448. }
  1449. },
  1450. on : function(types, listener){
  1451. return this.addListener(types,listener);
  1452. },
  1453. off : function(types, listener){
  1454. return this.removeListener(types, listener)
  1455. },
  1456. trigger:function(){
  1457. return this.fireEvent.apply(this,arguments);
  1458. },
  1459. /**
  1460. * 移除事件监听器
  1461. * @method removeListener
  1462. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1463. * @param { Function } fn 移除监听事件的函数引用
  1464. * @example
  1465. * ```javascript
  1466. * //changeCallback为方法体
  1467. * editor.removeListener("selectionchange",changeCallback);
  1468. * ```
  1469. */
  1470. removeListener:function (types, listener) {
  1471. types = utils.trim(types).split(/\s+/);
  1472. for (var i = 0, ti; ti = types[i++];) {
  1473. utils.removeItem(getListener(this, ti) || [], listener);
  1474. }
  1475. },
  1476. /**
  1477. * 触发事件
  1478. * @method fireEvent
  1479. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1480. * @remind 该方法会触发addListener
  1481. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1482. * @example
  1483. * ```javascript
  1484. * editor.fireEvent("selectionchange");
  1485. * ```
  1486. */
  1487. /**
  1488. * 触发事件
  1489. * @method fireEvent
  1490. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1491. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1492. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1493. * @example
  1494. * ```javascript
  1495. *
  1496. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1497. *
  1498. * console.log( arg1 + " " + arg2 );
  1499. *
  1500. * } );
  1501. *
  1502. * //触发selectionchange事件, 会执行上面的事件监听器
  1503. * //output: Hello World
  1504. * editor.fireEvent("selectionchange", "Hello", "World");
  1505. * ```
  1506. */
  1507. fireEvent:function () {
  1508. var types = arguments[0];
  1509. types = utils.trim(types).split(' ');
  1510. for (var i = 0, ti; ti = types[i++];) {
  1511. var listeners = getListener(this, ti),
  1512. r, t, k;
  1513. if (listeners) {
  1514. k = listeners.length;
  1515. while (k--) {
  1516. if(!listeners[k])continue;
  1517. t = listeners[k].apply(this, arguments);
  1518. if(t === true){
  1519. return t;
  1520. }
  1521. if (t !== undefined) {
  1522. r = t;
  1523. }
  1524. }
  1525. }
  1526. if (t = this['on' + ti.toLowerCase()]) {
  1527. r = t.apply(this, arguments);
  1528. }
  1529. }
  1530. return r;
  1531. }
  1532. };
  1533. /**
  1534. * 获得对象所拥有监听类型的所有监听器
  1535. * @unfile
  1536. * @module UE
  1537. * @since 1.2.6.1
  1538. * @method getListener
  1539. * @public
  1540. * @param { Object } obj 查询监听器的对象
  1541. * @param { String } type 事件类型
  1542. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1543. * @return { Array } 监听器数组
  1544. */
  1545. function getListener(obj, type, force) {
  1546. var allListeners;
  1547. type = type.toLowerCase();
  1548. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1549. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1550. }
  1551. // core/dtd.js
  1552. ///import editor.js
  1553. ///import core/dom/dom.js
  1554. ///import core/utils.js
  1555. /**
  1556. * dtd html语义化的体现类
  1557. * @constructor
  1558. * @namespace dtd
  1559. */
  1560. var dtd = dom.dtd = (function() {
  1561. function _( s ) {
  1562. for (var k in s) {
  1563. s[k.toUpperCase()] = s[k];
  1564. }
  1565. return s;
  1566. }
  1567. var X = utils.extend2;
  1568. var A = _({isindex:1,fieldset:1}),
  1569. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1570. C = X( _({a:1}), B ),
  1571. D = X( {iframe:1}, C ),
  1572. E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),
  1573. F = _({ins:1,del:1,script:1,style:1}),
  1574. G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ),
  1575. H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ),
  1576. I = X( _({p:1}), H ),
  1577. J = X( _({iframe:1}), H, B ),
  1578. K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),
  1579. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1580. M = _({tr:1}),
  1581. N = _({'#':1}),
  1582. O = X( _({param:1}), K ),
  1583. P = X( _({form:1}), A, D, E, I ),
  1584. Q = _({li:1,ol:1,ul:1}),
  1585. R = _({style:1,script:1}),
  1586. S = _({base:1,link:1,meta:1,title:1}),
  1587. T = X( S, R ),
  1588. U = _({head:1,body:1}),
  1589. V = _({html:1});
  1590. var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),
  1591. empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});
  1592. return _({
  1593. // $ 表示自定的属性
  1594. // body外的元素列表.
  1595. $nonBodyContent: X( V, U, S ),
  1596. //块结构元素列表
  1597. $block : block,
  1598. //内联元素列表
  1599. $inline : L,
  1600. $inlineWithA : X(_({a:1}),L),
  1601. $body : X( _({script:1,style:1}), block ),
  1602. $cdata : _({script:1,style:1}),
  1603. //自闭和元素
  1604. $empty : empty,
  1605. //不是自闭合,但不能让range选中里边
  1606. $nonChild : _({iframe:1,textarea:1}),
  1607. //列表元素列表
  1608. $listItem : _({dd:1,dt:1,li:1}),
  1609. //列表根元素列表
  1610. $list: _({ul:1,ol:1,dl:1}),
  1611. //不能认为是空的元素
  1612. $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),
  1613. //如果没有子节点就可以删除的元素列表,像span,a
  1614. $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}),
  1615. $removeEmptyBlock : _({'p':1,'div':1}),
  1616. //在table元素里的元素列表
  1617. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1618. //不转换的标签
  1619. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1620. html: U,
  1621. head: T,
  1622. style: N,
  1623. script: N,
  1624. body: P,
  1625. base: {},
  1626. link: {},
  1627. meta: {},
  1628. title: N,
  1629. col : {},
  1630. tr : _({td:1,th:1}),
  1631. img : {},
  1632. embed: {},
  1633. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1634. noscript : P,
  1635. td : P,
  1636. br : {},
  1637. th : P,
  1638. center : P,
  1639. kbd : L,
  1640. button : X( I, E ),
  1641. basefont : {},
  1642. h5 : L,
  1643. h4 : L,
  1644. samp : L,
  1645. h6 : L,
  1646. ol : Q,
  1647. h1 : L,
  1648. h3 : L,
  1649. option : N,
  1650. h2 : L,
  1651. form : X( A, D, E, I ),
  1652. select : _({optgroup:1,option:1}),
  1653. font : L,
  1654. ins : L,
  1655. menu : Q,
  1656. abbr : L,
  1657. label : L,
  1658. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1659. code : L,
  1660. tfoot : M,
  1661. cite : L,
  1662. li : P,
  1663. input : {},
  1664. iframe : P,
  1665. strong : L,
  1666. textarea : N,
  1667. noframes : P,
  1668. big : L,
  1669. small : L,
  1670. //trace:
  1671. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1672. hr : L,
  1673. dt : L,
  1674. sub : L,
  1675. optgroup : _({option:1}),
  1676. param : {},
  1677. bdo : L,
  1678. 'var' : L,
  1679. div : P,
  1680. object : O,
  1681. sup : L,
  1682. dd : P,
  1683. strike : L,
  1684. area : {},
  1685. dir : Q,
  1686. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1687. applet : O,
  1688. dl : _({dt:1,dd:1}),
  1689. del : L,
  1690. isindex : {},
  1691. fieldset : X( _({legend:1}), K ),
  1692. thead : M,
  1693. ul : Q,
  1694. acronym : L,
  1695. b : L,
  1696. a : X( _({a:1}), J ),
  1697. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1698. caption : L,
  1699. i : L,
  1700. u : L,
  1701. tbody : M,
  1702. s : L,
  1703. address : X( D, I ),
  1704. tt : L,
  1705. legend : L,
  1706. q : L,
  1707. pre : X( G, C ),
  1708. p : X(_({'a':1}),L),
  1709. em :L,
  1710. dfn : L
  1711. });
  1712. })();
  1713. // core/domUtils.js
  1714. /**
  1715. * Dom操作工具包
  1716. * @file
  1717. * @module UE.dom.domUtils
  1718. * @since 1.2.6.1
  1719. */
  1720. /**
  1721. * Dom操作工具包
  1722. * @unfile
  1723. * @module UE.dom.domUtils
  1724. */
  1725. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1726. var tmpNode = startFromChild && node[start],
  1727. parent;
  1728. !tmpNode && (tmpNode = node[ltr]);
  1729. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1730. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1731. return null;
  1732. }
  1733. tmpNode = parent[ltr];
  1734. }
  1735. if (tmpNode && fn && !fn(tmpNode)) {
  1736. return getDomNode(tmpNode, start, ltr, false, fn);
  1737. }
  1738. return tmpNode;
  1739. }
  1740. var attrFix = ie && browser.version < 9 ? {
  1741. tabindex:"tabIndex",
  1742. readonly:"readOnly",
  1743. "for":"htmlFor",
  1744. "class":"className",
  1745. maxlength:"maxLength",
  1746. cellspacing:"cellSpacing",
  1747. cellpadding:"cellPadding",
  1748. rowspan:"rowSpan",
  1749. colspan:"colSpan",
  1750. usemap:"useMap",
  1751. frameborder:"frameBorder"
  1752. } : {
  1753. tabindex:"tabIndex",
  1754. readonly:"readOnly"
  1755. },
  1756. styleBlock = utils.listToMap([
  1757. '-webkit-box', '-moz-box', 'block' ,
  1758. 'list-item' , 'table' , 'table-row-group' ,
  1759. 'table-header-group', 'table-footer-group' ,
  1760. 'table-row' , 'table-column-group' , 'table-column' ,
  1761. 'table-cell' , 'table-caption'
  1762. ]);
  1763. var domUtils = dom.domUtils = {
  1764. //节点常量
  1765. NODE_ELEMENT:1,
  1766. NODE_DOCUMENT:9,
  1767. NODE_TEXT:3,
  1768. NODE_COMMENT:8,
  1769. NODE_DOCUMENT_FRAGMENT:11,
  1770. //位置关系
  1771. POSITION_IDENTICAL:0,
  1772. POSITION_DISCONNECTED:1,
  1773. POSITION_FOLLOWING:2,
  1774. POSITION_PRECEDING:4,
  1775. POSITION_IS_CONTAINED:8,
  1776. POSITION_CONTAINS:16,
  1777. //ie6使用其他的会有一段空白出现
  1778. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1779. //-------------------------Node部分--------------------------------
  1780. keys:{
  1781. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1782. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1783. 37:1, 38:1, 39:1, 40:1,
  1784. 13:1 /*enter*/
  1785. },
  1786. /**
  1787. * 获取节点A相对于节点B的位置关系
  1788. * @method getPosition
  1789. * @param { Node } nodeA 需要查询位置关系的节点A
  1790. * @param { Node } nodeB 需要查询位置关系的节点B
  1791. * @return { Number } 节点A与节点B的关系
  1792. * @example
  1793. * ```javascript
  1794. * //output: 20
  1795. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1796. *
  1797. * switch ( position ) {
  1798. *
  1799. * //0
  1800. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1801. * console.log('元素相同');
  1802. * break;
  1803. * //1
  1804. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1805. * console.log('两个节点在不同的文档中');
  1806. * break;
  1807. * //2
  1808. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1809. * console.log('节点A在节点B之后');
  1810. * break;
  1811. * //4
  1812. * case UE.dom.domUtils.POSITION_PRECEDING;
  1813. * console.log('节点A在节点B之前');
  1814. * break;
  1815. * //8
  1816. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1817. * console.log('节点A被节点B包含');
  1818. * break;
  1819. * case 10:
  1820. * console.log('节点A被节点B包含且节点A在节点B之后');
  1821. * break;
  1822. * //16
  1823. * case UE.dom.domUtils.POSITION_CONTAINS:
  1824. * console.log('节点A包含节点B');
  1825. * break;
  1826. * case 20:
  1827. * console.log('节点A包含节点B且节点A在节点B之前');
  1828. * break;
  1829. *
  1830. * }
  1831. * ```
  1832. */
  1833. getPosition:function (nodeA, nodeB) {
  1834. // 如果两个节点是同一个节点
  1835. if (nodeA === nodeB) {
  1836. // domUtils.POSITION_IDENTICAL
  1837. return 0;
  1838. }
  1839. var node,
  1840. parentsA = [nodeA],
  1841. parentsB = [nodeB];
  1842. node = nodeA;
  1843. while (node = node.parentNode) {
  1844. // 如果nodeB是nodeA的祖先节点
  1845. if (node === nodeB) {
  1846. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1847. return 10;
  1848. }
  1849. parentsA.push(node);
  1850. }
  1851. node = nodeB;
  1852. while (node = node.parentNode) {
  1853. // 如果nodeA是nodeB的祖先节点
  1854. if (node === nodeA) {
  1855. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1856. return 20;
  1857. }
  1858. parentsB.push(node);
  1859. }
  1860. parentsA.reverse();
  1861. parentsB.reverse();
  1862. if (parentsA[0] !== parentsB[0]) {
  1863. // domUtils.POSITION_DISCONNECTED
  1864. return 1;
  1865. }
  1866. var i = -1;
  1867. while (i++, parentsA[i] === parentsB[i]) {
  1868. }
  1869. nodeA = parentsA[i];
  1870. nodeB = parentsB[i];
  1871. while (nodeA = nodeA.nextSibling) {
  1872. if (nodeA === nodeB) {
  1873. // domUtils.POSITION_PRECEDING
  1874. return 4
  1875. }
  1876. }
  1877. // domUtils.POSITION_FOLLOWING
  1878. return 2;
  1879. },
  1880. /**
  1881. * 检测节点node在父节点中的索引位置
  1882. * @method getNodeIndex
  1883. * @param { Node } node 需要检测的节点对象
  1884. * @return { Number } 该节点在父节点中的位置
  1885. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1886. */
  1887. /**
  1888. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1889. * @method getNodeIndex
  1890. * @param { Node } node 需要检测的节点对象
  1891. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1892. * @return { Number } 该节点在父节点中的位置
  1893. * @example
  1894. * ```javascript
  1895. *
  1896. * var node = document.createElement("div");
  1897. *
  1898. * node.appendChild( document.createTextNode( "hello" ) );
  1899. * node.appendChild( document.createTextNode( "world" ) );
  1900. * node.appendChild( node = document.createElement( "div" ) );
  1901. *
  1902. * //output: 2
  1903. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1904. *
  1905. * //output: 1
  1906. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1907. *
  1908. * ```
  1909. */
  1910. getNodeIndex:function (node, ignoreTextNode) {
  1911. var preNode = node,
  1912. i = 0;
  1913. while (preNode = preNode.previousSibling) {
  1914. if (ignoreTextNode && preNode.nodeType == 3) {
  1915. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1916. i++;
  1917. }
  1918. continue;
  1919. }
  1920. i++;
  1921. }
  1922. return i;
  1923. },
  1924. /**
  1925. * 检测节点node是否在给定的document对象上
  1926. * @method inDoc
  1927. * @param { Node } node 需要检测的节点对象
  1928. * @param { DomDocument } doc 需要检测的document对象
  1929. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1930. * @example
  1931. * ```javascript
  1932. *
  1933. * var node = document.createElement("div");
  1934. *
  1935. * //output: false
  1936. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1937. *
  1938. * document.body.appendChild( node );
  1939. *
  1940. * //output: true
  1941. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1942. *
  1943. * ```
  1944. */
  1945. inDoc:function (node, doc) {
  1946. return domUtils.getPosition(node, doc) == 10;
  1947. },
  1948. /**
  1949. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1950. * 查找的起点是给定node节点的父节点。
  1951. * @method findParent
  1952. * @param { Node } node 需要查找的节点
  1953. * @param { Function } filterFn 自定义的过滤方法。
  1954. * @warning 查找的终点是到body节点为止
  1955. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1956. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1957. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1958. * @example
  1959. * ```javascript
  1960. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1961. *
  1962. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1963. * return node.tagName === "HTML";
  1964. *
  1965. * } );
  1966. *
  1967. * //output: true
  1968. * console.log( filterNode === null );
  1969. * ```
  1970. */
  1971. /**
  1972. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1973. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1974. * @method findParent
  1975. * @param { Node } node 需要查找的节点
  1976. * @param { Function } filterFn 自定义的过滤方法。
  1977. * @param { Boolean } includeSelf 查找过程是否包含自身
  1978. * @warning 查找的终点是到body节点为止
  1979. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1980. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1981. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1982. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1983. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1984. * @example
  1985. * ```html
  1986. * <body>
  1987. *
  1988. * <div id="test">
  1989. * </div>
  1990. *
  1991. * <script type="text/javascript">
  1992. *
  1993. * //output: DIV, BODY
  1994. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1995. *
  1996. * console.log( node.tagName );
  1997. * return false;
  1998. *
  1999. * }, true );
  2000. *
  2001. * </script>
  2002. * </body>
  2003. * ```
  2004. */
  2005. findParent:function (node, filterFn, includeSelf) {
  2006. if (node && !domUtils.isBody(node)) {
  2007. node = includeSelf ? node : node.parentNode;
  2008. while (node) {
  2009. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2010. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2011. }
  2012. node = node.parentNode;
  2013. }
  2014. }
  2015. return null;
  2016. },
  2017. /**
  2018. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2019. * @method findParentByTagName
  2020. * @param { Node } node 需要查找的节点对象
  2021. * @param { Array } tagNames 需要查找的父节点的名称数组
  2022. * @warning 查找的终点是到body节点为止
  2023. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2024. * @example
  2025. * ```javascript
  2026. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2027. * //output: BODY
  2028. * console.log( node.tagName );
  2029. * ```
  2030. */
  2031. /**
  2032. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2033. * 否则, 起点是node的父节点。
  2034. * @method findParentByTagName
  2035. * @param { Node } node 需要查找的节点对象
  2036. * @param { Array } tagNames 需要查找的父节点的名称数组
  2037. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2038. * @warning 查找的终点是到body节点为止
  2039. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2040. * @example
  2041. * ```javascript
  2042. * var queryTarget = document.getElementsByTagName("div")[0];
  2043. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2044. * //output: true
  2045. * console.log( queryTarget === node );
  2046. * ```
  2047. */
  2048. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2049. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2050. return domUtils.findParent(node, function (node) {
  2051. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2052. }, includeSelf);
  2053. },
  2054. /**
  2055. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2056. * @method findParents
  2057. * @param { Node } node 需要查找的节点对象
  2058. * @return { Array } 给定节点的祖先节点数组
  2059. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2060. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2061. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2062. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2063. */
  2064. /**
  2065. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2066. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2067. * @method findParents
  2068. * @param { Node } node 需要查找的节点对象
  2069. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2070. * @return { Array } 给定节点的祖先节点数组
  2071. */
  2072. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2073. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2074. while (node = domUtils.findParent(node, filterFn)) {
  2075. parents.push(node);
  2076. }
  2077. return closerFirst ? parents : parents.reverse();
  2078. },
  2079. /**
  2080. * 在节点node后面插入新节点newNode
  2081. * @method insertAfter
  2082. * @param { Node } node 目标节点
  2083. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2084. * @return { Node } 新插入的节点
  2085. */
  2086. insertAfter:function (node, newNode) {
  2087. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2088. node.parentNode.appendChild(newNode);
  2089. },
  2090. /**
  2091. * 删除节点node及其下属的所有节点
  2092. * @method remove
  2093. * @param { Node } node 需要删除的节点对象
  2094. * @return { Node } 返回刚删除的节点对象
  2095. * @example
  2096. * ```html
  2097. * <div id="test">
  2098. * <div id="child">你好</div>
  2099. * </div>
  2100. * <script>
  2101. * UE.dom.domUtils.remove( document.body, false );
  2102. * //output: false
  2103. * console.log( document.getElementById( "child" ) !== null );
  2104. * </script>
  2105. * ```
  2106. */
  2107. /**
  2108. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2109. * @method remove
  2110. * @param { Node } node 需要删除的节点对象
  2111. * @param { Boolean } keepChildren 是否需要保留子节点
  2112. * @return { Node } 返回刚删除的节点对象
  2113. * @example
  2114. * ```html
  2115. * <div id="test">
  2116. * <div id="child">你好</div>
  2117. * </div>
  2118. * <script>
  2119. * UE.dom.domUtils.remove( document.body, true );
  2120. * //output: true
  2121. * console.log( document.getElementById( "child" ) !== null );
  2122. * </script>
  2123. * ```
  2124. */
  2125. remove:function (node, keepChildren) {
  2126. var parent = node.parentNode,
  2127. child;
  2128. if (parent) {
  2129. if (keepChildren && node.hasChildNodes()) {
  2130. while (child = node.firstChild) {
  2131. parent.insertBefore(child, node);
  2132. }
  2133. }
  2134. parent.removeChild(node);
  2135. }
  2136. return node;
  2137. },
  2138. /**
  2139. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2140. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2141. * @method getNextDomNode
  2142. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2143. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2144. * @example
  2145. * ```html
  2146. * <body>
  2147. * <div id="test">
  2148. * <span></span>
  2149. * </div>
  2150. * <i>xxx</i>
  2151. * </body>
  2152. * <script>
  2153. *
  2154. * //output: i节点
  2155. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2156. *
  2157. * </script>
  2158. * ```
  2159. * @example
  2160. * ```html
  2161. * <body>
  2162. * <div>
  2163. * <span></span>
  2164. * <i id="test">xxx</i>
  2165. * </div>
  2166. * <b>xxx</b>
  2167. * </body>
  2168. * <script>
  2169. *
  2170. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2171. * //output: b节点
  2172. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2173. *
  2174. * </script>
  2175. * ```
  2176. */
  2177. /**
  2178. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2179. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2180. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2181. * @method getNextDomNode
  2182. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2183. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2184. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2185. * @see UE.dom.domUtils.getNextDomNode(Node)
  2186. */
  2187. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2188. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2189. },
  2190. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2191. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2192. },
  2193. /**
  2194. * 检测节点node是否属是UEditor定义的bookmark节点
  2195. * @method isBookmarkNode
  2196. * @private
  2197. * @param { Node } node 需要检测的节点对象
  2198. * @return { Boolean } 是否是bookmark节点
  2199. * @example
  2200. * ```html
  2201. * <span id="_baidu_bookmark_1"></span>
  2202. * <script>
  2203. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2204. * //output: true
  2205. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2206. * </script>
  2207. * ```
  2208. */
  2209. isBookmarkNode:function (node) {
  2210. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2211. },
  2212. /**
  2213. * 获取节点node所属的window对象
  2214. * @method getWindow
  2215. * @param { Node } node 节点对象
  2216. * @return { Window } 当前节点所属的window对象
  2217. * @example
  2218. * ```javascript
  2219. * //output: true
  2220. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2221. * ```
  2222. */
  2223. getWindow:function (node) {
  2224. var doc = node.ownerDocument || node;
  2225. return doc.defaultView || doc.parentWindow;
  2226. },
  2227. /**
  2228. * 获取离nodeA与nodeB最近的公共的祖先节点
  2229. * @method getCommonAncestor
  2230. * @param { Node } nodeA 第一个节点
  2231. * @param { Node } nodeB 第二个节点
  2232. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2233. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2234. * @example
  2235. * ```javascript
  2236. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2237. * //output: true
  2238. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2239. * ```
  2240. */
  2241. getCommonAncestor:function (nodeA, nodeB) {
  2242. if (nodeA === nodeB)
  2243. return nodeA;
  2244. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2245. while (parent = parent.parentNode) {
  2246. if (parent === nodeB) {
  2247. return parent;
  2248. }
  2249. parentsA.push(parent);
  2250. }
  2251. parent = nodeB;
  2252. while (parent = parent.parentNode) {
  2253. if (parent === nodeA)
  2254. return parent;
  2255. parentsB.push(parent);
  2256. }
  2257. parentsA.reverse();
  2258. parentsB.reverse();
  2259. while (i++, parentsA[i] === parentsB[i]) {
  2260. }
  2261. return i == 0 ? null : parentsA[i - 1];
  2262. },
  2263. /**
  2264. * 清除node节点左右连续为空的兄弟inline节点
  2265. * @method clearEmptySibling
  2266. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2267. * 则这些兄弟节点将被删除
  2268. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2269. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2270. * @example
  2271. * ```html
  2272. * <body>
  2273. * <div></div>
  2274. * <span id="test"></span>
  2275. * <i></i>
  2276. * <b></b>
  2277. * <em>xxx</em>
  2278. * <span></span>
  2279. * </body>
  2280. * <script>
  2281. *
  2282. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2283. *
  2284. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2285. * console.log( document.body.innerHTML );
  2286. *
  2287. * </script>
  2288. * ```
  2289. */
  2290. /**
  2291. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2292. * 则忽略对右边兄弟节点的操作。
  2293. * @method clearEmptySibling
  2294. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2295. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2296. * 则这些兄弟节点将被删除
  2297. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2298. */
  2299. /**
  2300. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2301. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2302. * @method clearEmptySibling
  2303. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2304. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2305. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2306. * 则这些兄弟节点将被删除
  2307. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2308. */
  2309. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2310. function clear(next, dir) {
  2311. var tmpNode;
  2312. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2313. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2314. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2315. tmpNode = next[dir];
  2316. domUtils.remove(next);
  2317. next = tmpNode;
  2318. }
  2319. }
  2320. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2321. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2322. },
  2323. /**
  2324. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2325. * @method split
  2326. * @param { Node } textNode 需要拆分的文本节点对象
  2327. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2328. * @return { Node } 拆分后形成的新节点
  2329. * @example
  2330. * ```html
  2331. * <div id="test">abcdef</div>
  2332. * <script>
  2333. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2334. * //output: def
  2335. * console.log( newNode.nodeValue );
  2336. * </script>
  2337. * ```
  2338. */
  2339. split:function (node, offset) {
  2340. var doc = node.ownerDocument;
  2341. if (browser.ie && offset == node.nodeValue.length) {
  2342. var next = doc.createTextNode('');
  2343. return domUtils.insertAfter(node, next);
  2344. }
  2345. var retval = node.splitText(offset);
  2346. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2347. if (browser.ie8) {
  2348. var tmpNode = doc.createTextNode('');
  2349. domUtils.insertAfter(retval, tmpNode);
  2350. domUtils.remove(tmpNode);
  2351. }
  2352. return retval;
  2353. },
  2354. /**
  2355. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2356. * @method isWhitespace
  2357. * @param { Node } node 需要检测的节点对象
  2358. * @return { Boolean } 检测的节点是否为空
  2359. * @example
  2360. * ```html
  2361. * <div id="test">
  2362. *
  2363. * </div>
  2364. * <script>
  2365. * //output: true
  2366. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2367. * </script>
  2368. * ```
  2369. */
  2370. isWhitespace:function (node) {
  2371. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2372. },
  2373. /**
  2374. * 获取元素element相对于viewport的位置坐标
  2375. * @method getXY
  2376. * @param { Node } element 需要计算位置的节点对象
  2377. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2378. * y代表垂直偏移距离。
  2379. *
  2380. * @example
  2381. * ```javascript
  2382. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2383. * //output: test的坐标为: 12, 24
  2384. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2385. * ```
  2386. */
  2387. getXY:function (element) {
  2388. var x = 0, y = 0;
  2389. while (element.offsetParent) {
  2390. y += element.offsetTop;
  2391. x += element.offsetLeft;
  2392. element = element.offsetParent;
  2393. }
  2394. return { 'x':x, 'y':y};
  2395. },
  2396. /**
  2397. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2398. * @method on
  2399. * @param { Node } element 需要绑定事件的节点对象
  2400. * @param { String } type 绑定的事件类型
  2401. * @param { Function } handler 事件处理器
  2402. * @example
  2403. * ```javascript
  2404. * UE.dom.domUtils.on(document.body,"click",function(e){
  2405. * //e为事件对象,this为被点击元素对戏那个
  2406. * });
  2407. * ```
  2408. */
  2409. /**
  2410. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2411. * @method on
  2412. * @param { Node } element 需要绑定事件的节点对象
  2413. * @param { Array } type 绑定的事件类型数组
  2414. * @param { Function } handler 事件处理器
  2415. * @example
  2416. * ```javascript
  2417. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2418. * //evt为事件对象,this为被点击元素对象
  2419. * });
  2420. * ```
  2421. */
  2422. on:function (element, type, handler) {
  2423. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2424. k = types.length;
  2425. if (k) while (k--) {
  2426. type = types[k];
  2427. if (element.addEventListener) {
  2428. element.addEventListener(type, handler, false);
  2429. } else {
  2430. if (!handler._d) {
  2431. handler._d = {
  2432. els : []
  2433. };
  2434. }
  2435. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2436. if (!handler._d[key] || index == -1) {
  2437. if(index == -1){
  2438. handler._d.els.push(element);
  2439. }
  2440. if(!handler._d[key]){
  2441. handler._d[key] = function (evt) {
  2442. return handler.call(evt.srcElement, evt || window.event);
  2443. };
  2444. }
  2445. element.attachEvent('on' + type, handler._d[key]);
  2446. }
  2447. }
  2448. }
  2449. element = null;
  2450. },
  2451. /**
  2452. * 解除DOM事件绑定
  2453. * @method un
  2454. * @param { Node } element 需要解除事件绑定的节点对象
  2455. * @param { String } type 需要接触绑定的事件类型
  2456. * @param { Function } handler 对应的事件处理器
  2457. * @example
  2458. * ```javascript
  2459. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2460. * //evt为事件对象,this为被点击元素对象
  2461. * });
  2462. * ```
  2463. */
  2464. /**
  2465. * 解除DOM事件绑定
  2466. * @method un
  2467. * @param { Node } element 需要解除事件绑定的节点对象
  2468. * @param { Array } type 需要接触绑定的事件类型数组
  2469. * @param { Function } handler 对应的事件处理器
  2470. * @example
  2471. * ```javascript
  2472. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2473. * //evt为事件对象,this为被点击元素对象
  2474. * });
  2475. * ```
  2476. */
  2477. un:function (element, type, handler) {
  2478. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2479. k = types.length;
  2480. if (k) while (k--) {
  2481. type = types[k];
  2482. if (element.removeEventListener) {
  2483. element.removeEventListener(type, handler, false);
  2484. } else {
  2485. var key = type + handler.toString();
  2486. try{
  2487. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2488. }catch(e){}
  2489. if (handler._d && handler._d[key]) {
  2490. var index = utils.indexOf(handler._d.els,element);
  2491. if(index!=-1){
  2492. handler._d.els.splice(index,1);
  2493. }
  2494. handler._d.els.length == 0 && delete handler._d[key];
  2495. }
  2496. }
  2497. }
  2498. },
  2499. /**
  2500. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2501. * @method isSameElement
  2502. * @param { Node } nodeA 需要比较的节点
  2503. * @param { Node } nodeB 需要比较的节点
  2504. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2505. * @example
  2506. * ```html
  2507. * <span style="font-size:12px">ssss</span>
  2508. * <span style="font-size:12px">bbbbb</span>
  2509. * <span style="font-size:13px">ssss</span>
  2510. * <span style="font-size:14px">bbbbb</span>
  2511. *
  2512. * <script>
  2513. *
  2514. * var nodes = document.getElementsByTagName( "span" );
  2515. *
  2516. * //output: true
  2517. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2518. *
  2519. * //output: false
  2520. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2521. *
  2522. * </script>
  2523. * ```
  2524. */
  2525. isSameElement:function (nodeA, nodeB) {
  2526. if (nodeA.tagName != nodeB.tagName) {
  2527. return false;
  2528. }
  2529. var thisAttrs = nodeA.attributes,
  2530. otherAttrs = nodeB.attributes;
  2531. if (!ie && thisAttrs.length != otherAttrs.length) {
  2532. return false;
  2533. }
  2534. var attrA, attrB, al = 0, bl = 0;
  2535. for (var i = 0; attrA = thisAttrs[i++];) {
  2536. if (attrA.nodeName == 'style') {
  2537. if (attrA.specified) {
  2538. al++;
  2539. }
  2540. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2541. continue;
  2542. } else {
  2543. return false;
  2544. }
  2545. }
  2546. if (ie) {
  2547. if (attrA.specified) {
  2548. al++;
  2549. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2550. } else {
  2551. continue;
  2552. }
  2553. } else {
  2554. attrB = nodeB.attributes[attrA.nodeName];
  2555. }
  2556. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2557. return false;
  2558. }
  2559. }
  2560. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2561. if (ie) {
  2562. for (i = 0; attrB = otherAttrs[i++];) {
  2563. if (attrB.specified) {
  2564. bl++;
  2565. }
  2566. }
  2567. if (al != bl) {
  2568. return false;
  2569. }
  2570. }
  2571. return true;
  2572. },
  2573. /**
  2574. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2575. * @method isSameStyle
  2576. * @param { Node } nodeA 需要比较的节点
  2577. * @param { Node } nodeB 需要比较的节点
  2578. * @return { Boolean } 两个节点是否具有相同的style属性值
  2579. * @example
  2580. * ```html
  2581. * <span style="font-size:12px">ssss</span>
  2582. * <span style="font-size:12px">bbbbb</span>
  2583. * <span style="font-size:13px">ssss</span>
  2584. * <span style="font-size:14px">bbbbb</span>
  2585. *
  2586. * <script>
  2587. *
  2588. * var nodes = document.getElementsByTagName( "span" );
  2589. *
  2590. * //output: true
  2591. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2592. *
  2593. * //output: false
  2594. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2595. *
  2596. * </script>
  2597. * ```
  2598. */
  2599. isSameStyle:function (nodeA, nodeB) {
  2600. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2601. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2602. if (browser.opera) {
  2603. styleA = nodeA.style;
  2604. styleB = nodeB.style;
  2605. if (styleA.length != styleB.length)
  2606. return false;
  2607. for (var p in styleA) {
  2608. if (/^(\d+|csstext)$/i.test(p)) {
  2609. continue;
  2610. }
  2611. if (styleA[p] != styleB[p]) {
  2612. return false;
  2613. }
  2614. }
  2615. return true;
  2616. }
  2617. if (!styleA || !styleB) {
  2618. return styleA == styleB;
  2619. }
  2620. styleA = styleA.split(';');
  2621. styleB = styleB.split(';');
  2622. if (styleA.length != styleB.length) {
  2623. return false;
  2624. }
  2625. for (var i = 0, ci; ci = styleA[i++];) {
  2626. if (utils.indexOf(styleB, ci) == -1) {
  2627. return false;
  2628. }
  2629. }
  2630. return true;
  2631. },
  2632. /**
  2633. * 检查节点node是否为block元素
  2634. * @method isBlockElm
  2635. * @param { Node } node 需要检测的节点对象
  2636. * @return { Boolean } 是否是block元素节点
  2637. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2638. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2639. * @example
  2640. * ```html
  2641. * <span id="test1" style="display: block"></span>
  2642. * <span id="test2"></span>
  2643. * <div id="test3" style="display: inline"></div>
  2644. *
  2645. * <script>
  2646. *
  2647. * //output: true
  2648. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2649. *
  2650. * //output: false
  2651. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2652. *
  2653. * //output: true
  2654. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2655. *
  2656. * </script>
  2657. * ```
  2658. */
  2659. isBlockElm:function (node) {
  2660. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2661. },
  2662. /**
  2663. * 检测node节点是否为body节点
  2664. * @method isBody
  2665. * @param { Element } node 需要检测的dom元素
  2666. * @return { Boolean } 给定的元素是否是body元素
  2667. * @example
  2668. * ```javascript
  2669. * //output: true
  2670. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2671. * ```
  2672. */
  2673. isBody:function (node) {
  2674. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2675. },
  2676. /**
  2677. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2678. * 拆分形成的两个节点之间是node节点
  2679. * @method breakParent
  2680. * @param { Node } node 作为分界的节点对象
  2681. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2682. * @return { Node } 给定的node分界节点
  2683. * @example
  2684. * ```javascript
  2685. *
  2686. * var node = document.createElement("span"),
  2687. * wrapNode = document.createElement( "div" ),
  2688. * parent = document.createElement("p");
  2689. *
  2690. * parent.appendChild( node );
  2691. * wrapNode.appendChild( parent );
  2692. *
  2693. * //拆分前
  2694. * //output: <p><span></span></p>
  2695. * console.log( wrapNode.innerHTML );
  2696. *
  2697. *
  2698. * UE.dom.domUtils.breakParent( node, parent );
  2699. * //拆分后
  2700. * //output: <p></p><span></span><p></p>
  2701. * console.log( wrapNode.innerHTML );
  2702. *
  2703. * ```
  2704. */
  2705. breakParent:function (node, parent) {
  2706. var tmpNode,
  2707. parentClone = node,
  2708. clone = node,
  2709. leftNodes,
  2710. rightNodes;
  2711. do {
  2712. parentClone = parentClone.parentNode;
  2713. if (leftNodes) {
  2714. tmpNode = parentClone.cloneNode(false);
  2715. tmpNode.appendChild(leftNodes);
  2716. leftNodes = tmpNode;
  2717. tmpNode = parentClone.cloneNode(false);
  2718. tmpNode.appendChild(rightNodes);
  2719. rightNodes = tmpNode;
  2720. } else {
  2721. leftNodes = parentClone.cloneNode(false);
  2722. rightNodes = leftNodes.cloneNode(false);
  2723. }
  2724. while (tmpNode = clone.previousSibling) {
  2725. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2726. }
  2727. while (tmpNode = clone.nextSibling) {
  2728. rightNodes.appendChild(tmpNode);
  2729. }
  2730. clone = parentClone;
  2731. } while (parent !== parentClone);
  2732. tmpNode = parent.parentNode;
  2733. tmpNode.insertBefore(leftNodes, parent);
  2734. tmpNode.insertBefore(rightNodes, parent);
  2735. tmpNode.insertBefore(node, rightNodes);
  2736. domUtils.remove(parent);
  2737. return node;
  2738. },
  2739. /**
  2740. * 检查节点node是否是空inline节点
  2741. * @method isEmptyInlineElement
  2742. * @param { Node } node 需要检测的节点对象
  2743. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2744. * @example
  2745. * ```html
  2746. * <b><i></i></b> => 1
  2747. * <b><i></i><u></u></b> => 1
  2748. * <b></b> => 1
  2749. * <b>xx<i></i></b> => 0
  2750. * ```
  2751. */
  2752. isEmptyInlineElement:function (node) {
  2753. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2754. return 0;
  2755. }
  2756. node = node.firstChild;
  2757. while (node) {
  2758. //如果是创建的bookmark就跳过
  2759. if (domUtils.isBookmarkNode(node)) {
  2760. return 0;
  2761. }
  2762. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2763. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2764. ) {
  2765. return 0;
  2766. }
  2767. node = node.nextSibling;
  2768. }
  2769. return 1;
  2770. },
  2771. /**
  2772. * 删除node节点下首尾两端的空白文本子节点
  2773. * @method trimWhiteTextNode
  2774. * @param { Element } node 需要执行删除操作的元素对象
  2775. * @example
  2776. * ```javascript
  2777. * var node = document.createElement("div");
  2778. *
  2779. * node.appendChild( document.createTextNode( "" ) );
  2780. *
  2781. * node.appendChild( document.createElement("div") );
  2782. *
  2783. * node.appendChild( document.createTextNode( "" ) );
  2784. *
  2785. * //3
  2786. * console.log( node.childNodes.length );
  2787. *
  2788. * UE.dom.domUtils.trimWhiteTextNode( node );
  2789. *
  2790. * //1
  2791. * console.log( node.childNodes.length );
  2792. * ```
  2793. */
  2794. trimWhiteTextNode:function (node) {
  2795. function remove(dir) {
  2796. var child;
  2797. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2798. node.removeChild(child);
  2799. }
  2800. }
  2801. remove('firstChild');
  2802. remove('lastChild');
  2803. },
  2804. /**
  2805. * 合并node节点下相同的子节点
  2806. * @name mergeChild
  2807. * @desc
  2808. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2809. * @example
  2810. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2811. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2812. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2813. */
  2814. mergeChild:function (node, tagName, attrs) {
  2815. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2816. for (var i = 0, ci; ci = list[i++];) {
  2817. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2818. continue;
  2819. }
  2820. //span单独处理
  2821. if (ci.tagName.toLowerCase() == 'span') {
  2822. if (node === ci.parentNode) {
  2823. domUtils.trimWhiteTextNode(node);
  2824. if (node.childNodes.length == 1) {
  2825. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2826. domUtils.remove(ci, true);
  2827. continue;
  2828. }
  2829. }
  2830. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2831. if (attrs) {
  2832. var style = attrs.style;
  2833. if (style) {
  2834. style = style.split(';');
  2835. for (var j = 0, s; s = style[j++];) {
  2836. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2837. }
  2838. }
  2839. }
  2840. if (domUtils.isSameStyle(ci, node)) {
  2841. domUtils.remove(ci, true);
  2842. }
  2843. continue;
  2844. }
  2845. if (domUtils.isSameElement(node, ci)) {
  2846. domUtils.remove(ci, true);
  2847. }
  2848. }
  2849. },
  2850. /**
  2851. * 原生方法getElementsByTagName的封装
  2852. * @method getElementsByTagName
  2853. * @param { Node } node 目标节点对象
  2854. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2855. * @return { Array } 符合条件的节点集合
  2856. */
  2857. getElementsByTagName:function (node, name,filter) {
  2858. if(filter && utils.isString(filter)){
  2859. var className = filter;
  2860. filter = function(node){return domUtils.hasClass(node,className)}
  2861. }
  2862. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2863. var arr = [];
  2864. for(var n = 0,ni;ni=name[n++];){
  2865. var list = node.getElementsByTagName(ni);
  2866. for (var i = 0, ci; ci = list[i++];) {
  2867. if(!filter || filter(ci))
  2868. arr.push(ci);
  2869. }
  2870. }
  2871. return arr;
  2872. },
  2873. /**
  2874. * 将节点node提取到父节点上
  2875. * @method mergeToParent
  2876. * @param { Element } node 需要提取的元素对象
  2877. * @example
  2878. * ```html
  2879. * <div id="parent">
  2880. * <div id="sub">
  2881. * <span id="child"></span>
  2882. * </div>
  2883. * </div>
  2884. *
  2885. * <script>
  2886. *
  2887. * var child = document.getElementById( "child" );
  2888. *
  2889. * //output: sub
  2890. * console.log( child.parentNode.id );
  2891. *
  2892. * UE.dom.domUtils.mergeToParent( child );
  2893. *
  2894. * //output: parent
  2895. * console.log( child.parentNode.id );
  2896. *
  2897. * </script>
  2898. * ```
  2899. */
  2900. mergeToParent:function (node) {
  2901. var parent = node.parentNode;
  2902. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2903. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2904. domUtils.trimWhiteTextNode(parent);
  2905. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2906. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2907. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2908. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2909. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2910. parent = parent.parentNode;
  2911. continue;
  2912. } else {
  2913. parent.style.cssText += ";" + node.style.cssText;
  2914. //trace:952 a标签要保持下划线
  2915. if (parent.tagName == 'A') {
  2916. parent.style.textDecoration = 'underline';
  2917. }
  2918. }
  2919. }
  2920. if (parent.tagName != 'A') {
  2921. parent === node.parentNode && domUtils.remove(node, true);
  2922. break;
  2923. }
  2924. }
  2925. parent = parent.parentNode;
  2926. }
  2927. },
  2928. /**
  2929. * 合并节点node的左右兄弟节点
  2930. * @method mergeSibling
  2931. * @param { Element } node 需要合并的目标节点
  2932. * @example
  2933. * ```html
  2934. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2935. *
  2936. * <script>
  2937. * var demoNode = document.getElementById("test");
  2938. * UE.dom.domUtils.mergeSibling( demoNode );
  2939. * //output: xxxxoooxxxx
  2940. * console.log( demoNode.innerHTML );
  2941. * </script>
  2942. * ```
  2943. */
  2944. /**
  2945. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2946. * @method mergeSibling
  2947. * @param { Element } node 需要合并的目标节点
  2948. * @param { Boolean } ignorePre 是否忽略合并左节点
  2949. * @example
  2950. * ```html
  2951. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2952. *
  2953. * <script>
  2954. * var demoNode = document.getElementById("test");
  2955. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2956. * //output: oooxxxx
  2957. * console.log( demoNode.innerHTML );
  2958. * </script>
  2959. * ```
  2960. */
  2961. /**
  2962. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2963. * @method mergeSibling
  2964. * @param { Element } node 需要合并的目标节点
  2965. * @param { Boolean } ignorePre 是否忽略合并左节点
  2966. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2967. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2968. * @example
  2969. * ```html
  2970. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2971. *
  2972. * <script>
  2973. * var demoNode = document.getElementById("test");
  2974. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2975. * //output: xxxxooo
  2976. * console.log( demoNode.innerHTML );
  2977. * </script>
  2978. * ```
  2979. */
  2980. mergeSibling:function (node, ignorePre, ignoreNext) {
  2981. function merge(rtl, start, node) {
  2982. var next;
  2983. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2984. while (next.firstChild) {
  2985. if (start == 'firstChild') {
  2986. node.insertBefore(next.lastChild, node.firstChild);
  2987. } else {
  2988. node.appendChild(next.firstChild);
  2989. }
  2990. }
  2991. domUtils.remove(next);
  2992. }
  2993. }
  2994. !ignorePre && merge('previousSibling', 'firstChild', node);
  2995. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2996. },
  2997. /**
  2998. * 设置节点node及其子节点不会被选中
  2999. * @method unSelectable
  3000. * @param { Element } node 需要执行操作的dom元素
  3001. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3002. * @example
  3003. * ```javascript
  3004. * UE.dom.domUtils.unSelectable( document.body );
  3005. * ```
  3006. */
  3007. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  3008. //for ie9
  3009. node.onselectstart = function () {
  3010. return false;
  3011. };
  3012. node.onclick = node.onkeyup = node.onkeydown = function () {
  3013. return false;
  3014. };
  3015. node.unselectable = 'on';
  3016. node.setAttribute("unselectable", "on");
  3017. for (var i = 0, ci; ci = node.all[i++];) {
  3018. switch (ci.tagName.toLowerCase()) {
  3019. case 'iframe' :
  3020. case 'textarea' :
  3021. case 'input' :
  3022. case 'select' :
  3023. break;
  3024. default :
  3025. ci.unselectable = 'on';
  3026. node.setAttribute("unselectable", "on");
  3027. }
  3028. }
  3029. } : function (node) {
  3030. node.style.MozUserSelect =
  3031. node.style.webkitUserSelect =
  3032. node.style.msUserSelect =
  3033. node.style.KhtmlUserSelect = 'none';
  3034. },
  3035. /**
  3036. * 删除节点node上的指定属性名称的属性
  3037. * @method removeAttributes
  3038. * @param { Node } node 需要删除属性的节点对象
  3039. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3040. * @example
  3041. * ```html
  3042. * <div id="wrap">
  3043. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3044. * </div>
  3045. *
  3046. * <script>
  3047. *
  3048. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3049. *
  3050. * //output: <span style="font-size:14px;">xxxxx</span>
  3051. * console.log( document.getElementById("wrap").innerHTML );
  3052. *
  3053. * </script>
  3054. * ```
  3055. */
  3056. /**
  3057. * 删除节点node上的指定属性名称的属性
  3058. * @method removeAttributes
  3059. * @param { Node } node 需要删除属性的节点对象
  3060. * @param { Array } attrNames 需要删除的属性名数组
  3061. * @example
  3062. * ```html
  3063. * <div id="wrap">
  3064. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3065. * </div>
  3066. *
  3067. * <script>
  3068. *
  3069. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3070. *
  3071. * //output: <span style="font-size:14px;">xxxxx</span>
  3072. * console.log( document.getElementById("wrap").innerHTML );
  3073. *
  3074. * </script>
  3075. * ```
  3076. */
  3077. removeAttributes:function (node, attrNames) {
  3078. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3079. for (var i = 0, ci; ci = attrNames[i++];) {
  3080. ci = attrFix[ci] || ci;
  3081. switch (ci) {
  3082. case 'className':
  3083. node[ci] = '';
  3084. break;
  3085. case 'style':
  3086. node.style.cssText = '';
  3087. var val = node.getAttributeNode('style');
  3088. !browser.ie && val && node.removeAttributeNode(val);
  3089. }
  3090. node.removeAttribute(ci);
  3091. }
  3092. },
  3093. /**
  3094. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3095. * @method createElement
  3096. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3097. * @param { String } tagName 需要创建的元素的标签名
  3098. * @param { Object } attrs 新创建的元素的属性key-value集合
  3099. * @return { Element } 新创建的元素对象
  3100. * @example
  3101. * ```javascript
  3102. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3103. * id: 'test'
  3104. * } );
  3105. *
  3106. * //output: DIV
  3107. * console.log( ele.tagName );
  3108. *
  3109. * //output: test
  3110. * console.log( ele.id );
  3111. *
  3112. * ```
  3113. */
  3114. createElement:function (doc, tag, attrs) {
  3115. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3116. },
  3117. /**
  3118. * 为节点node添加属性attrs,attrs为属性键值对
  3119. * @method setAttributes
  3120. * @param { Element } node 需要设置属性的元素对象
  3121. * @param { Object } attrs 需要设置的属性名-值对
  3122. * @return { Element } 设置属性的元素对象
  3123. * @example
  3124. * ```html
  3125. * <span id="test"></span>
  3126. *
  3127. * <script>
  3128. *
  3129. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3130. * id: 'demo'
  3131. * } );
  3132. *
  3133. * //output: demo
  3134. * console.log( testNode.id );
  3135. *
  3136. * </script>
  3137. *
  3138. */
  3139. setAttributes:function (node, attrs) {
  3140. for (var attr in attrs) {
  3141. if(attrs.hasOwnProperty(attr)){
  3142. var value = attrs[attr];
  3143. switch (attr) {
  3144. case 'class':
  3145. //ie下要这样赋值,setAttribute不起作用
  3146. node.className = value;
  3147. break;
  3148. case 'style' :
  3149. node.style.cssText = node.style.cssText + ";" + value;
  3150. break;
  3151. case 'innerHTML':
  3152. node[attr] = value;
  3153. break;
  3154. case 'value':
  3155. node.value = value;
  3156. break;
  3157. default:
  3158. node.setAttribute(attrFix[attr] || attr, value);
  3159. }
  3160. }
  3161. }
  3162. return node;
  3163. },
  3164. /**
  3165. * 获取元素element经过计算后的样式值
  3166. * @method getComputedStyle
  3167. * @param { Element } element 需要获取样式的元素对象
  3168. * @param { String } styleName 需要获取的样式名
  3169. * @return { String } 获取到的样式值
  3170. * @example
  3171. * ```html
  3172. * <style type="text/css">
  3173. * #test {
  3174. * font-size: 15px;
  3175. * }
  3176. * </style>
  3177. *
  3178. * <span id="test"></span>
  3179. *
  3180. * <script>
  3181. * //output: 15px
  3182. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3183. * </script>
  3184. * ```
  3185. */
  3186. getComputedStyle:function (element, styleName) {
  3187. //一下的属性单独处理
  3188. var pros = 'width height top left';
  3189. if(pros.indexOf(styleName) > -1){
  3190. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3191. }
  3192. //忽略文本节点
  3193. if (element.nodeType == 3) {
  3194. element = element.parentNode;
  3195. }
  3196. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3197. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3198. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3199. var span = element.ownerDocument.createElement('span');
  3200. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3201. span.innerHTML = '.';
  3202. element.appendChild(span);
  3203. var result = span.offsetHeight;
  3204. element.removeChild(span);
  3205. span = null;
  3206. return result + 'px';
  3207. }
  3208. try {
  3209. var value = domUtils.getStyle(element, styleName) ||
  3210. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3211. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3212. } catch (e) {
  3213. return "";
  3214. }
  3215. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3216. },
  3217. /**
  3218. * 删除元素element指定的className
  3219. * @method removeClasses
  3220. * @param { Element } ele 需要删除class的元素节点
  3221. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3222. * @example
  3223. * ```html
  3224. * <span id="test" class="test1 test2 test3">xxx</span>
  3225. *
  3226. * <script>
  3227. *
  3228. * var testNode = document.getElementById( "test" );
  3229. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3230. *
  3231. * //output: test3
  3232. * console.log( testNode.className );
  3233. *
  3234. * </script>
  3235. * ```
  3236. */
  3237. /**
  3238. * 删除元素element指定的className
  3239. * @method removeClasses
  3240. * @param { Element } ele 需要删除class的元素节点
  3241. * @param { Array } classNames 需要删除的className数组
  3242. * @example
  3243. * ```html
  3244. * <span id="test" class="test1 test2 test3">xxx</span>
  3245. *
  3246. * <script>
  3247. *
  3248. * var testNode = document.getElementById( "test" );
  3249. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3250. *
  3251. * //output: test3
  3252. * console.log( testNode.className );
  3253. *
  3254. * </script>
  3255. * ```
  3256. */
  3257. removeClasses:function (elm, classNames) {
  3258. classNames = utils.isArray(classNames) ? classNames :
  3259. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3260. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3261. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3262. }
  3263. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3264. if(cls){
  3265. elm.className = cls;
  3266. }else{
  3267. domUtils.removeAttributes(elm,['class']);
  3268. }
  3269. },
  3270. /**
  3271. * 给元素element添加className
  3272. * @method addClass
  3273. * @param { Node } ele 需要增加className的元素
  3274. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3275. * @remind 相同的类名不会被重复添加
  3276. * @example
  3277. * ```html
  3278. * <span id="test" class="cls1 cls2"></span>
  3279. *
  3280. * <script>
  3281. * var testNode = document.getElementById("test");
  3282. *
  3283. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3284. *
  3285. * //output: cl1 cls2 cls3 cls4
  3286. * console.log( testNode.className );
  3287. *
  3288. * <script>
  3289. * ```
  3290. */
  3291. /**
  3292. * 给元素element添加className
  3293. * @method addClass
  3294. * @param { Node } ele 需要增加className的元素
  3295. * @param { Array } classNames 需要添加的className的数组
  3296. * @remind 相同的类名不会被重复添加
  3297. * @example
  3298. * ```html
  3299. * <span id="test" class="cls1 cls2"></span>
  3300. *
  3301. * <script>
  3302. * var testNode = document.getElementById("test");
  3303. *
  3304. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3305. *
  3306. * //output: cl1 cls2 cls3 cls4
  3307. * console.log( testNode.className );
  3308. *
  3309. * <script>
  3310. * ```
  3311. */
  3312. addClass:function (elm, classNames) {
  3313. if(!elm)return;
  3314. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3315. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3316. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3317. cls += ' ' + ci;
  3318. }
  3319. }
  3320. elm.className = utils.trim(cls);
  3321. },
  3322. /**
  3323. * 判断元素element是否包含给定的样式类名className
  3324. * @method hasClass
  3325. * @param { Node } ele 需要检测的元素
  3326. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3327. * @return { Boolean } 元素是否包含所有给定的className
  3328. * @example
  3329. * ```html
  3330. * <span id="test1" class="cls1 cls2"></span>
  3331. *
  3332. * <script>
  3333. * var test1 = document.getElementById("test1");
  3334. *
  3335. * //output: false
  3336. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3337. *
  3338. * //output: true
  3339. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3340. * </script>
  3341. * ```
  3342. */
  3343. /**
  3344. * 判断元素element是否包含给定的样式类名className
  3345. * @method hasClass
  3346. * @param { Node } ele 需要检测的元素
  3347. * @param { Array } classNames 需要检测的className数组
  3348. * @return { Boolean } 元素是否包含所有给定的className
  3349. * @example
  3350. * ```html
  3351. * <span id="test1" class="cls1 cls2"></span>
  3352. *
  3353. * <script>
  3354. * var test1 = document.getElementById("test1");
  3355. *
  3356. * //output: false
  3357. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3358. *
  3359. * //output: true
  3360. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3361. * </script>
  3362. * ```
  3363. */
  3364. hasClass:function (element, className) {
  3365. if(utils.isRegExp(className)){
  3366. return className.test(element.className)
  3367. }
  3368. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3369. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3370. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3371. return false;
  3372. }
  3373. }
  3374. return i - 1 == className.length;
  3375. },
  3376. /**
  3377. * 阻止事件默认行为
  3378. * @method preventDefault
  3379. * @param { Event } evt 需要阻止默认行为的事件对象
  3380. * @example
  3381. * ```javascript
  3382. * UE.dom.domUtils.preventDefault( evt );
  3383. * ```
  3384. */
  3385. preventDefault:function (evt) {
  3386. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3387. },
  3388. /**
  3389. * 删除元素element指定的样式
  3390. * @method removeStyle
  3391. * @param { Element } element 需要删除样式的元素
  3392. * @param { String } styleName 需要删除的样式名
  3393. * @example
  3394. * ```html
  3395. * <span id="test" style="color: red; background: blue;"></span>
  3396. *
  3397. * <script>
  3398. *
  3399. * var testNode = document.getElementById("test");
  3400. *
  3401. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3402. *
  3403. * //output: background: blue;
  3404. * console.log( testNode.style.cssText );
  3405. *
  3406. * </script>
  3407. * ```
  3408. */
  3409. removeStyle:function (element, name) {
  3410. if(browser.ie ){
  3411. //针对color先单独处理一下
  3412. if(name == 'color'){
  3413. name = '(^|;)' + name;
  3414. }
  3415. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3416. }else{
  3417. if (element.style.removeProperty) {
  3418. element.style.removeProperty (name);
  3419. }else {
  3420. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3421. }
  3422. }
  3423. if (!element.style.cssText) {
  3424. domUtils.removeAttributes(element, ['style']);
  3425. }
  3426. },
  3427. /**
  3428. * 获取元素element的style属性的指定值
  3429. * @method getStyle
  3430. * @param { Element } element 需要获取属性值的元素
  3431. * @param { String } styleName 需要获取的style的名称
  3432. * @warning 该方法仅获取元素style属性中所标明的值
  3433. * @return { String } 该元素包含指定的style属性值
  3434. * @example
  3435. * ```html
  3436. * <div id="test" style="color: red;"></div>
  3437. *
  3438. * <script>
  3439. *
  3440. * var testNode = document.getElementById( "test" );
  3441. *
  3442. * //output: red
  3443. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3444. *
  3445. * //output: ""
  3446. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3447. *
  3448. * </script>
  3449. * ```
  3450. */
  3451. getStyle:function (element, name) {
  3452. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3453. return utils.fixColor(name, value);
  3454. },
  3455. /**
  3456. * 为元素element设置样式属性值
  3457. * @method setStyle
  3458. * @param { Element } element 需要设置样式的元素
  3459. * @param { String } styleName 样式名
  3460. * @param { String } styleValue 样式值
  3461. * @example
  3462. * ```html
  3463. * <div id="test"></div>
  3464. *
  3465. * <script>
  3466. *
  3467. * var testNode = document.getElementById( "test" );
  3468. *
  3469. * //output: ""
  3470. * console.log( testNode.style.color );
  3471. *
  3472. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3473. * //output: "red"
  3474. * console.log( testNode.style.color );
  3475. *
  3476. * </script>
  3477. * ```
  3478. */
  3479. setStyle:function (element, name, value) {
  3480. element.style[utils.cssStyleToDomStyle(name)] = value;
  3481. if(!utils.trim(element.style.cssText)){
  3482. this.removeAttributes(element,'style')
  3483. }
  3484. },
  3485. /**
  3486. * 为元素element设置多个样式属性值
  3487. * @method setStyles
  3488. * @param { Element } element 需要设置样式的元素
  3489. * @param { Object } styles 样式名值对
  3490. * @example
  3491. * ```html
  3492. * <div id="test"></div>
  3493. *
  3494. * <script>
  3495. *
  3496. * var testNode = document.getElementById( "test" );
  3497. *
  3498. * //output: ""
  3499. * console.log( testNode.style.color );
  3500. *
  3501. * UE.dom.domUtils.setStyles( testNode, {
  3502. * 'color': 'red'
  3503. * } );
  3504. * //output: "red"
  3505. * console.log( testNode.style.color );
  3506. *
  3507. * </script>
  3508. * ```
  3509. */
  3510. setStyles:function (element, styles) {
  3511. for (var name in styles) {
  3512. if (styles.hasOwnProperty(name)) {
  3513. domUtils.setStyle(element, name, styles[name]);
  3514. }
  3515. }
  3516. },
  3517. /**
  3518. * 删除_moz_dirty属性
  3519. * @private
  3520. * @method removeDirtyAttr
  3521. */
  3522. removeDirtyAttr:function (node) {
  3523. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3524. ci.removeAttribute('_moz_dirty');
  3525. }
  3526. node.removeAttribute('_moz_dirty');
  3527. },
  3528. /**
  3529. * 获取子节点的数量
  3530. * @method getChildCount
  3531. * @param { Element } node 需要检测的元素
  3532. * @return { Number } 给定的node元素的子节点数量
  3533. * @example
  3534. * ```html
  3535. * <div id="test">
  3536. * <span></span>
  3537. * </div>
  3538. *
  3539. * <script>
  3540. *
  3541. * //output: 3
  3542. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3543. *
  3544. * </script>
  3545. * ```
  3546. */
  3547. /**
  3548. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3549. * @method getChildCount
  3550. * @param { Element } node 需要检测的元素
  3551. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3552. * @return { Number } 符合过滤条件的node元素的子节点数量
  3553. * @example
  3554. * ```html
  3555. * <div id="test">
  3556. * <span></span>
  3557. * </div>
  3558. *
  3559. * <script>
  3560. *
  3561. * //output: 1
  3562. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3563. *
  3564. * return node.nodeType === 1;
  3565. *
  3566. * } ) );
  3567. *
  3568. * </script>
  3569. * ```
  3570. */
  3571. getChildCount:function (node, fn) {
  3572. var count = 0, first = node.firstChild;
  3573. fn = fn || function () {
  3574. return 1;
  3575. };
  3576. while (first) {
  3577. if (fn(first)) {
  3578. count++;
  3579. }
  3580. first = first.nextSibling;
  3581. }
  3582. return count;
  3583. },
  3584. /**
  3585. * 判断给定节点是否为空节点
  3586. * @method isEmptyNode
  3587. * @param { Node } node 需要检测的节点对象
  3588. * @return { Boolean } 节点是否为空
  3589. * @example
  3590. * ```javascript
  3591. * UE.dom.domUtils.isEmptyNode( document.body );
  3592. * ```
  3593. */
  3594. isEmptyNode:function (node) {
  3595. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3596. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3597. }) == 0
  3598. },
  3599. clearSelectedArr:function (nodes) {
  3600. var node;
  3601. while (node = nodes.pop()) {
  3602. domUtils.removeAttributes(node, ['class']);
  3603. }
  3604. },
  3605. /**
  3606. * 将显示区域滚动到指定节点的位置
  3607. * @method scrollToView
  3608. * @param {Node} node 节点
  3609. * @param {window} win window对象
  3610. * @param {Number} offsetTop 距离上方的偏移量
  3611. */
  3612. scrollToView:function (node, win, offsetTop) {
  3613. var getViewPaneSize = function () {
  3614. var doc = win.document,
  3615. mode = doc.compatMode == 'CSS1Compat';
  3616. return {
  3617. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3618. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3619. };
  3620. },
  3621. getScrollPosition = function (win) {
  3622. if ('pageXOffset' in win) {
  3623. return {
  3624. x:win.pageXOffset || 0,
  3625. y:win.pageYOffset || 0
  3626. };
  3627. }
  3628. else {
  3629. var doc = win.document;
  3630. return {
  3631. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3632. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3633. };
  3634. }
  3635. };
  3636. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3637. offset += (node.offsetHeight || 0);
  3638. var elementPosition = domUtils.getXY(node);
  3639. offset += elementPosition.y;
  3640. var currentScroll = getScrollPosition(win).y;
  3641. // offset += 50;
  3642. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3643. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3644. }
  3645. },
  3646. /**
  3647. * 判断给定节点是否为br
  3648. * @method isBr
  3649. * @param { Node } node 需要判断的节点对象
  3650. * @return { Boolean } 给定的节点是否是br节点
  3651. */
  3652. isBr:function (node) {
  3653. return node.nodeType == 1 && node.tagName == 'BR';
  3654. },
  3655. /**
  3656. * 判断给定的节点是否是一个“填充”节点
  3657. * @private
  3658. * @method isFillChar
  3659. * @param { Node } node 需要判断的节点
  3660. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3661. * @returns { Boolean } 节点是否是填充节点
  3662. */
  3663. isFillChar:function (node,isInStart) {
  3664. if(node.nodeType != 3)
  3665. return false;
  3666. var text = node.nodeValue;
  3667. if(isInStart){
  3668. return new RegExp('^' + domUtils.fillChar).test(text)
  3669. }
  3670. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3671. },
  3672. isStartInblock:function (range) {
  3673. var tmpRange = range.cloneRange(),
  3674. flag = 0,
  3675. start = tmpRange.startContainer,
  3676. tmp;
  3677. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3678. start = start.childNodes[tmpRange.startOffset];
  3679. var pre = start.previousSibling;
  3680. while(pre && domUtils.isFillChar(pre)){
  3681. start = pre;
  3682. pre = pre.previousSibling;
  3683. }
  3684. }
  3685. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3686. tmpRange.setStartBefore(start);
  3687. start = tmpRange.startContainer;
  3688. }
  3689. while (start && domUtils.isFillChar(start)) {
  3690. tmp = start;
  3691. start = start.previousSibling
  3692. }
  3693. if (tmp) {
  3694. tmpRange.setStartBefore(tmp);
  3695. start = tmpRange.startContainer;
  3696. }
  3697. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3698. tmpRange.setStart(start, 0).collapse(true);
  3699. }
  3700. while (!tmpRange.startOffset) {
  3701. start = tmpRange.startContainer;
  3702. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3703. flag = 1;
  3704. break;
  3705. }
  3706. var pre = tmpRange.startContainer.previousSibling,
  3707. tmpNode;
  3708. if (!pre) {
  3709. tmpRange.setStartBefore(tmpRange.startContainer);
  3710. } else {
  3711. while (pre && domUtils.isFillChar(pre)) {
  3712. tmpNode = pre;
  3713. pre = pre.previousSibling;
  3714. }
  3715. if (tmpNode) {
  3716. tmpRange.setStartBefore(tmpNode);
  3717. } else {
  3718. tmpRange.setStartBefore(tmpRange.startContainer);
  3719. }
  3720. }
  3721. }
  3722. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3723. },
  3724. /**
  3725. * 判断给定的元素是否是一个空元素
  3726. * @method isEmptyBlock
  3727. * @param { Element } node 需要判断的元素
  3728. * @return { Boolean } 是否是空元素
  3729. * @example
  3730. * ```html
  3731. * <div id="test"></div>
  3732. *
  3733. * <script>
  3734. * //output: true
  3735. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3736. * </script>
  3737. * ```
  3738. */
  3739. /**
  3740. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3741. * @method isEmptyBlock
  3742. * @param { Element } node 需要判断的元素
  3743. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3744. * @return { Boolean } 是否是空元素
  3745. */
  3746. isEmptyBlock:function (node,reg) {
  3747. // HaoChuan9421
  3748. if(!node){
  3749. return;
  3750. }
  3751. if(node.nodeType != 1)
  3752. return 0;
  3753. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3754. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3755. return 0;
  3756. }
  3757. for (var n in dtd.$isNotEmpty) {
  3758. if (node.getElementsByTagName(n).length) {
  3759. return 0;
  3760. }
  3761. }
  3762. return 1;
  3763. },
  3764. /**
  3765. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3766. * @method setViewportOffset
  3767. * @param { Element } element 需要设置偏移量的元素
  3768. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3769. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3770. * offset.top的距离
  3771. * @example
  3772. * ```html
  3773. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3774. *
  3775. * <script>
  3776. *
  3777. * var testNode = document.getElementById("test");
  3778. *
  3779. * UE.dom.domUtils.setViewportOffset( testNode, {
  3780. * left: 200,
  3781. * top: 50
  3782. * } );
  3783. *
  3784. * //output: top: 300px; left: 100px; position: absolute;
  3785. * console.log( testNode.style.cssText );
  3786. *
  3787. * </script>
  3788. * ```
  3789. */
  3790. setViewportOffset:function (element, offset) {
  3791. var left = parseInt(element.style.left) | 0;
  3792. var top = parseInt(element.style.top) | 0;
  3793. var rect = element.getBoundingClientRect();
  3794. var offsetLeft = offset.left - rect.left;
  3795. var offsetTop = offset.top - rect.top;
  3796. if (offsetLeft) {
  3797. element.style.left = left + offsetLeft + 'px';
  3798. }
  3799. if (offsetTop) {
  3800. element.style.top = top + offsetTop + 'px';
  3801. }
  3802. },
  3803. /**
  3804. * 用“填充字符”填充节点
  3805. * @method fillNode
  3806. * @private
  3807. * @param { DomDocument } doc 填充的节点所在的docment对象
  3808. * @param { Node } node 需要填充的节点对象
  3809. * @example
  3810. * ```html
  3811. * <div id="test"></div>
  3812. *
  3813. * <script>
  3814. * var testNode = document.getElementById("test");
  3815. *
  3816. * //output: 0
  3817. * console.log( testNode.childNodes.length );
  3818. *
  3819. * UE.dom.domUtils.fillNode( document, testNode );
  3820. *
  3821. * //output: 1
  3822. * console.log( testNode.childNodes.length );
  3823. *
  3824. * </script>
  3825. * ```
  3826. */
  3827. fillNode:function (doc, node) {
  3828. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3829. node.innerHTML = '';
  3830. node.appendChild(tmpNode);
  3831. },
  3832. /**
  3833. * 把节点src的所有子节点追加到另一个节点tag上去
  3834. * @method moveChild
  3835. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3836. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3837. * @example
  3838. * ```html
  3839. * <div id="test1">
  3840. * <span></span>
  3841. * </div>
  3842. * <div id="test2">
  3843. * <div></div>
  3844. * </div>
  3845. *
  3846. * <script>
  3847. *
  3848. * var test1 = document.getElementById("test1"),
  3849. * test2 = document.getElementById("test2");
  3850. *
  3851. * UE.dom.domUtils.moveChild( test1, test2 );
  3852. *
  3853. * //output: ""(空字符串)
  3854. * console.log( test1.innerHTML );
  3855. *
  3856. * //output: "<div></div><span></span>"
  3857. * console.log( test2.innerHTML );
  3858. *
  3859. * </script>
  3860. * ```
  3861. */
  3862. /**
  3863. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3864. * @method moveChild
  3865. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3866. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3867. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3868. * @example
  3869. * ```html
  3870. * <div id="test1">
  3871. * <span></span>
  3872. * </div>
  3873. * <div id="test2">
  3874. * <div></div>
  3875. * </div>
  3876. *
  3877. * <script>
  3878. *
  3879. * var test1 = document.getElementById("test1"),
  3880. * test2 = document.getElementById("test2");
  3881. *
  3882. * UE.dom.domUtils.moveChild( test1, test2, true );
  3883. *
  3884. * //output: ""(空字符串)
  3885. * console.log( test1.innerHTML );
  3886. *
  3887. * //output: "<span></span><div></div>"
  3888. * console.log( test2.innerHTML );
  3889. *
  3890. * </script>
  3891. * ```
  3892. */
  3893. moveChild:function (src, tag, dir) {
  3894. while (src.firstChild) {
  3895. if (dir && tag.firstChild) {
  3896. tag.insertBefore(src.lastChild, tag.firstChild);
  3897. } else {
  3898. tag.appendChild(src.firstChild);
  3899. }
  3900. }
  3901. },
  3902. /**
  3903. * 判断节点的标签上是否不存在任何属性
  3904. * @method hasNoAttributes
  3905. * @private
  3906. * @param { Node } node 需要检测的节点对象
  3907. * @return { Boolean } 节点是否不包含任何属性
  3908. * @example
  3909. * ```html
  3910. * <div id="test"><span>xxxx</span></div>
  3911. *
  3912. * <script>
  3913. *
  3914. * //output: false
  3915. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3916. *
  3917. * //output: true
  3918. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3919. *
  3920. * </script>
  3921. * ```
  3922. */
  3923. hasNoAttributes:function (node) {
  3924. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3925. },
  3926. /**
  3927. * 检测节点是否是UEditor所使用的辅助节点
  3928. * @method isCustomeNode
  3929. * @private
  3930. * @param { Node } node 需要检测的节点
  3931. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3932. * @return { Boolean } 给定的节点是否是一个辅助节点
  3933. */
  3934. isCustomeNode:function (node) {
  3935. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3936. },
  3937. /**
  3938. * 检测节点的标签是否是给定的标签
  3939. * @method isTagNode
  3940. * @param { Node } node 需要检测的节点对象
  3941. * @param { String } tagName 标签
  3942. * @return { Boolean } 节点的标签是否是给定的标签
  3943. * @example
  3944. * ```html
  3945. * <div id="test"></div>
  3946. *
  3947. * <script>
  3948. *
  3949. * //output: true
  3950. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3951. *
  3952. * </script>
  3953. * ```
  3954. */
  3955. isTagNode:function (node, tagNames) {
  3956. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3957. },
  3958. /**
  3959. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3960. * @method filterNodeList
  3961. * @param { Array } nodeList 需要过滤的节点数组
  3962. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3963. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3964. * @example
  3965. * ```javascript
  3966. * var divNodes = document.getElementsByTagName("div");
  3967. * divNodes = [].slice.call( divNodes, 0 );
  3968. *
  3969. * //output: null
  3970. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3971. * return node.tagName.toLowerCase() !== 'div';
  3972. * } ) );
  3973. * ```
  3974. */
  3975. /**
  3976. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3977. * @method filterNodeList
  3978. * @param { Array } nodeList 需要过滤的节点数组
  3979. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3980. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3981. * @example
  3982. * ```javascript
  3983. * var divNodes = document.getElementsByTagName("div");
  3984. * divNodes = [].slice.call( divNodes, 0 );
  3985. *
  3986. * //output: null
  3987. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3988. * ```
  3989. */
  3990. /**
  3991. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3992. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3993. * @method filterNodeList
  3994. * @param { Array } nodeList 需要过滤的节点数组
  3995. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3996. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3997. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3998. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3999. * @example
  4000. * ```javascript
  4001. * var divNodes = document.getElementsByTagName("div");
  4002. * divNodes = [].slice.call( divNodes, 0 );
  4003. *
  4004. * //output: 3(假定有3个div)
  4005. * console.log( divNodes.length );
  4006. *
  4007. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4008. * return node.tagName.toLowerCase() === 'div';
  4009. * }, true );
  4010. *
  4011. * //output: 3
  4012. * console.log( nodes.length );
  4013. *
  4014. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4015. * return node.tagName.toLowerCase() === 'div';
  4016. * }, false );
  4017. *
  4018. * //output: div
  4019. * console.log( node.nodeName );
  4020. * ```
  4021. */
  4022. filterNodeList : function(nodelist,filter,forAll){
  4023. var results = [];
  4024. if(!utils .isFunction(filter)){
  4025. var str = filter;
  4026. filter = function(n){
  4027. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4028. };
  4029. }
  4030. utils.each(nodelist,function(n){
  4031. filter(n) && results.push(n)
  4032. });
  4033. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4034. },
  4035. /**
  4036. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4037. * @method isInNodeEndBoundary
  4038. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4039. * @param node 需要检测的节点对象
  4040. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4041. */
  4042. isInNodeEndBoundary : function (rng,node){
  4043. var start = rng.startContainer;
  4044. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4045. return 0;
  4046. }
  4047. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4048. return 0;
  4049. }
  4050. while(start !== node){
  4051. if(start.nextSibling){
  4052. return 0
  4053. };
  4054. start = start.parentNode;
  4055. }
  4056. return 1;
  4057. },
  4058. isBoundaryNode : function (node,dir){
  4059. var tmp;
  4060. while(!domUtils.isBody(node)){
  4061. tmp = node;
  4062. node = node.parentNode;
  4063. if(tmp !== node[dir]){
  4064. return false;
  4065. }
  4066. }
  4067. return true;
  4068. },
  4069. fillHtml : browser.ie11below ? '&nbsp;' : '<br/>'
  4070. };
  4071. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4072. // core/Range.js
  4073. /**
  4074. * Range封装
  4075. * @file
  4076. * @module UE.dom
  4077. * @class Range
  4078. * @since 1.2.6.1
  4079. */
  4080. /**
  4081. * dom操作封装
  4082. * @unfile
  4083. * @module UE.dom
  4084. */
  4085. /**
  4086. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4087. * @unfile
  4088. * @module UE.dom
  4089. * @class Range
  4090. */
  4091. (function () {
  4092. var guid = 0,
  4093. fillChar = domUtils.fillChar,
  4094. fillData;
  4095. /**
  4096. * 更新range的collapse状态
  4097. * @param {Range} range range对象
  4098. */
  4099. function updateCollapse(range) {
  4100. range.collapsed =
  4101. range.startContainer && range.endContainer &&
  4102. range.startContainer === range.endContainer &&
  4103. range.startOffset == range.endOffset;
  4104. }
  4105. function selectOneNode(rng){
  4106. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4107. }
  4108. function setEndPoint(toStart, node, offset, range) {
  4109. //如果node是自闭合标签要处理
  4110. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4111. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4112. node = node.parentNode;
  4113. }
  4114. if (toStart) {
  4115. range.startContainer = node;
  4116. range.startOffset = offset;
  4117. if (!range.endContainer) {
  4118. range.collapse(true);
  4119. }
  4120. } else {
  4121. range.endContainer = node;
  4122. range.endOffset = offset;
  4123. if (!range.startContainer) {
  4124. range.collapse(false);
  4125. }
  4126. }
  4127. updateCollapse(range);
  4128. return range;
  4129. }
  4130. function execContentsAction(range, action) {
  4131. //调整边界
  4132. //range.includeBookmark();
  4133. var start = range.startContainer,
  4134. end = range.endContainer,
  4135. startOffset = range.startOffset,
  4136. endOffset = range.endOffset,
  4137. doc = range.document,
  4138. frag = doc.createDocumentFragment(),
  4139. tmpStart, tmpEnd;
  4140. if (start.nodeType == 1) {
  4141. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4142. }
  4143. if (end.nodeType == 1) {
  4144. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4145. }
  4146. if (start === end && start.nodeType == 3) {
  4147. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4148. //is not clone
  4149. if (action) {
  4150. start.deleteData(startOffset, endOffset - startOffset);
  4151. range.collapse(true);
  4152. }
  4153. return frag;
  4154. }
  4155. var current, currentLevel, clone = frag,
  4156. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4157. for (var i = 0; startParents[i] == endParents[i];) {
  4158. i++;
  4159. }
  4160. for (var j = i, si; si = startParents[j]; j++) {
  4161. current = si.nextSibling;
  4162. if (si == start) {
  4163. if (!tmpStart) {
  4164. if (range.startContainer.nodeType == 3) {
  4165. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4166. //is not clone
  4167. if (action) {
  4168. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4169. }
  4170. } else {
  4171. clone.appendChild(!action ? start.cloneNode(true) : start);
  4172. }
  4173. }
  4174. } else {
  4175. currentLevel = si.cloneNode(false);
  4176. clone.appendChild(currentLevel);
  4177. }
  4178. while (current) {
  4179. if (current === end || current === endParents[j]) {
  4180. break;
  4181. }
  4182. si = current.nextSibling;
  4183. clone.appendChild(!action ? current.cloneNode(true) : current);
  4184. current = si;
  4185. }
  4186. clone = currentLevel;
  4187. }
  4188. clone = frag;
  4189. if (!startParents[i]) {
  4190. clone.appendChild(startParents[i - 1].cloneNode(false));
  4191. clone = clone.firstChild;
  4192. }
  4193. for (var j = i, ei; ei = endParents[j]; j++) {
  4194. current = ei.previousSibling;
  4195. if (ei == end) {
  4196. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4197. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4198. //is not clone
  4199. if (action) {
  4200. end.deleteData(0, endOffset);
  4201. }
  4202. }
  4203. } else {
  4204. currentLevel = ei.cloneNode(false);
  4205. clone.appendChild(currentLevel);
  4206. }
  4207. //如果两端同级,右边第一次已经被开始做了
  4208. if (j != i || !startParents[i]) {
  4209. while (current) {
  4210. if (current === start) {
  4211. break;
  4212. }
  4213. ei = current.previousSibling;
  4214. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4215. current = ei;
  4216. }
  4217. }
  4218. clone = currentLevel;
  4219. }
  4220. if (action) {
  4221. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4222. }
  4223. tmpStart && domUtils.remove(tmpStart);
  4224. tmpEnd && domUtils.remove(tmpEnd);
  4225. return frag;
  4226. }
  4227. /**
  4228. * 创建一个跟document绑定的空的Range实例
  4229. * @constructor
  4230. * @param { Document } document 新建的选区所属的文档对象
  4231. */
  4232. /**
  4233. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4234. */
  4235. /**
  4236. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4237. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4238. */
  4239. /**
  4240. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4241. */
  4242. /**
  4243. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4244. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4245. */
  4246. /**
  4247. * @property { Boolean } collapsed 当前Range是否闭合
  4248. * @default true
  4249. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4250. */
  4251. /**
  4252. * @property { Document } document 当前Range所属的Document对象
  4253. * @remind 不同range的的document属性可以是不同的
  4254. */
  4255. var Range = dom.Range = function (document) {
  4256. var me = this;
  4257. me.startContainer =
  4258. me.startOffset =
  4259. me.endContainer =
  4260. me.endOffset = null;
  4261. me.document = document;
  4262. me.collapsed = true;
  4263. };
  4264. /**
  4265. * 删除fillData
  4266. * @param doc
  4267. * @param excludeNode
  4268. */
  4269. function removeFillData(doc, excludeNode) {
  4270. try {
  4271. if (fillData && domUtils.inDoc(fillData, doc)) {
  4272. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4273. var tmpNode = fillData.parentNode;
  4274. domUtils.remove(fillData);
  4275. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4276. //safari的contains有bug
  4277. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4278. ) {
  4279. fillData = tmpNode.parentNode;
  4280. domUtils.remove(tmpNode);
  4281. tmpNode = fillData;
  4282. }
  4283. } else {
  4284. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4285. }
  4286. }
  4287. } catch (e) {
  4288. }
  4289. }
  4290. /**
  4291. * @param node
  4292. * @param dir
  4293. */
  4294. function mergeSibling(node, dir) {
  4295. var tmpNode;
  4296. node = node[dir];
  4297. while (node && domUtils.isFillChar(node)) {
  4298. tmpNode = node[dir];
  4299. domUtils.remove(node);
  4300. node = tmpNode;
  4301. }
  4302. }
  4303. Range.prototype = {
  4304. /**
  4305. * 克隆选区的内容到一个DocumentFragment里
  4306. * @method cloneContents
  4307. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4308. * @example
  4309. * ```html
  4310. * <body>
  4311. * <!-- 中括号表示选区 -->
  4312. * <b>x<i>x[x</i>xx]x</b>
  4313. *
  4314. * <script>
  4315. * //range是已选中的选区
  4316. * var fragment = range.cloneContents(),
  4317. * node = document.createElement("div");
  4318. *
  4319. * node.appendChild( fragment );
  4320. *
  4321. * //output: <i>x</i>xx
  4322. * console.log( node.innerHTML );
  4323. *
  4324. * </script>
  4325. * </body>
  4326. * ```
  4327. */
  4328. cloneContents:function () {
  4329. return this.collapsed ? null : execContentsAction(this, 0);
  4330. },
  4331. /**
  4332. * 删除当前选区范围中的所有内容
  4333. * @method deleteContents
  4334. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4335. * @return { UE.dom.Range } 当前操作的Range对象
  4336. * @example
  4337. * ```html
  4338. * <body>
  4339. * <!-- 中括号表示选区 -->
  4340. * <b>x<i>x[x</i>xx]x</b>
  4341. *
  4342. * <script>
  4343. * //range是已选中的选区
  4344. * range.deleteContents();
  4345. *
  4346. * //竖线表示闭合后的选区位置
  4347. * //output: <b>x<i>x</i>|x</b>
  4348. * console.log( document.body.innerHTML );
  4349. *
  4350. * //此时, range的各项属性为
  4351. * //output: B
  4352. * console.log( range.startContainer.tagName );
  4353. * //output: 2
  4354. * console.log( range.startOffset );
  4355. * //output: B
  4356. * console.log( range.endContainer.tagName );
  4357. * //output: 2
  4358. * console.log( range.endOffset );
  4359. * //output: true
  4360. * console.log( range.collapsed );
  4361. *
  4362. * </script>
  4363. * </body>
  4364. * ```
  4365. */
  4366. deleteContents:function () {
  4367. var txt;
  4368. if (!this.collapsed) {
  4369. execContentsAction(this, 1);
  4370. }
  4371. if (browser.webkit) {
  4372. txt = this.startContainer;
  4373. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4374. this.setStartBefore(txt).collapse(true);
  4375. domUtils.remove(txt);
  4376. }
  4377. }
  4378. return this;
  4379. },
  4380. /**
  4381. * 将当前选区的内容提取到一个DocumentFragment里
  4382. * @method extractContents
  4383. * @remind 执行该操作后, 选区将变成闭合状态
  4384. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4385. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4386. * @example
  4387. * ```html
  4388. * <body>
  4389. * <!-- 中括号表示选区 -->
  4390. * <b>x<i>x[x</i>xx]x</b>
  4391. *
  4392. * <script>
  4393. * //range是已选中的选区
  4394. * var fragment = range.extractContents(),
  4395. * node = document.createElement( "div" );
  4396. *
  4397. * node.appendChild( fragment );
  4398. *
  4399. * //竖线表示闭合后的选区位置
  4400. *
  4401. * //output: <b>x<i>x</i>|x</b>
  4402. * console.log( document.body.innerHTML );
  4403. * //output: <i>x</i>xx
  4404. * console.log( node.innerHTML );
  4405. *
  4406. * //此时, range的各项属性为
  4407. * //output: B
  4408. * console.log( range.startContainer.tagName );
  4409. * //output: 2
  4410. * console.log( range.startOffset );
  4411. * //output: B
  4412. * console.log( range.endContainer.tagName );
  4413. * //output: 2
  4414. * console.log( range.endOffset );
  4415. * //output: true
  4416. * console.log( range.collapsed );
  4417. *
  4418. * </script>
  4419. * </body>
  4420. */
  4421. extractContents:function () {
  4422. return this.collapsed ? null : execContentsAction(this, 2);
  4423. },
  4424. /**
  4425. * 设置Range的开始容器节点和偏移量
  4426. * @method setStart
  4427. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4428. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4429. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4430. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4431. * 中的索引
  4432. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4433. * @param { int } offset 选区的开始位置偏移量
  4434. * @return { UE.dom.Range } 当前range对象
  4435. * @example
  4436. * ```html
  4437. * <!-- 选区 -->
  4438. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4439. *
  4440. * <script>
  4441. *
  4442. * //执行操作
  4443. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4444. *
  4445. * //此时, 选区变成了
  4446. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4447. *
  4448. * </script>
  4449. * ```
  4450. * @example
  4451. * ```html
  4452. * <!-- 选区 -->
  4453. * <b>xxx<img>[xx]x</b>
  4454. *
  4455. * <script>
  4456. *
  4457. * //执行操作
  4458. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4459. *
  4460. * //此时, 选区变成了
  4461. * //<b>xxx[<img>xx]x</b>
  4462. *
  4463. * </script>
  4464. * ```
  4465. */
  4466. setStart:function (node, offset) {
  4467. return setEndPoint(true, node, offset, this);
  4468. },
  4469. /**
  4470. * 设置Range的结束容器和偏移量
  4471. * @method setEnd
  4472. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4473. * @param { int } offset 结束边界的偏移量
  4474. * @see UE.dom.Range:setStart(Node,int)
  4475. * @return { UE.dom.Range } 当前range对象
  4476. */
  4477. setEnd:function (node, offset) {
  4478. return setEndPoint(false, node, offset, this);
  4479. },
  4480. /**
  4481. * 将Range开始位置设置到node节点之后
  4482. * @method setStartAfter
  4483. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4484. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4485. * @return { UE.dom.Range } 当前range对象
  4486. * @example
  4487. * ```html
  4488. * <!-- 选区示例 -->
  4489. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4490. *
  4491. * <script>
  4492. *
  4493. * //执行操作
  4494. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4495. *
  4496. * //结果选区
  4497. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4498. *
  4499. * </script>
  4500. * ```
  4501. */
  4502. setStartAfter:function (node) {
  4503. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4504. },
  4505. /**
  4506. * 将Range开始位置设置到node节点之前
  4507. * @method setStartBefore
  4508. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4509. * @param { Node } node 新的选区开始位置在该节点之前
  4510. * @see UE.dom.Range:setStartAfter(Node)
  4511. * @return { UE.dom.Range } 当前range对象
  4512. */
  4513. setStartBefore:function (node) {
  4514. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4515. },
  4516. /**
  4517. * 将Range结束位置设置到node节点之后
  4518. * @method setEndAfter
  4519. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4520. * @param { Node } node 目标节点
  4521. * @see UE.dom.Range:setStartAfter(Node)
  4522. * @return { UE.dom.Range } 当前range对象
  4523. * @example
  4524. * ```html
  4525. * <!-- 选区示例 -->
  4526. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4527. *
  4528. * <script>
  4529. *
  4530. * //执行操作
  4531. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4532. *
  4533. * //结果选区
  4534. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4535. *
  4536. * </script>
  4537. * ```
  4538. */
  4539. setEndAfter:function (node) {
  4540. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4541. },
  4542. /**
  4543. * 将Range结束位置设置到node节点之前
  4544. * @method setEndBefore
  4545. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4546. * @param { Node } node 目标节点
  4547. * @see UE.dom.Range:setEndAfter(Node)
  4548. * @return { UE.dom.Range } 当前range对象
  4549. */
  4550. setEndBefore:function (node) {
  4551. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4552. },
  4553. /**
  4554. * 设置Range的开始位置到node节点内的第一个子节点之前
  4555. * @method setStartAtFirst
  4556. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4557. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4558. * @param { Node } node 目标节点
  4559. * @see UE.dom.Range:setStartBefore(Node)
  4560. * @return { UE.dom.Range } 当前range对象
  4561. * @example
  4562. * ```html
  4563. * <!-- 选区示例 -->
  4564. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4565. *
  4566. * <script>
  4567. *
  4568. * //执行操作
  4569. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4570. *
  4571. * //结果选区
  4572. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4573. *
  4574. * </script>
  4575. * ```
  4576. */
  4577. setStartAtFirst:function (node) {
  4578. return this.setStart(node, 0);
  4579. },
  4580. /**
  4581. * 设置Range的开始位置到node节点内的最后一个节点之后
  4582. * @method setStartAtLast
  4583. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4584. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4585. * @param { Node } node 目标节点
  4586. * @see UE.dom.Range:setStartAtFirst(Node)
  4587. * @return { UE.dom.Range } 当前range对象
  4588. */
  4589. setStartAtLast:function (node) {
  4590. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4591. },
  4592. /**
  4593. * 设置Range的结束位置到node节点内的第一个节点之前
  4594. * @method setEndAtFirst
  4595. * @param { Node } node 目标节点
  4596. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4597. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4598. * @see UE.dom.Range:setStartAtFirst(Node)
  4599. * @return { UE.dom.Range } 当前range对象
  4600. */
  4601. setEndAtFirst:function (node) {
  4602. return this.setEnd(node, 0);
  4603. },
  4604. /**
  4605. * 设置Range的结束位置到node节点内的最后一个节点之后
  4606. * @method setEndAtLast
  4607. * @param { Node } node 目标节点
  4608. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4609. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4610. * @see UE.dom.Range:setStartAtFirst(Node)
  4611. * @return { UE.dom.Range } 当前range对象
  4612. */
  4613. setEndAtLast:function (node) {
  4614. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4615. },
  4616. /**
  4617. * 选中给定节点
  4618. * @method selectNode
  4619. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4620. * 而endOffset为startOffset+1
  4621. * @param { Node } node 需要选中的节点
  4622. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4623. * @example
  4624. * ```html
  4625. * <!-- 选区示例 -->
  4626. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4627. *
  4628. * <script>
  4629. *
  4630. * //执行操作
  4631. * range.selectNode( document.getElementsByTagName("i")[0] );
  4632. *
  4633. * //结果选区
  4634. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4635. *
  4636. * </script>
  4637. * ```
  4638. */
  4639. selectNode:function (node) {
  4640. return this.setStartBefore(node).setEndAfter(node);
  4641. },
  4642. /**
  4643. * 选中给定节点内部的所有节点
  4644. * @method selectNodeContents
  4645. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4646. * 而endOffset是该节点的子节点数。
  4647. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4648. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4649. * @example
  4650. * ```html
  4651. * <!-- 选区示例 -->
  4652. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4653. *
  4654. * <script>
  4655. *
  4656. * //执行操作
  4657. * range.selectNode( document.getElementsByTagName("b")[0] );
  4658. *
  4659. * //结果选区
  4660. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4661. *
  4662. * </script>
  4663. * ```
  4664. */
  4665. selectNodeContents:function (node) {
  4666. return this.setStart(node, 0).setEndAtLast(node);
  4667. },
  4668. /**
  4669. * clone当前Range对象
  4670. * @method cloneRange
  4671. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4672. * @return { UE.dom.Range } 当前range对象的一个副本
  4673. */
  4674. cloneRange:function () {
  4675. var me = this;
  4676. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4677. },
  4678. /**
  4679. * 向当前选区的结束处闭合选区
  4680. * @method collapse
  4681. * @return { UE.dom.Range } 当前range对象
  4682. * @example
  4683. * ```html
  4684. * <!-- 选区示例 -->
  4685. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4686. *
  4687. * <script>
  4688. *
  4689. * //执行操作
  4690. * range.collapse();
  4691. *
  4692. * //结果选区
  4693. * //“|”表示选区已闭合
  4694. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4695. *
  4696. * </script>
  4697. * ```
  4698. */
  4699. /**
  4700. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4701. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4702. * @method collapse
  4703. * @param { Boolean } toStart 是否向选区开始处闭合
  4704. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4705. * @see UE.dom.Range:collapse()
  4706. * @example
  4707. * ```html
  4708. * <!-- 选区示例 -->
  4709. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4710. *
  4711. * <script>
  4712. *
  4713. * //执行操作
  4714. * range.collapse( true );
  4715. *
  4716. * //结果选区
  4717. * //“|”表示选区已闭合
  4718. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4719. *
  4720. * </script>
  4721. * ```
  4722. */
  4723. collapse:function (toStart) {
  4724. var me = this;
  4725. if (toStart) {
  4726. me.endContainer = me.startContainer;
  4727. me.endOffset = me.startOffset;
  4728. } else {
  4729. me.startContainer = me.endContainer;
  4730. me.startOffset = me.endOffset;
  4731. }
  4732. me.collapsed = true;
  4733. return me;
  4734. },
  4735. /**
  4736. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4737. * @method shrinkBoundary
  4738. * @return { UE.dom.Range } 当前range对象
  4739. * @example
  4740. * ```html
  4741. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4742. * ```
  4743. *
  4744. * @example
  4745. * ```html
  4746. * <!-- 选区示例 -->
  4747. * <b>x[xx</b><i>]xxx</i>
  4748. *
  4749. * <script>
  4750. *
  4751. * //执行收缩
  4752. * range.shrinkBoundary();
  4753. *
  4754. * //结果选区
  4755. * //<b>x[xx]</b><i>xxx</i>
  4756. * </script>
  4757. * ```
  4758. *
  4759. * @example
  4760. * ```html
  4761. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4762. * ```
  4763. */
  4764. /**
  4765. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4766. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4767. * @method shrinkBoundary
  4768. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4769. * @return { UE.dom.Range } 当前range对象
  4770. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4771. */
  4772. shrinkBoundary:function (ignoreEnd) {
  4773. var me = this, child,
  4774. collapsed = me.collapsed;
  4775. function check(node){
  4776. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4777. }
  4778. while (me.startContainer.nodeType == 1 //是element
  4779. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4780. && check(child)) {
  4781. me.setStart(child, 0);
  4782. }
  4783. if (collapsed) {
  4784. return me.collapse(true);
  4785. }
  4786. if (!ignoreEnd) {
  4787. while (me.endContainer.nodeType == 1//是element
  4788. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4789. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4790. && check(child)) {
  4791. me.setEnd(child, child.childNodes.length);
  4792. }
  4793. }
  4794. return me;
  4795. },
  4796. /**
  4797. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4798. * @method getCommonAncestor
  4799. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4800. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4801. * @example
  4802. * ```html
  4803. * //选区示例
  4804. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4805. * <script>
  4806. *
  4807. * var node = range.getCommonAncestor();
  4808. *
  4809. * //公共祖先节点是: b节点
  4810. * //输出: B
  4811. * console.log(node.tagName);
  4812. *
  4813. * </script>
  4814. * ```
  4815. */
  4816. /**
  4817. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4818. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4819. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4820. * @method getCommonAncestor
  4821. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4822. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4823. * @see UE.dom.Range:getCommonAncestor()
  4824. * @example
  4825. * ```html
  4826. * <body>
  4827. *
  4828. * <!-- 选区示例 -->
  4829. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4830. *
  4831. * <script>
  4832. *
  4833. * var node = range.getCommonAncestor( false );
  4834. *
  4835. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4836. * //output: B
  4837. * console.log( node.tagName );
  4838. *
  4839. * </script>
  4840. *
  4841. * </body>
  4842. * ```
  4843. */
  4844. /**
  4845. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4846. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4847. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4848. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4849. * @method getCommonAncestor
  4850. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4851. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4852. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4853. * @see UE.dom.Range:getCommonAncestor()
  4854. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4855. * @example
  4856. * ```html
  4857. * <body>
  4858. *
  4859. * <!-- 选区示例 -->
  4860. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4861. *
  4862. * <script>
  4863. *
  4864. * var node = range.getCommonAncestor( true, false );
  4865. *
  4866. * //output: SPAN
  4867. * console.log( node.tagName );
  4868. *
  4869. * </script>
  4870. *
  4871. * </body>
  4872. * ```
  4873. */
  4874. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4875. var me = this,
  4876. start = me.startContainer,
  4877. end = me.endContainer;
  4878. if (start === end) {
  4879. if (includeSelf && selectOneNode(this)) {
  4880. start = start.childNodes[me.startOffset];
  4881. if(start.nodeType == 1)
  4882. return start;
  4883. }
  4884. //只有在上来就相等的情况下才会出现是文本的情况
  4885. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4886. }
  4887. return domUtils.getCommonAncestor(start, end);
  4888. },
  4889. /**
  4890. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4891. * @method trimBoundary
  4892. * @remind 该操作有可能会引起文本节点被切开
  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();
  4904. *
  4905. * //调整之后, 容器节点变成了i节点
  4906. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4907. * </script>
  4908. * ```
  4909. */
  4910. /**
  4911. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4912. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4913. * @method trimBoundary
  4914. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4915. * @return { UE.dom.Range } 当前range对象
  4916. * @example
  4917. * ```html
  4918. *
  4919. * //选区示例
  4920. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4921. *
  4922. * <script>
  4923. * //未调整前, 选区的开始容器和结束都是文本节点
  4924. * //执行调整
  4925. * range.trimBoundary( true );
  4926. *
  4927. * //调整之后, 开始容器节点变成了i节点
  4928. * //但是, 结束容器没有发生变化
  4929. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4930. * </script>
  4931. * ```
  4932. */
  4933. trimBoundary:function (ignoreEnd) {
  4934. this.txtToElmBoundary();
  4935. var start = this.startContainer,
  4936. offset = this.startOffset,
  4937. collapsed = this.collapsed,
  4938. end = this.endContainer;
  4939. if (start.nodeType == 3) {
  4940. if (offset == 0) {
  4941. this.setStartBefore(start);
  4942. } else {
  4943. if (offset >= start.nodeValue.length) {
  4944. this.setStartAfter(start);
  4945. } else {
  4946. var textNode = domUtils.split(start, offset);
  4947. //跟新结束边界
  4948. if (start === end) {
  4949. this.setEnd(textNode, this.endOffset - offset);
  4950. } else if (start.parentNode === end) {
  4951. this.endOffset += 1;
  4952. }
  4953. this.setStartBefore(textNode);
  4954. }
  4955. }
  4956. if (collapsed) {
  4957. return this.collapse(true);
  4958. }
  4959. }
  4960. if (!ignoreEnd) {
  4961. offset = this.endOffset;
  4962. end = this.endContainer;
  4963. if (end.nodeType == 3) {
  4964. if (offset == 0) {
  4965. this.setEndBefore(end);
  4966. } else {
  4967. offset < end.nodeValue.length && domUtils.split(end, offset);
  4968. this.setEndAfter(end);
  4969. }
  4970. }
  4971. }
  4972. return this;
  4973. },
  4974. /**
  4975. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4976. * @method txtToElmBoundary
  4977. * @remind 该操作不会修改dom节点
  4978. * @return { UE.dom.Range } 当前range对象
  4979. */
  4980. /**
  4981. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4982. * ignoreCollapsed 的值决定是否执行该调整
  4983. * @method txtToElmBoundary
  4984. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4985. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4986. * @return { UE.dom.Range } 当前range对象
  4987. */
  4988. txtToElmBoundary:function (ignoreCollapsed) {
  4989. function adjust(r, c) {
  4990. var container = r[c + 'Container'],
  4991. offset = r[c + 'Offset'];
  4992. if (container.nodeType == 3) {
  4993. if (!offset) {
  4994. r['set' + c.replace(/(\w)/, function (a) {
  4995. return a.toUpperCase();
  4996. }) + 'Before'](container);
  4997. } else if (offset >= container.nodeValue.length) {
  4998. r['set' + c.replace(/(\w)/, function (a) {
  4999. return a.toUpperCase();
  5000. }) + 'After' ](container);
  5001. }
  5002. }
  5003. }
  5004. if (ignoreCollapsed || !this.collapsed) {
  5005. adjust(this, 'start');
  5006. adjust(this, 'end');
  5007. }
  5008. return this;
  5009. },
  5010. /**
  5011. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5012. * @method insertNode
  5013. * @param { Node } node 需要插入的节点
  5014. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5015. * @return { UE.dom.Range } 当前range对象
  5016. */
  5017. insertNode:function (node) {
  5018. var first = node, length = 1;
  5019. if (node.nodeType == 11) {
  5020. first = node.firstChild;
  5021. length = node.childNodes.length;
  5022. }
  5023. this.trimBoundary(true);
  5024. var start = this.startContainer,
  5025. offset = this.startOffset;
  5026. var nextNode = start.childNodes[ offset ];
  5027. if (nextNode) {
  5028. start.insertBefore(node, nextNode);
  5029. } else {
  5030. start.appendChild(node);
  5031. }
  5032. if (first.parentNode === this.endContainer) {
  5033. this.endOffset = this.endOffset + length;
  5034. }
  5035. return this.setStartBefore(first);
  5036. },
  5037. /**
  5038. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5039. * @method setCursor
  5040. * @return { UE.dom.Range } 当前range对象
  5041. * @see UE.dom.Range:collapse()
  5042. */
  5043. /**
  5044. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5045. * @method setCursor
  5046. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5047. * 反之,则向开始容器方向闭合
  5048. * @return { UE.dom.Range } 当前range对象
  5049. * @see UE.dom.Range:collapse(Boolean)
  5050. */
  5051. setCursor:function (toEnd, noFillData) {
  5052. return this.collapse(!toEnd).select(noFillData);
  5053. },
  5054. /**
  5055. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5056. * @method createBookmark
  5057. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5058. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5059. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5060. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5061. * 返回的记录的类型为ID, 反之则为引用
  5062. */
  5063. createBookmark:function (serialize, same) {
  5064. var endNode,
  5065. startNode = this.document.createElement('span');
  5066. startNode.style.cssText = 'display:none;line-height:0px;';
  5067. startNode.appendChild(this.document.createTextNode('\u200D'));
  5068. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5069. if (!this.collapsed) {
  5070. endNode = startNode.cloneNode(true);
  5071. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5072. }
  5073. this.insertNode(startNode);
  5074. if (endNode) {
  5075. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5076. }
  5077. this.setStartAfter(startNode);
  5078. return {
  5079. start:serialize ? startNode.id : startNode,
  5080. end:endNode ? serialize ? endNode.id : endNode : null,
  5081. id:serialize
  5082. }
  5083. },
  5084. /**
  5085. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5086. * @method moveToBookmark
  5087. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5088. * @return { UE.dom.Range } 当前range对象
  5089. * @see UE.dom.Range:createBookmark(Boolean)
  5090. */
  5091. moveToBookmark:function (bookmark) {
  5092. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5093. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5094. this.setStartBefore(start);
  5095. domUtils.remove(start);
  5096. if (end) {
  5097. this.setEndBefore(end);
  5098. domUtils.remove(end);
  5099. } else {
  5100. this.collapse(true);
  5101. }
  5102. return this;
  5103. },
  5104. /**
  5105. * 调整range的边界,使其"放大"到最近的父节点
  5106. * @method enlarge
  5107. * @remind 会引起选区的变化
  5108. * @return { UE.dom.Range } 当前range对象
  5109. */
  5110. /**
  5111. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5112. * 要求扩大之后的父节点是block节点
  5113. * @method enlarge
  5114. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5115. * @return { UE.dom.Range } 当前range对象
  5116. */
  5117. enlarge:function (toBlock, stopFn) {
  5118. var isBody = domUtils.isBody,
  5119. pre, node, tmp = this.document.createTextNode('');
  5120. if (toBlock) {
  5121. node = this.startContainer;
  5122. if (node.nodeType == 1) {
  5123. if (node.childNodes[this.startOffset]) {
  5124. pre = node = node.childNodes[this.startOffset]
  5125. } else {
  5126. node.appendChild(tmp);
  5127. pre = node = tmp;
  5128. }
  5129. } else {
  5130. pre = node;
  5131. }
  5132. while (1) {
  5133. if (domUtils.isBlockElm(node)) {
  5134. node = pre;
  5135. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5136. node = pre;
  5137. }
  5138. this.setStartBefore(node);
  5139. break;
  5140. }
  5141. pre = node;
  5142. node = node.parentNode;
  5143. }
  5144. node = this.endContainer;
  5145. if (node.nodeType == 1) {
  5146. if (pre = node.childNodes[this.endOffset]) {
  5147. node.insertBefore(tmp, pre);
  5148. } else {
  5149. node.appendChild(tmp);
  5150. }
  5151. pre = node = tmp;
  5152. } else {
  5153. pre = node;
  5154. }
  5155. while (1) {
  5156. if (domUtils.isBlockElm(node)) {
  5157. node = pre;
  5158. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5159. node = pre;
  5160. }
  5161. this.setEndAfter(node);
  5162. break;
  5163. }
  5164. pre = node;
  5165. node = node.parentNode;
  5166. }
  5167. if (tmp.parentNode === this.endContainer) {
  5168. this.endOffset--;
  5169. }
  5170. domUtils.remove(tmp);
  5171. }
  5172. // 扩展边界到最大
  5173. if (!this.collapsed) {
  5174. while (this.startOffset == 0) {
  5175. if (stopFn && stopFn(this.startContainer)) {
  5176. break;
  5177. }
  5178. if (isBody(this.startContainer)) {
  5179. break;
  5180. }
  5181. this.setStartBefore(this.startContainer);
  5182. }
  5183. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5184. if (stopFn && stopFn(this.endContainer)) {
  5185. break;
  5186. }
  5187. if (isBody(this.endContainer)) {
  5188. break;
  5189. }
  5190. this.setEndAfter(this.endContainer);
  5191. }
  5192. }
  5193. return this;
  5194. },
  5195. enlargeToBlockElm:function(ignoreEnd){
  5196. while(!domUtils.isBlockElm(this.startContainer)){
  5197. this.setStartBefore(this.startContainer);
  5198. }
  5199. if(!ignoreEnd){
  5200. while(!domUtils.isBlockElm(this.endContainer)){
  5201. this.setEndAfter(this.endContainer);
  5202. }
  5203. }
  5204. return this;
  5205. },
  5206. /**
  5207. * 调整Range的边界,使其"缩小"到最合适的位置
  5208. * @method adjustmentBoundary
  5209. * @return { UE.dom.Range } 当前range对象
  5210. * @see UE.dom.Range:shrinkBoundary()
  5211. */
  5212. adjustmentBoundary:function () {
  5213. if (!this.collapsed) {
  5214. while (!domUtils.isBody(this.startContainer) &&
  5215. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5216. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5217. ) {
  5218. this.setStartAfter(this.startContainer);
  5219. }
  5220. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5221. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5222. ) {
  5223. this.setEndBefore(this.endContainer);
  5224. }
  5225. }
  5226. return this;
  5227. },
  5228. /**
  5229. * 给range选区中的内容添加给定的inline标签
  5230. * @method applyInlineStyle
  5231. * @param { String } tagName 需要添加的标签名
  5232. * @example
  5233. * ```html
  5234. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5235. * ```
  5236. */
  5237. /**
  5238. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5239. * @method applyInlineStyle
  5240. * @param { String } tagName 需要添加的标签名
  5241. * @param { Object } attrs 跟随新添加的标签的属性
  5242. * @return { UE.dom.Range } 当前选区
  5243. * @example
  5244. * ```html
  5245. * <p>xxxx[xxxx]x</p>
  5246. *
  5247. * ==>
  5248. *
  5249. * <!-- 执行操作 -->
  5250. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5251. *
  5252. * ==>
  5253. *
  5254. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5255. * ```
  5256. */
  5257. applyInlineStyle:function (tagName, attrs, list) {
  5258. if (this.collapsed)return this;
  5259. this.trimBoundary().enlarge(false,
  5260. function (node) {
  5261. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5262. }).adjustmentBoundary();
  5263. var bookmark = this.createBookmark(),
  5264. end = bookmark.end,
  5265. filterFn = function (node) {
  5266. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5267. },
  5268. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5269. node,
  5270. pre,
  5271. range = this.cloneRange();
  5272. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5273. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5274. range.setStartBefore(current);
  5275. node = current;
  5276. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5277. pre = node;
  5278. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5279. return dtd[tagName][parent.tagName];
  5280. });
  5281. }
  5282. var frag = range.setEndAfter(pre).extractContents(), elm;
  5283. if (list && list.length > 0) {
  5284. var level, top;
  5285. top = level = list[0].cloneNode(false);
  5286. for (var i = 1, ci; ci = list[i++];) {
  5287. level.appendChild(ci.cloneNode(false));
  5288. level = level.firstChild;
  5289. }
  5290. elm = level;
  5291. } else {
  5292. elm = range.document.createElement(tagName);
  5293. }
  5294. if (attrs) {
  5295. domUtils.setAttributes(elm, attrs);
  5296. }
  5297. elm.appendChild(frag);
  5298. range.insertNode(list ? top : elm);
  5299. //处理下滑线在a上的情况
  5300. var aNode;
  5301. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5302. domUtils.setAttributes(aNode, attrs);
  5303. domUtils.remove(elm, true);
  5304. elm = aNode;
  5305. } else {
  5306. domUtils.mergeSibling(elm);
  5307. domUtils.clearEmptySibling(elm);
  5308. }
  5309. //去除子节点相同的
  5310. domUtils.mergeChild(elm, attrs);
  5311. current = domUtils.getNextDomNode(elm, false, filterFn);
  5312. domUtils.mergeToParent(elm);
  5313. if (node === end) {
  5314. break;
  5315. }
  5316. } else {
  5317. current = domUtils.getNextDomNode(current, true, filterFn);
  5318. }
  5319. }
  5320. return this.moveToBookmark(bookmark);
  5321. },
  5322. /**
  5323. * 移除当前选区内指定的inline标签,但保留其中的内容
  5324. * @method removeInlineStyle
  5325. * @param { String } tagName 需要移除的标签名
  5326. * @return { UE.dom.Range } 当前的range对象
  5327. * @example
  5328. * ```html
  5329. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5330. * ```
  5331. */
  5332. /**
  5333. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5334. * @method removeInlineStyle
  5335. * @param { Array } tagNameArr 需要移除的标签名的数组
  5336. * @return { UE.dom.Range } 当前的range对象
  5337. * @see UE.dom.Range:removeInlineStyle(String)
  5338. */
  5339. removeInlineStyle:function (tagNames) {
  5340. if (this.collapsed)return this;
  5341. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5342. this.shrinkBoundary().adjustmentBoundary();
  5343. var start = this.startContainer, end = this.endContainer;
  5344. while (1) {
  5345. if (start.nodeType == 1) {
  5346. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5347. break;
  5348. }
  5349. if (start.tagName.toLowerCase() == 'body') {
  5350. start = null;
  5351. break;
  5352. }
  5353. }
  5354. start = start.parentNode;
  5355. }
  5356. while (1) {
  5357. if (end.nodeType == 1) {
  5358. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5359. break;
  5360. }
  5361. if (end.tagName.toLowerCase() == 'body') {
  5362. end = null;
  5363. break;
  5364. }
  5365. }
  5366. end = end.parentNode;
  5367. }
  5368. var bookmark = this.createBookmark(),
  5369. frag,
  5370. tmpRange;
  5371. if (start) {
  5372. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5373. frag = tmpRange.extractContents();
  5374. tmpRange.insertNode(frag);
  5375. domUtils.clearEmptySibling(start, true);
  5376. start.parentNode.insertBefore(bookmark.start, start);
  5377. }
  5378. if (end) {
  5379. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5380. frag = tmpRange.extractContents();
  5381. tmpRange.insertNode(frag);
  5382. domUtils.clearEmptySibling(end, false, true);
  5383. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5384. }
  5385. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5386. return node.nodeType == 1;
  5387. }), next;
  5388. while (current && current !== bookmark.end) {
  5389. next = domUtils.getNextDomNode(current, true, function (node) {
  5390. return node.nodeType == 1;
  5391. });
  5392. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5393. domUtils.remove(current, true);
  5394. }
  5395. current = next;
  5396. }
  5397. return this.moveToBookmark(bookmark);
  5398. },
  5399. /**
  5400. * 获取当前选中的自闭合的节点
  5401. * @method getClosedNode
  5402. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5403. */
  5404. getClosedNode:function () {
  5405. var node;
  5406. if (!this.collapsed) {
  5407. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5408. if (selectOneNode(range)) {
  5409. var child = range.startContainer.childNodes[range.startOffset];
  5410. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5411. node = child;
  5412. }
  5413. }
  5414. }
  5415. return node;
  5416. },
  5417. /**
  5418. * 在页面上高亮range所表示的选区
  5419. * @method select
  5420. * @return { UE.dom.Range } 返回当前Range对象
  5421. */
  5422. //这里不区分ie9以上,trace:3824
  5423. select:browser.ie ? function (noFillData, textRange) {
  5424. var nativeRange;
  5425. if (!this.collapsed)
  5426. this.shrinkBoundary();
  5427. var node = this.getClosedNode();
  5428. if (node && !textRange) {
  5429. try {
  5430. nativeRange = this.document.body.createControlRange();
  5431. nativeRange.addElement(node);
  5432. nativeRange.select();
  5433. } catch (e) {}
  5434. return this;
  5435. }
  5436. var bookmark = this.createBookmark(),
  5437. start = bookmark.start,
  5438. end;
  5439. nativeRange = this.document.body.createTextRange();
  5440. nativeRange.moveToElementText(start);
  5441. nativeRange.moveStart('character', 1);
  5442. if (!this.collapsed) {
  5443. var nativeRangeEnd = this.document.body.createTextRange();
  5444. end = bookmark.end;
  5445. nativeRangeEnd.moveToElementText(end);
  5446. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5447. } else {
  5448. if (!noFillData && this.startContainer.nodeType != 3) {
  5449. //使用<span>|x<span>固定住光标
  5450. var tmpText = this.document.createTextNode(fillChar),
  5451. tmp = this.document.createElement('span');
  5452. tmp.appendChild(this.document.createTextNode(fillChar));
  5453. start.parentNode.insertBefore(tmp, start);
  5454. start.parentNode.insertBefore(tmpText, start);
  5455. //当点b,i,u时,不能清除i上边的b
  5456. removeFillData(this.document, tmpText);
  5457. fillData = tmpText;
  5458. mergeSibling(tmp, 'previousSibling');
  5459. mergeSibling(start, 'nextSibling');
  5460. nativeRange.moveStart('character', -1);
  5461. nativeRange.collapse(true);
  5462. }
  5463. }
  5464. this.moveToBookmark(bookmark);
  5465. tmp && domUtils.remove(tmp);
  5466. //IE在隐藏状态下不支持range操作,catch一下
  5467. try {
  5468. nativeRange.select();
  5469. } catch (e) {
  5470. }
  5471. return this;
  5472. } : function (notInsertFillData) {
  5473. function checkOffset(rng){
  5474. function check(node,offset,dir){
  5475. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5476. rng[dir + 'Offset'] = node.nodeValue.length
  5477. }
  5478. }
  5479. check(rng.startContainer,rng.startOffset,'start');
  5480. check(rng.endContainer,rng.endOffset,'end');
  5481. }
  5482. var win = domUtils.getWindow(this.document),
  5483. sel = win.getSelection(),
  5484. txtNode;
  5485. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5486. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5487. browser.gecko ? this.document.body.focus() : win.focus();
  5488. if (sel) {
  5489. sel.removeAllRanges();
  5490. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5491. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5492. if (this.collapsed && !notInsertFillData) {
  5493. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5494. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5495. // var tmp = this.document.createTextNode('');
  5496. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5497. // }
  5498. //
  5499. //处理光标落在文本节点的情况
  5500. //处理以下的情况
  5501. //<b>|xxxx</b>
  5502. //<b>xxxx</b>|xxxx
  5503. //xxxx<b>|</b>
  5504. var start = this.startContainer,child = start;
  5505. if(start.nodeType == 1){
  5506. child = start.childNodes[this.startOffset];
  5507. }
  5508. if( !(start.nodeType == 3 && this.startOffset) &&
  5509. (child ?
  5510. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5511. :
  5512. (!start.lastChild || start.lastChild.nodeType != 3)
  5513. )
  5514. ){
  5515. txtNode = this.document.createTextNode(fillChar);
  5516. //跟着前边走
  5517. this.insertNode(txtNode);
  5518. removeFillData(this.document, txtNode);
  5519. mergeSibling(txtNode, 'previousSibling');
  5520. mergeSibling(txtNode, 'nextSibling');
  5521. fillData = txtNode;
  5522. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5523. }
  5524. }
  5525. var nativeRange = this.document.createRange();
  5526. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5527. var child = this.startContainer.childNodes[this.startOffset];
  5528. if(!child){
  5529. //往前靠拢
  5530. child = this.startContainer.lastChild;
  5531. if( child && domUtils.isBr(child)){
  5532. this.setStartBefore(child).collapse(true);
  5533. }
  5534. }else{
  5535. //向后靠拢
  5536. while(child && domUtils.isBlockElm(child)){
  5537. if(child.nodeType == 1 && child.childNodes[0]){
  5538. child = child.childNodes[0]
  5539. }else{
  5540. break;
  5541. }
  5542. }
  5543. child && this.setStartBefore(child).collapse(true)
  5544. }
  5545. }
  5546. //是createAddress最后一位算的不准,现在这里进行微调
  5547. checkOffset(this);
  5548. nativeRange.setStart(this.startContainer, this.startOffset);
  5549. nativeRange.setEnd(this.endContainer, this.endOffset);
  5550. sel.addRange(nativeRange);
  5551. }
  5552. return this;
  5553. },
  5554. /**
  5555. * 滚动到当前range开始的位置
  5556. * @method scrollToView
  5557. * @param { Window } win 当前range对象所属的window对象
  5558. * @return { UE.dom.Range } 当前Range对象
  5559. */
  5560. /**
  5561. * 滚动到距离当前range开始位置 offset 的位置处
  5562. * @method scrollToView
  5563. * @param { Window } win 当前range对象所属的window对象
  5564. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5565. * @return { UE.dom.Range } 当前Range对象
  5566. */
  5567. scrollToView:function (win, offset) {
  5568. win = win ? window : domUtils.getWindow(this.document);
  5569. var me = this,
  5570. span = me.document.createElement('span');
  5571. //trace:717
  5572. span.innerHTML = '&nbsp;';
  5573. me.cloneRange().insertNode(span);
  5574. domUtils.scrollToView(span, win, offset);
  5575. domUtils.remove(span);
  5576. return me;
  5577. },
  5578. /**
  5579. * 判断当前选区内容是否占位符
  5580. * @private
  5581. * @method inFillChar
  5582. * @return { Boolean } 如果是占位符返回true,否则返回false
  5583. */
  5584. inFillChar : function(){
  5585. var start = this.startContainer;
  5586. if(this.collapsed && start.nodeType == 3
  5587. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5588. ){
  5589. return true;
  5590. }
  5591. return false;
  5592. },
  5593. /**
  5594. * 保存
  5595. * @method createAddress
  5596. * @private
  5597. * @return { Boolean } 返回开始和结束的位置
  5598. * @example
  5599. * ```html
  5600. * <body>
  5601. * <p>
  5602. * aaaa
  5603. * <em>
  5604. * <!-- 选区开始 -->
  5605. * bbbb
  5606. * <!-- 选区结束 -->
  5607. * </em>
  5608. * </p>
  5609. *
  5610. * <script>
  5611. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5612. * console.log( range.createAddress() );
  5613. * </script>
  5614. * </body>
  5615. * ```
  5616. */
  5617. createAddress : function(ignoreEnd,ignoreTxt){
  5618. var addr = {},me = this;
  5619. function getAddress(isStart){
  5620. var node = isStart ? me.startContainer : me.endContainer;
  5621. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5622. addrs = [];
  5623. for(var i = 0,ci;ci = parents[i++];){
  5624. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5625. }
  5626. var firstIndex = 0;
  5627. if(ignoreTxt){
  5628. if(node.nodeType == 3){
  5629. var tmpNode = node.previousSibling;
  5630. while(tmpNode && tmpNode.nodeType == 3){
  5631. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5632. tmpNode = tmpNode.previousSibling;
  5633. }
  5634. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5635. }else{
  5636. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5637. if(node){
  5638. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5639. }else{
  5640. node = isStart ? me.startContainer : me.endContainer;
  5641. var first = node.firstChild;
  5642. while(first){
  5643. if(domUtils.isFillChar(first)){
  5644. first = first.nextSibling;
  5645. continue;
  5646. }
  5647. firstIndex++;
  5648. if(first.nodeType == 3){
  5649. while( first && first.nodeType == 3){
  5650. first = first.nextSibling;
  5651. }
  5652. }else{
  5653. first = first.nextSibling;
  5654. }
  5655. }
  5656. }
  5657. }
  5658. }else{
  5659. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5660. }
  5661. if(firstIndex < 0){
  5662. firstIndex = 0;
  5663. }
  5664. addrs.push(firstIndex);
  5665. return addrs;
  5666. }
  5667. addr.startAddress = getAddress(true);
  5668. if(!ignoreEnd){
  5669. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5670. }
  5671. return addr;
  5672. },
  5673. /**
  5674. * 保存
  5675. * @method createAddress
  5676. * @private
  5677. * @return { Boolean } 返回开始和结束的位置
  5678. * @example
  5679. * ```html
  5680. * <body>
  5681. * <p>
  5682. * aaaa
  5683. * <em>
  5684. * <!-- 选区开始 -->
  5685. * bbbb
  5686. * <!-- 选区结束 -->
  5687. * </em>
  5688. * </p>
  5689. *
  5690. * <script>
  5691. * var range = editor.selection.getRange();
  5692. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5693. * range.select();
  5694. * //output: 'bbbb'
  5695. * console.log(editor.selection.getText());
  5696. * </script>
  5697. * </body>
  5698. * ```
  5699. */
  5700. moveToAddress : function(addr,ignoreEnd){
  5701. var me = this;
  5702. function getNode(address,isStart){
  5703. var tmpNode = me.document.body,
  5704. parentNode,offset;
  5705. for(var i= 0,ci,l=address.length;i<l;i++){
  5706. ci = address[i];
  5707. parentNode = tmpNode;
  5708. tmpNode = tmpNode.childNodes[ci];
  5709. if(!tmpNode){
  5710. offset = ci;
  5711. break;
  5712. }
  5713. }
  5714. if(isStart){
  5715. if(tmpNode){
  5716. me.setStartBefore(tmpNode)
  5717. }else{
  5718. me.setStart(parentNode,offset)
  5719. }
  5720. }else{
  5721. if(tmpNode){
  5722. me.setEndBefore(tmpNode)
  5723. }else{
  5724. me.setEnd(parentNode,offset)
  5725. }
  5726. }
  5727. }
  5728. getNode(addr.startAddress,true);
  5729. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5730. return me;
  5731. },
  5732. /**
  5733. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5734. * @method equals
  5735. * @param { UE.dom.Range } 需要判断的Range对象
  5736. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5737. */
  5738. equals : function(rng){
  5739. for(var p in this){
  5740. if(this.hasOwnProperty(p)){
  5741. if(this[p] !== rng[p])
  5742. return false
  5743. }
  5744. }
  5745. return true;
  5746. },
  5747. /**
  5748. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5749. * 作为其参数。
  5750. * @method traversal
  5751. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5752. * @return { UE.dom.Range } 当前range对象
  5753. * @example
  5754. * ```html
  5755. *
  5756. * <body>
  5757. *
  5758. * <!-- 选区开始 -->
  5759. * <span></span>
  5760. * <a></a>
  5761. * <!-- 选区结束 -->
  5762. * </body>
  5763. *
  5764. * <script>
  5765. *
  5766. * //output: <span></span><a></a>
  5767. * console.log( range.cloneContents() );
  5768. *
  5769. * range.traversal( function ( node ) {
  5770. *
  5771. * if ( node.nodeType === 1 ) {
  5772. * node.className = "test";
  5773. * }
  5774. *
  5775. * } );
  5776. *
  5777. * //output: <span class="test"></span><a class="test"></a>
  5778. * console.log( range.cloneContents() );
  5779. *
  5780. * </script>
  5781. * ```
  5782. */
  5783. /**
  5784. * 遍历range内的节点。
  5785. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5786. * 作为其参数。
  5787. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5788. * 发doFn函数的执行
  5789. * @method traversal
  5790. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5791. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5792. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5793. * 会触发doFn。
  5794. * @return { UE.dom.Range } 当前range对象
  5795. * @see UE.dom.Range:traversal(Function)
  5796. * @example
  5797. * ```html
  5798. *
  5799. * <body>
  5800. *
  5801. * <!-- 选区开始 -->
  5802. * <span></span>
  5803. * <a></a>
  5804. * <!-- 选区结束 -->
  5805. * </body>
  5806. *
  5807. * <script>
  5808. *
  5809. * //output: <span></span><a></a>
  5810. * console.log( range.cloneContents() );
  5811. *
  5812. * range.traversal( function ( node ) {
  5813. *
  5814. * node.className = "test";
  5815. *
  5816. * }, function ( node ) {
  5817. * return node.nodeType === 1;
  5818. * } );
  5819. *
  5820. * //output: <span class="test"></span><a class="test"></a>
  5821. * console.log( range.cloneContents() );
  5822. *
  5823. * </script>
  5824. * ```
  5825. */
  5826. traversal:function(doFn,filterFn){
  5827. if (this.collapsed)
  5828. return this;
  5829. var bookmark = this.createBookmark(),
  5830. end = bookmark.end,
  5831. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5832. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5833. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5834. doFn(current);
  5835. current = tmpNode;
  5836. }
  5837. return this.moveToBookmark(bookmark);
  5838. }
  5839. };
  5840. })();
  5841. // core/Selection.js
  5842. /**
  5843. * 选集
  5844. * @file
  5845. * @module UE.dom
  5846. * @class Selection
  5847. * @since 1.2.6.1
  5848. */
  5849. /**
  5850. * 选区集合
  5851. * @unfile
  5852. * @module UE.dom
  5853. * @class Selection
  5854. */
  5855. (function () {
  5856. function getBoundaryInformation( range, start ) {
  5857. var getIndex = domUtils.getNodeIndex;
  5858. range = range.duplicate();
  5859. range.collapse( start );
  5860. var parent = range.parentElement();
  5861. //如果节点里没有子节点,直接退出
  5862. if ( !parent.hasChildNodes() ) {
  5863. return {container:parent, offset:0};
  5864. }
  5865. var siblings = parent.children,
  5866. child,
  5867. testRange = range.duplicate(),
  5868. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5869. distance;
  5870. while ( startIndex <= endIndex ) {
  5871. index = Math.floor( (startIndex + endIndex) / 2 );
  5872. child = siblings[index];
  5873. testRange.moveToElementText( child );
  5874. var position = testRange.compareEndPoints( 'StartToStart', range );
  5875. if ( position > 0 ) {
  5876. endIndex = index - 1;
  5877. } else if ( position < 0 ) {
  5878. startIndex = index + 1;
  5879. } else {
  5880. //trace:1043
  5881. return {container:parent, offset:getIndex( child )};
  5882. }
  5883. }
  5884. if ( index == -1 ) {
  5885. testRange.moveToElementText( parent );
  5886. testRange.setEndPoint( 'StartToStart', range );
  5887. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5888. siblings = parent.childNodes;
  5889. if ( !distance ) {
  5890. child = siblings[siblings.length - 1];
  5891. return {container:child, offset:child.nodeValue.length};
  5892. }
  5893. var i = siblings.length;
  5894. while ( distance > 0 ){
  5895. distance -= siblings[ --i ].nodeValue.length;
  5896. }
  5897. return {container:siblings[i], offset:-distance};
  5898. }
  5899. testRange.collapse( position > 0 );
  5900. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5901. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5902. if ( !distance ) {
  5903. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5904. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5905. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5906. }
  5907. while ( distance > 0 ) {
  5908. try {
  5909. var pre = child;
  5910. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5911. distance -= child.nodeValue.length;
  5912. } catch ( e ) {
  5913. return {container:parent, offset:getIndex( pre )};
  5914. }
  5915. }
  5916. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5917. }
  5918. /**
  5919. * 将ieRange转换为Range对象
  5920. * @param {Range} ieRange ieRange对象
  5921. * @param {Range} range Range对象
  5922. * @return {Range} range 返回转换后的Range对象
  5923. */
  5924. function transformIERangeToRange( ieRange, range ) {
  5925. if ( ieRange.item ) {
  5926. range.selectNode( ieRange.item( 0 ) );
  5927. } else {
  5928. var bi = getBoundaryInformation( ieRange, true );
  5929. range.setStart( bi.container, bi.offset );
  5930. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5931. bi = getBoundaryInformation( ieRange, false );
  5932. range.setEnd( bi.container, bi.offset );
  5933. }
  5934. }
  5935. return range;
  5936. }
  5937. /**
  5938. * 获得ieRange
  5939. * @param {Selection} sel Selection对象
  5940. * @return {ieRange} 得到ieRange
  5941. */
  5942. function _getIERange( sel ) {
  5943. var ieRange;
  5944. //ie下有可能报错
  5945. try {
  5946. ieRange = sel.getNative().createRange();
  5947. } catch ( e ) {
  5948. return null;
  5949. }
  5950. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5951. if ( ( el.ownerDocument || el ) === sel.document ) {
  5952. return ieRange;
  5953. }
  5954. return null;
  5955. }
  5956. var Selection = dom.Selection = function ( doc ) {
  5957. var me = this, iframe;
  5958. me.document = doc;
  5959. if ( browser.ie9below ) {
  5960. iframe = domUtils.getWindow( doc ).frameElement;
  5961. domUtils.on( iframe, 'beforedeactivate', function () {
  5962. me._bakIERange = me.getIERange();
  5963. } );
  5964. domUtils.on( iframe, 'activate', function () {
  5965. try {
  5966. if ( !_getIERange( me ) && me._bakIERange ) {
  5967. me._bakIERange.select();
  5968. }
  5969. } catch ( ex ) {
  5970. }
  5971. me._bakIERange = null;
  5972. } );
  5973. }
  5974. iframe = doc = null;
  5975. };
  5976. Selection.prototype = {
  5977. rangeInBody : function(rng,txtRange){
  5978. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5979. return node === this.document.body || domUtils.inDoc(node,this.document);
  5980. },
  5981. /**
  5982. * 获取原生seleciton对象
  5983. * @method getNative
  5984. * @return { Object } 获得selection对象
  5985. * @example
  5986. * ```javascript
  5987. * editor.selection.getNative();
  5988. * ```
  5989. */
  5990. getNative:function () {
  5991. var doc = this.document;
  5992. try {
  5993. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5994. } catch ( e ) {
  5995. return null;
  5996. }
  5997. },
  5998. /**
  5999. * 获得ieRange
  6000. * @method getIERange
  6001. * @return { Object } 返回ie原生的Range
  6002. * @example
  6003. * ```javascript
  6004. * editor.selection.getIERange();
  6005. * ```
  6006. */
  6007. getIERange:function () {
  6008. var ieRange = _getIERange( this );
  6009. if ( !ieRange ) {
  6010. if ( this._bakIERange ) {
  6011. return this._bakIERange;
  6012. }
  6013. }
  6014. return ieRange;
  6015. },
  6016. /**
  6017. * 缓存当前选区的range和选区的开始节点
  6018. * @method cache
  6019. */
  6020. cache:function () {
  6021. this.clear();
  6022. this._cachedRange = this.getRange();
  6023. this._cachedStartElement = this.getStart();
  6024. this._cachedStartElementPath = this.getStartElementPath();
  6025. },
  6026. /**
  6027. * 获取选区开始位置的父节点到body
  6028. * @method getStartElementPath
  6029. * @return { Array } 返回父节点集合
  6030. * @example
  6031. * ```javascript
  6032. * editor.selection.getStartElementPath();
  6033. * ```
  6034. */
  6035. getStartElementPath:function () {
  6036. if ( this._cachedStartElementPath ) {
  6037. return this._cachedStartElementPath;
  6038. }
  6039. var start = this.getStart();
  6040. if ( start ) {
  6041. return domUtils.findParents( start, true, null, true )
  6042. }
  6043. return [];
  6044. },
  6045. /**
  6046. * 清空缓存
  6047. * @method clear
  6048. */
  6049. clear:function () {
  6050. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6051. },
  6052. /**
  6053. * 编辑器是否得到了选区
  6054. * @method isFocus
  6055. */
  6056. isFocus:function () {
  6057. try {
  6058. if(browser.ie9below){
  6059. var nativeRange = _getIERange(this);
  6060. return !!(nativeRange && this.rangeInBody(nativeRange));
  6061. }else{
  6062. return !!this.getNative().rangeCount;
  6063. }
  6064. } catch ( e ) {
  6065. return false;
  6066. }
  6067. },
  6068. /**
  6069. * 获取选区对应的Range
  6070. * @method getRange
  6071. * @return { Object } 得到Range对象
  6072. * @example
  6073. * ```javascript
  6074. * editor.selection.getRange();
  6075. * ```
  6076. */
  6077. getRange:function () {
  6078. var me = this;
  6079. function optimze( range ) {
  6080. var child = me.document.body.firstChild,
  6081. collapsed = range.collapsed;
  6082. while ( child && child.firstChild ) {
  6083. range.setStart( child, 0 );
  6084. child = child.firstChild;
  6085. }
  6086. if ( !range.startContainer ) {
  6087. range.setStart( me.document.body, 0 )
  6088. }
  6089. if ( collapsed ) {
  6090. range.collapse( true );
  6091. }
  6092. }
  6093. if ( me._cachedRange != null ) {
  6094. return this._cachedRange;
  6095. }
  6096. var range = new baidu.editor.dom.Range( me.document );
  6097. if ( browser.ie9below ) {
  6098. var nativeRange = me.getIERange();
  6099. if ( nativeRange ) {
  6100. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6101. try{
  6102. transformIERangeToRange( nativeRange, range );
  6103. }catch(e){
  6104. optimze( range );
  6105. }
  6106. } else {
  6107. optimze( range );
  6108. }
  6109. } else {
  6110. var sel = me.getNative();
  6111. if ( sel && sel.rangeCount ) {
  6112. var firstRange = sel.getRangeAt( 0 );
  6113. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6114. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6115. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6116. optimze( range );
  6117. }
  6118. } else {
  6119. //trace:1734 有可能已经不在dom树上了,标识的节点
  6120. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6121. return this._bakRange;
  6122. }
  6123. optimze( range );
  6124. }
  6125. }
  6126. return this._bakRange = range;
  6127. },
  6128. /**
  6129. * 获取开始元素,用于状态反射
  6130. * @method getStart
  6131. * @return { Element } 获得开始元素
  6132. * @example
  6133. * ```javascript
  6134. * editor.selection.getStart();
  6135. * ```
  6136. */
  6137. getStart:function () {
  6138. if ( this._cachedStartElement ) {
  6139. return this._cachedStartElement;
  6140. }
  6141. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6142. tmpRange,
  6143. start, tmp, parent;
  6144. if ( browser.ie9below ) {
  6145. if ( !range ) {
  6146. //todo 给第一个值可能会有问题
  6147. return this.document.body.firstChild;
  6148. }
  6149. //control元素
  6150. if ( range.item ){
  6151. return range.item( 0 );
  6152. }
  6153. tmpRange = range.duplicate();
  6154. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6155. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6156. tmpRange.collapse( 1 );
  6157. start = tmpRange.parentElement();
  6158. parent = tmp = range.parentElement();
  6159. while ( tmp = tmp.parentNode ) {
  6160. if ( tmp == start ) {
  6161. start = parent;
  6162. break;
  6163. }
  6164. }
  6165. } else {
  6166. range.shrinkBoundary();
  6167. start = range.startContainer;
  6168. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6169. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6170. }
  6171. if ( start.nodeType == 3 ){
  6172. return start.parentNode;
  6173. }
  6174. }
  6175. return start;
  6176. },
  6177. /**
  6178. * 得到选区中的文本
  6179. * @method getText
  6180. * @return { String } 选区中包含的文本
  6181. * @example
  6182. * ```javascript
  6183. * editor.selection.getText();
  6184. * ```
  6185. */
  6186. getText:function () {
  6187. var nativeSel, nativeRange;
  6188. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6189. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6190. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6191. }
  6192. return '';
  6193. },
  6194. /**
  6195. * 清除选区
  6196. * @method clearRange
  6197. * @example
  6198. * ```javascript
  6199. * editor.selection.clearRange();
  6200. * ```
  6201. */
  6202. clearRange : function(){
  6203. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6204. }
  6205. };
  6206. })();
  6207. // core/Editor.js
  6208. /**
  6209. * 编辑器主类,包含编辑器提供的大部分公用接口
  6210. * @file
  6211. * @module UE
  6212. * @class Editor
  6213. * @since 1.2.6.1
  6214. */
  6215. /**
  6216. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6217. * @unfile
  6218. * @module UE
  6219. */
  6220. /**
  6221. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6222. * @unfile
  6223. * @module UE
  6224. * @class Editor
  6225. */
  6226. (function () {
  6227. var uid = 0, _selectionChangeTimer;
  6228. /**
  6229. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6230. * @private
  6231. * @method setValue
  6232. * @param { UE.Editor } editor 编辑器事例
  6233. */
  6234. function setValue(form, editor) {
  6235. var textarea;
  6236. if (editor.textarea) {
  6237. if (utils.isString(editor.textarea)) {
  6238. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6239. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6240. textarea = ti;
  6241. break;
  6242. }
  6243. }
  6244. } else {
  6245. textarea = editor.textarea;
  6246. }
  6247. }
  6248. if (!textarea) {
  6249. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6250. 'name': editor.options.textarea,
  6251. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6252. 'style': "display:none"
  6253. }));
  6254. //不要产生多个textarea
  6255. editor.textarea = textarea;
  6256. }
  6257. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
  6258. textarea.value = editor.hasContents() ?
  6259. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6260. ''
  6261. }
  6262. function loadPlugins(me){
  6263. //初始化插件
  6264. for (var pi in UE.plugins) {
  6265. UE.plugins[pi].call(me);
  6266. }
  6267. }
  6268. function checkCurLang(I18N){
  6269. for(var lang in I18N){
  6270. return lang
  6271. }
  6272. }
  6273. function langReadied(me){
  6274. me.langIsReady = true;
  6275. me.fireEvent("langReady");
  6276. }
  6277. /**
  6278. * 编辑器准备就绪后会触发该事件
  6279. * @module UE
  6280. * @class Editor
  6281. * @event ready
  6282. * @remind render方法执行完成之后,会触发该事件
  6283. * @remind
  6284. * @example
  6285. * ```javascript
  6286. * editor.addListener( 'ready', function( editor ) {
  6287. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6288. * } );
  6289. * ```
  6290. */
  6291. /**
  6292. * 执行destroy方法,会触发该事件
  6293. * @module UE
  6294. * @class Editor
  6295. * @event destroy
  6296. * @see UE.Editor:destroy()
  6297. */
  6298. /**
  6299. * 执行reset方法,会触发该事件
  6300. * @module UE
  6301. * @class Editor
  6302. * @event reset
  6303. * @see UE.Editor:reset()
  6304. */
  6305. /**
  6306. * 执行focus方法,会触发该事件
  6307. * @module UE
  6308. * @class Editor
  6309. * @event focus
  6310. * @see UE.Editor:focus(Boolean)
  6311. */
  6312. /**
  6313. * 语言加载完成会触发该事件
  6314. * @module UE
  6315. * @class Editor
  6316. * @event langReady
  6317. */
  6318. /**
  6319. * 运行命令之后会触发该命令
  6320. * @module UE
  6321. * @class Editor
  6322. * @event beforeExecCommand
  6323. */
  6324. /**
  6325. * 运行命令之后会触发该命令
  6326. * @module UE
  6327. * @class Editor
  6328. * @event afterExecCommand
  6329. */
  6330. /**
  6331. * 运行命令之前会触发该命令
  6332. * @module UE
  6333. * @class Editor
  6334. * @event firstBeforeExecCommand
  6335. */
  6336. /**
  6337. * 在getContent方法执行之前会触发该事件
  6338. * @module UE
  6339. * @class Editor
  6340. * @event beforeGetContent
  6341. * @see UE.Editor:getContent()
  6342. */
  6343. /**
  6344. * 在getContent方法执行之后会触发该事件
  6345. * @module UE
  6346. * @class Editor
  6347. * @event afterGetContent
  6348. * @see UE.Editor:getContent()
  6349. */
  6350. /**
  6351. * 在getAllHtml方法执行时会触发该事件
  6352. * @module UE
  6353. * @class Editor
  6354. * @event getAllHtml
  6355. * @see UE.Editor:getAllHtml()
  6356. */
  6357. /**
  6358. * 在setContent方法执行之前会触发该事件
  6359. * @module UE
  6360. * @class Editor
  6361. * @event beforeSetContent
  6362. * @see UE.Editor:setContent(String)
  6363. */
  6364. /**
  6365. * 在setContent方法执行之后会触发该事件
  6366. * @module UE
  6367. * @class Editor
  6368. * @event afterSetContent
  6369. * @see UE.Editor:setContent(String)
  6370. */
  6371. /**
  6372. * 每当编辑器内部选区发生改变时,将触发该事件
  6373. * @event selectionchange
  6374. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6375. * @example
  6376. * ```javascript
  6377. * editor.addListener( 'selectionchange', function( editor ) {
  6378. * console.log('选区发生改变');
  6379. * }
  6380. */
  6381. /**
  6382. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6383. * @module UE
  6384. * @class Editor
  6385. * @event beforeSelectionChange
  6386. * @see UE.Editor:selectionchange
  6387. */
  6388. /**
  6389. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6390. * @module UE
  6391. * @class Editor
  6392. * @event afterSelectionChange
  6393. * @see UE.Editor:selectionchange
  6394. */
  6395. /**
  6396. * 编辑器内容发生改变时会触发该事件
  6397. * @module UE
  6398. * @class Editor
  6399. * @event contentChange
  6400. */
  6401. /**
  6402. * 以默认参数构建一个编辑器实例
  6403. * @constructor
  6404. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6405. * @example
  6406. * ```javascript
  6407. * var editor = new UE.Editor();
  6408. * editor.execCommand('blod');
  6409. * ```
  6410. * @see UE.Config
  6411. */
  6412. /**
  6413. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6414. * @constructor
  6415. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6416. * @param { Object } setting 创建编辑器的参数
  6417. * @example
  6418. * ```javascript
  6419. * var editor = new UE.Editor();
  6420. * editor.execCommand('blod');
  6421. * ```
  6422. * @see UE.Config
  6423. */
  6424. var Editor = UE.Editor = function (options) {
  6425. var me = this;
  6426. me.uid = uid++;
  6427. EventBase.call(me);
  6428. me.commands = {};
  6429. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6430. me.shortcutkeys = {};
  6431. me.inputRules = [];
  6432. me.outputRules = [];
  6433. //设置默认的常用属性
  6434. me.setOpt(Editor.defaultOptions(me));
  6435. /* 尝试异步加载后台配置 */
  6436. me.loadServerConfig();
  6437. if(!utils.isEmptyObject(UE.I18N)){
  6438. //修改默认的语言类型
  6439. me.options.lang = checkCurLang(UE.I18N);
  6440. UE.plugin.load(me);
  6441. langReadied(me);
  6442. }else{
  6443. utils.loadFile(document, {
  6444. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6445. tag: "script",
  6446. type: "text/javascript",
  6447. defer: "defer"
  6448. }, function () {
  6449. UE.plugin.load(me);
  6450. langReadied(me);
  6451. });
  6452. }
  6453. UE.instants['ueditorInstant' + me.uid] = me;
  6454. };
  6455. Editor.prototype = {
  6456. registerCommand : function(name,obj){
  6457. this.commands[name] = obj;
  6458. },
  6459. /**
  6460. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6461. * @method ready
  6462. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6463. * 立即触发该回调。
  6464. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6465. * @example
  6466. * ```javascript
  6467. * editor.ready( function( editor ) {
  6468. * editor.setContent('初始化完毕');
  6469. * } );
  6470. * ```
  6471. * @see UE.Editor.event:ready
  6472. */
  6473. ready: function (fn) {
  6474. var me = this;
  6475. if (fn) {
  6476. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6477. }
  6478. },
  6479. /**
  6480. * 该方法是提供给插件里面使用,设置配置项默认值
  6481. * @method setOpt
  6482. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6483. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6484. * @param { String } key 编辑器的可接受的选项名称
  6485. * @param { * } val 该选项可接受的值
  6486. * @example
  6487. * ```javascript
  6488. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6489. * ```
  6490. */
  6491. /**
  6492. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6493. * @method setOpt
  6494. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6495. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6496. * @param { Object } options 将要设置的选项的键值对对象
  6497. * @example
  6498. * ```javascript
  6499. * editor.setOpt( {
  6500. * 'initContent': '欢迎使用编辑器'
  6501. * } );
  6502. * ```
  6503. */
  6504. setOpt: function (key, val) {
  6505. var obj = {};
  6506. if (utils.isString(key)) {
  6507. obj[key] = val
  6508. } else {
  6509. obj = key;
  6510. }
  6511. utils.extend(this.options, obj, true);
  6512. },
  6513. getOpt:function(key){
  6514. return this.options[key]
  6515. },
  6516. /**
  6517. * 销毁编辑器实例,使用textarea代替
  6518. * @method destroy
  6519. * @example
  6520. * ```javascript
  6521. * editor.destroy();
  6522. * ```
  6523. */
  6524. destroy: function () {
  6525. var me = this;
  6526. me.fireEvent('destroy');
  6527. var container = me.container.parentNode;
  6528. var textarea = me.textarea;
  6529. if (!textarea) {
  6530. textarea = document.createElement('textarea');
  6531. container.parentNode.insertBefore(textarea, container);
  6532. } else {
  6533. textarea.style.display = ''
  6534. }
  6535. textarea.style.width = me.iframe.offsetWidth + 'px';
  6536. textarea.style.height = me.iframe.offsetHeight + 'px';
  6537. textarea.value = me.getContent();
  6538. textarea.id = me.key;
  6539. container.innerHTML = '';
  6540. domUtils.remove(container);
  6541. var key = me.key;
  6542. //trace:2004
  6543. for (var p in me) {
  6544. if (me.hasOwnProperty(p)) {
  6545. delete this[p];
  6546. }
  6547. }
  6548. UE.delEditor(key);
  6549. },
  6550. /**
  6551. * 渲染编辑器的DOM到指定容器
  6552. * @method render
  6553. * @param { String } containerId 指定一个容器ID
  6554. * @remind 执行该方法,会触发ready事件
  6555. * @warning 必须且只能调用一次
  6556. */
  6557. /**
  6558. * 渲染编辑器的DOM到指定容器
  6559. * @method render
  6560. * @param { Element } containerDom 直接指定容器对象
  6561. * @remind 执行该方法,会触发ready事件
  6562. * @warning 必须且只能调用一次
  6563. */
  6564. render: function (container) {
  6565. var me = this,
  6566. options = me.options,
  6567. getStyleValue=function(attr){
  6568. return parseInt(domUtils.getComputedStyle(container,attr));
  6569. };
  6570. if (utils.isString(container)) {
  6571. container = document.getElementById(container);
  6572. }
  6573. if (container) {
  6574. if(options.initialFrameWidth){
  6575. options.minFrameWidth = options.initialFrameWidth
  6576. }else{
  6577. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6578. }
  6579. if(options.initialFrameHeight){
  6580. options.minFrameHeight = options.initialFrameHeight
  6581. }else{
  6582. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6583. }
  6584. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6585. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6586. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6587. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6588. container.style.zIndex = options.zIndex;
  6589. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6590. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6591. '<style type=\'text/css\'>' +
  6592. //设置四周的留边
  6593. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6594. //设置默认字体和字号
  6595. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6596. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6597. //设置段落间距
  6598. 'p{margin:5px 0;}</style>' +
  6599. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6600. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6601. '</head><body class=\'view\' ></body>' +
  6602. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6603. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6604. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6605. container.appendChild(domUtils.createElement(document, 'iframe', {
  6606. id: 'ueditor_' + me.uid,
  6607. width: "100%",
  6608. height: "100%",
  6609. frameborder: "0",
  6610. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6611. // scrolling :'no',
  6612. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6613. 'document.write("' + html + '");document.close();}())'
  6614. }));
  6615. container.style.overflow = 'hidden';
  6616. //解决如果是给定的百分比,会导致高度算不对的问题
  6617. setTimeout(function(){
  6618. if( /%$/.test(options.initialFrameWidth)){
  6619. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6620. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6621. // container.style.width = options.initialFrameWidth + 'px';
  6622. }
  6623. if(/%$/.test(options.initialFrameHeight)){
  6624. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6625. container.style.height = options.initialFrameHeight + 'px';
  6626. }
  6627. })
  6628. }
  6629. },
  6630. /**
  6631. * 编辑器初始化
  6632. * @method _setup
  6633. * @private
  6634. * @param { Element } doc 编辑器Iframe中的文档对象
  6635. */
  6636. _setup: function (doc) {
  6637. var me = this,
  6638. options = me.options;
  6639. if (ie) {
  6640. doc.body.disabled = true;
  6641. doc.body.contentEditable = true;
  6642. doc.body.disabled = false;
  6643. } else {
  6644. doc.body.contentEditable = true;
  6645. }
  6646. doc.body.spellcheck = false;
  6647. me.document = doc;
  6648. me.window = doc.defaultView || doc.parentWindow;
  6649. me.iframe = me.window.frameElement;
  6650. me.body = doc.body;
  6651. me.selection = new dom.Selection(doc);
  6652. //gecko初始化就能得到range,无法判断isFocus了
  6653. var geckoSel;
  6654. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6655. geckoSel.removeAllRanges();
  6656. }
  6657. this._initEvents();
  6658. //为form提交提供一个隐藏的textarea
  6659. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6660. if (form.tagName == 'FORM') {
  6661. me.form = form;
  6662. if(me.options.autoSyncData){
  6663. domUtils.on(me.window,'blur',function(){
  6664. setValue(form,me);
  6665. });
  6666. }else{
  6667. domUtils.on(form, 'submit', function () {
  6668. setValue(this, me);
  6669. });
  6670. }
  6671. break;
  6672. }
  6673. }
  6674. if (options.initialContent) {
  6675. if (options.autoClearinitialContent) {
  6676. var oldExecCommand = me.execCommand;
  6677. me.execCommand = function () {
  6678. me.fireEvent('firstBeforeExecCommand');
  6679. return oldExecCommand.apply(me, arguments);
  6680. };
  6681. this._setDefaultContent(options.initialContent);
  6682. } else
  6683. this.setContent(options.initialContent, false, true);
  6684. }
  6685. //编辑器不能为空内容
  6686. if (domUtils.isEmptyNode(me.body)) {
  6687. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6688. }
  6689. //如果要求focus, 就把光标定位到内容开始
  6690. if (options.focus) {
  6691. setTimeout(function () {
  6692. me.focus(me.options.focusInEnd);
  6693. //如果自动清除开着,就不需要做selectionchange;
  6694. !me.options.autoClearinitialContent && me._selectionChange();
  6695. }, 0);
  6696. }
  6697. if (!me.container) {
  6698. me.container = this.iframe.parentNode;
  6699. }
  6700. if (options.fullscreen && me.ui) {
  6701. me.ui.setFullScreen(true);
  6702. }
  6703. try {
  6704. me.document.execCommand('2D-position', false, false);
  6705. } catch (e) {
  6706. }
  6707. try {
  6708. me.document.execCommand('enableInlineTableEditing', false, false);
  6709. } catch (e) {
  6710. }
  6711. try {
  6712. me.document.execCommand('enableObjectResizing', false, false);
  6713. } catch (e) {
  6714. }
  6715. //挂接快捷键
  6716. me._bindshortcutKeys();
  6717. me.isReady = 1;
  6718. me.fireEvent('ready');
  6719. options.onready && options.onready.call(me);
  6720. if (!browser.ie9below) {
  6721. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6722. //chrome下会出现alt+tab切换时,导致选区位置不对
  6723. if (e.type == 'blur') {
  6724. me._bakRange = me.selection.getRange();
  6725. try {
  6726. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6727. me.selection.getNative().removeAllRanges();
  6728. } catch (e) {
  6729. me._bakNativeRange = null;
  6730. }
  6731. } else {
  6732. try {
  6733. me._bakRange && me._bakRange.select();
  6734. } catch (e) {
  6735. }
  6736. }
  6737. });
  6738. }
  6739. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6740. if (browser.gecko && browser.version <= 10902) {
  6741. //修复ff3.6初始化进来,不能点击获得焦点
  6742. me.body.contentEditable = false;
  6743. setTimeout(function () {
  6744. me.body.contentEditable = true;
  6745. }, 100);
  6746. setInterval(function () {
  6747. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6748. }, 100)
  6749. }
  6750. !options.isShow && me.setHide();
  6751. options.readonly && me.setDisabled();
  6752. },
  6753. /**
  6754. * 同步数据到编辑器所在的form
  6755. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6756. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6757. * @method sync
  6758. * @example
  6759. * ```javascript
  6760. * editor.sync();
  6761. * form.sumbit(); //form变量已经指向了form元素
  6762. * ```
  6763. */
  6764. /**
  6765. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6766. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6767. * @method sync
  6768. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6769. */
  6770. sync: function (formId) {
  6771. var me = this,
  6772. form = formId ? document.getElementById(formId) :
  6773. domUtils.findParent(me.iframe.parentNode, function (node) {
  6774. return node.tagName == 'FORM'
  6775. }, true);
  6776. form && setValue(form, me);
  6777. },
  6778. /**
  6779. * 设置编辑器高度
  6780. * @method setHeight
  6781. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6782. * @param { Number } number 设置的高度值,纯数值,不带单位
  6783. * @example
  6784. * ```javascript
  6785. * editor.setHeight(number);
  6786. * ```
  6787. */
  6788. setHeight: function (height,notSetHeight) {
  6789. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6790. this.iframe.parentNode.style.height = height + 'px';
  6791. }
  6792. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6793. this.body.style.height = height + 'px';
  6794. !notSetHeight && this.trigger('setHeight')
  6795. },
  6796. /**
  6797. * 为编辑器的编辑命令提供快捷键
  6798. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6799. * @method addshortcutkey
  6800. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6801. * @example
  6802. * ```javascript
  6803. * editor.addshortcutkey({
  6804. * "Bold" : "ctrl+66",//^B
  6805. * "Italic" : "ctrl+73", //^I
  6806. * });
  6807. * ```
  6808. */
  6809. /**
  6810. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6811. * @method addshortcutkey
  6812. * @param { String } cmd 触发快捷键时,响应的命令
  6813. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6814. * @example
  6815. * ```javascript
  6816. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6817. * ```
  6818. */
  6819. addshortcutkey: function (cmd, keys) {
  6820. var obj = {};
  6821. if (keys) {
  6822. obj[cmd] = keys
  6823. } else {
  6824. obj = cmd;
  6825. }
  6826. utils.extend(this.shortcutkeys, obj)
  6827. },
  6828. /**
  6829. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6830. * @method _bindshortcutKeys
  6831. * @private
  6832. */
  6833. _bindshortcutKeys: function () {
  6834. var me = this, shortcutkeys = this.shortcutkeys;
  6835. me.addListener('keydown', function (type, e) {
  6836. var keyCode = e.keyCode || e.which;
  6837. for (var i in shortcutkeys) {
  6838. var tmp = shortcutkeys[i].split(',');
  6839. for (var t = 0, ti; ti = tmp[t++];) {
  6840. ti = ti.split(':');
  6841. var key = ti[0], param = ti[1];
  6842. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6843. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6844. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6845. && keyCode == RegExp.$3
  6846. ) ||
  6847. keyCode == RegExp.$1
  6848. ) {
  6849. if (me.queryCommandState(i,param) != -1)
  6850. me.execCommand(i, param);
  6851. domUtils.preventDefault(e);
  6852. }
  6853. }
  6854. }
  6855. }
  6856. });
  6857. },
  6858. /**
  6859. * 获取编辑器的内容
  6860. * @method getContent
  6861. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6862. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6863. * @example
  6864. * ```javascript
  6865. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6866. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6867. * ```
  6868. */
  6869. /**
  6870. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6871. * @method getContent
  6872. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6873. * 代表当前编辑器的内容是否空,
  6874. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6875. * 经过内置过滤规则处理后的内容。
  6876. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6877. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6878. * @return { String } 编辑器的内容字符串
  6879. * @example
  6880. * ```javascript
  6881. * // editor 是一个编辑器的实例
  6882. * var content = editor.getContent( function ( editor ) {
  6883. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6884. * } );
  6885. * ```
  6886. */
  6887. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6888. var me = this;
  6889. if (cmd && utils.isFunction(cmd)) {
  6890. fn = cmd;
  6891. cmd = '';
  6892. }
  6893. if (fn ? !fn() : !this.hasContents()) {
  6894. return '';
  6895. }
  6896. me.fireEvent('beforegetcontent');
  6897. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6898. me.filterOutputRule(root);
  6899. me.fireEvent('aftergetcontent', cmd,root);
  6900. return root.toHtml(formatter);
  6901. },
  6902. /**
  6903. * 取得完整的html代码,可以直接显示成完整的html文档
  6904. * @method getAllHtml
  6905. * @return { String } 编辑器的内容html文档字符串
  6906. * @eaxmple
  6907. * ```javascript
  6908. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6909. * ```
  6910. */
  6911. getAllHtml: function () {
  6912. var me = this,
  6913. headHtml = [],
  6914. html = '';
  6915. me.fireEvent('getAllHtml', headHtml);
  6916. if (browser.ie && browser.version > 8) {
  6917. var headHtmlForIE9 = '';
  6918. utils.each(me.document.styleSheets, function (si) {
  6919. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6920. });
  6921. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6922. headHtmlForIE9 += si.outerHTML;
  6923. });
  6924. }
  6925. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6926. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6927. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6928. },
  6929. /**
  6930. * 得到编辑器的纯文本内容,但会保留段落格式
  6931. * @method getPlainTxt
  6932. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6933. * @example
  6934. * ```javascript
  6935. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6936. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6937. * ```
  6938. */
  6939. getPlainTxt: function () {
  6940. var reg = new RegExp(domUtils.fillChar, 'g'),
  6941. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6942. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6943. .replace(/<br\/?>/gi, '\n')
  6944. .replace(/<[^>/]+>/g, '')
  6945. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6946. return dtd.$block[c] ? '\n' : b ? b : '';
  6947. });
  6948. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6949. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6950. },
  6951. /**
  6952. * 获取编辑器中的纯文本内容,没有段落格式
  6953. * @method getContentTxt
  6954. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6955. * @example
  6956. * ```javascript
  6957. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6958. * console.log(editor.getPlainTxt()); //输出:"12
  6959. * ```
  6960. */
  6961. getContentTxt: function () {
  6962. var reg = new RegExp(domUtils.fillChar, 'g');
  6963. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6964. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6965. },
  6966. /**
  6967. * 设置编辑器的内容,可修改编辑器当前的html内容
  6968. * @method setContent
  6969. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6970. * @warning 该方法会触发selectionchange事件
  6971. * @param { String } html 要插入的html内容
  6972. * @example
  6973. * ```javascript
  6974. * editor.getContent('<p>test</p>');
  6975. * ```
  6976. */
  6977. /**
  6978. * 设置编辑器的内容,可修改编辑器当前的html内容
  6979. * @method setContent
  6980. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6981. * @warning 该方法会触发selectionchange事件
  6982. * @param { String } html 要插入的html内容
  6983. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6984. * @example
  6985. * ```javascript
  6986. * //假设设置前的编辑器内容是 <p>old text</p>
  6987. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6988. * ```
  6989. */
  6990. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6991. var me = this;
  6992. me.fireEvent('beforesetcontent', html);
  6993. var root = UE.htmlparser(html);
  6994. me.filterInputRule(root);
  6995. html = root.toHtml();
  6996. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6997. function isCdataDiv(node){
  6998. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6999. }
  7000. //给文本或者inline节点套p标签
  7001. if (me.options.enterTag == 'p') {
  7002. var child = this.body.firstChild, tmpNode;
  7003. if (!child || child.nodeType == 1 &&
  7004. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7005. domUtils.isCustomeNode(child)
  7006. )
  7007. && child === this.body.lastChild) {
  7008. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7009. } else {
  7010. var p = me.document.createElement('p');
  7011. while (child) {
  7012. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7013. tmpNode = child.nextSibling;
  7014. p.appendChild(child);
  7015. child = tmpNode;
  7016. }
  7017. if (p.firstChild) {
  7018. if (!child) {
  7019. me.body.appendChild(p);
  7020. break;
  7021. } else {
  7022. child.parentNode.insertBefore(p, child);
  7023. p = me.document.createElement('p');
  7024. }
  7025. }
  7026. child = child.nextSibling;
  7027. }
  7028. }
  7029. }
  7030. me.fireEvent('aftersetcontent');
  7031. me.fireEvent('contentchange');
  7032. !notFireSelectionchange && me._selectionChange();
  7033. //清除保存的选区
  7034. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7035. //trace:1742 setContent后gecko能得到焦点问题
  7036. var geckoSel;
  7037. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7038. geckoSel.removeAllRanges();
  7039. }
  7040. if(me.options.autoSyncData){
  7041. me.form && setValue(me.form,me);
  7042. }
  7043. },
  7044. /**
  7045. * 让编辑器获得焦点,默认focus到编辑器头部
  7046. * @method focus
  7047. * @example
  7048. * ```javascript
  7049. * editor.focus()
  7050. * ```
  7051. */
  7052. /**
  7053. * 让编辑器获得焦点,toEnd确定focus位置
  7054. * @method focus
  7055. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7056. * @example
  7057. * ```javascript
  7058. * editor.focus(true)
  7059. * ```
  7060. */
  7061. focus: function (toEnd) {
  7062. try {
  7063. var me = this,
  7064. rng = me.selection.getRange();
  7065. if (toEnd) {
  7066. var node = me.body.lastChild;
  7067. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7068. if(domUtils.isEmptyBlock(node)){
  7069. rng.setStartAtFirst(node)
  7070. }else{
  7071. rng.setStartAtLast(node)
  7072. }
  7073. rng.collapse(true);
  7074. }
  7075. rng.setCursor(true);
  7076. } else {
  7077. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7078. var node = me.body.firstChild;
  7079. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7080. rng.setStartAtFirst(node).collapse(true);
  7081. }
  7082. }
  7083. rng.select(true);
  7084. }
  7085. this.fireEvent('focus selectionchange');
  7086. } catch (e) {
  7087. }
  7088. },
  7089. isFocus:function(){
  7090. return this.selection.isFocus();
  7091. },
  7092. blur:function(){
  7093. var sel = this.selection.getNative();
  7094. if(sel.empty && browser.ie){
  7095. var nativeRng = document.body.createTextRange();
  7096. nativeRng.moveToElementText(document.body);
  7097. nativeRng.collapse(true);
  7098. nativeRng.select();
  7099. sel.empty()
  7100. }else{
  7101. sel.removeAllRanges()
  7102. }
  7103. //this.fireEvent('blur selectionchange');
  7104. },
  7105. /**
  7106. * 初始化UE事件及部分事件代理
  7107. * @method _initEvents
  7108. * @private
  7109. */
  7110. _initEvents: function () {
  7111. var me = this,
  7112. doc = me.document,
  7113. win = me.window;
  7114. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7115. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7116. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7117. domUtils.on(me.body,'drop',function(e){
  7118. //阻止ff下默认的弹出新页面打开图片
  7119. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7120. me.fireEvent('contentchange')
  7121. });
  7122. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7123. //特殊键不触发selectionchange
  7124. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7125. return;
  7126. }
  7127. if (evt.button == 2)return;
  7128. me._selectionChange(250, evt);
  7129. });
  7130. },
  7131. /**
  7132. * 触发事件代理
  7133. * @method _proxyDomEvent
  7134. * @private
  7135. * @return { * } fireEvent的返回值
  7136. * @see UE.EventBase:fireEvent(String)
  7137. */
  7138. _proxyDomEvent: function (evt) {
  7139. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7140. return false;
  7141. }
  7142. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7143. return false;
  7144. }
  7145. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7146. },
  7147. /**
  7148. * 变化选区
  7149. * @method _selectionChange
  7150. * @private
  7151. */
  7152. _selectionChange: function (delay, evt) {
  7153. var me = this;
  7154. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7155. // if ( !me.selection.isFocus() ){
  7156. // return;
  7157. // }
  7158. var hackForMouseUp = false;
  7159. var mouseX, mouseY;
  7160. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7161. var range = this.selection.getRange();
  7162. if (!range.collapsed) {
  7163. hackForMouseUp = true;
  7164. mouseX = evt.clientX;
  7165. mouseY = evt.clientY;
  7166. }
  7167. }
  7168. clearTimeout(_selectionChangeTimer);
  7169. _selectionChangeTimer = setTimeout(function () {
  7170. if (!me.selection || !me.selection.getNative()) {
  7171. return;
  7172. }
  7173. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7174. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7175. var ieRange;
  7176. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7177. ieRange = me.document.body.createTextRange();
  7178. try {
  7179. ieRange.moveToPoint(mouseX, mouseY);
  7180. } catch (ex) {
  7181. ieRange = null;
  7182. }
  7183. }
  7184. var bakGetIERange;
  7185. if (ieRange) {
  7186. bakGetIERange = me.selection.getIERange;
  7187. me.selection.getIERange = function () {
  7188. return ieRange;
  7189. };
  7190. }
  7191. me.selection.cache();
  7192. if (bakGetIERange) {
  7193. me.selection.getIERange = bakGetIERange;
  7194. }
  7195. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7196. me.fireEvent('beforeselectionchange');
  7197. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7198. me.fireEvent('selectionchange', !!evt);
  7199. me.fireEvent('afterselectionchange');
  7200. me.selection.clear();
  7201. }
  7202. }, delay || 50);
  7203. },
  7204. /**
  7205. * 执行编辑命令
  7206. * @method _callCmdFn
  7207. * @private
  7208. * @param { String } fnName 函数名称
  7209. * @param { * } args 传给命令函数的参数
  7210. * @return { * } 返回命令函数运行的返回值
  7211. */
  7212. _callCmdFn: function (fnName, args) {
  7213. var cmdName = args[0].toLowerCase(),
  7214. cmd, cmdFn;
  7215. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7216. cmdFn = cmd && cmd[fnName];
  7217. //没有querycommandstate或者没有command的都默认返回0
  7218. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7219. return 0;
  7220. } else if (cmdFn) {
  7221. return cmdFn.apply(this, args);
  7222. }
  7223. },
  7224. /**
  7225. * 执行编辑命令cmdName,完成富文本编辑效果
  7226. * @method execCommand
  7227. * @param { String } cmdName 需要执行的命令
  7228. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7229. * @return { * } 返回命令函数运行的返回值
  7230. * @example
  7231. * ```javascript
  7232. * editor.execCommand(cmdName);
  7233. * ```
  7234. */
  7235. execCommand: function (cmdName) {
  7236. cmdName = cmdName.toLowerCase();
  7237. var me = this,
  7238. result,
  7239. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7240. if (!cmd || !cmd.execCommand) {
  7241. return null;
  7242. }
  7243. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7244. me.__hasEnterExecCommand = true;
  7245. if (me.queryCommandState.apply(me,arguments) != -1) {
  7246. me.fireEvent('saveScene');
  7247. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7248. result = this._callCmdFn('execCommand', arguments);
  7249. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7250. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7251. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7252. me.fireEvent('saveScene');
  7253. }
  7254. me.__hasEnterExecCommand = false;
  7255. } else {
  7256. result = this._callCmdFn('execCommand', arguments);
  7257. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7258. }
  7259. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7260. return result;
  7261. },
  7262. /**
  7263. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7264. * @method queryCommandState
  7265. * @param { String } cmdName 需要查询的命令名称
  7266. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7267. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7268. * @example
  7269. * ```javascript
  7270. * editor.queryCommandState(cmdName) => (-1|0|1)
  7271. * ```
  7272. * @see COMMAND.LIST
  7273. */
  7274. queryCommandState: function (cmdName) {
  7275. return this._callCmdFn('queryCommandState', arguments);
  7276. },
  7277. /**
  7278. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7279. * @method queryCommandValue
  7280. * @param { String } cmdName 需要查询的命令名称
  7281. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7282. * @remind 只有部分插件有此方法
  7283. * @return { * } 返回每个命令特定的当前状态值
  7284. * @grammar editor.queryCommandValue(cmdName) => {*}
  7285. * @see COMMAND.LIST
  7286. */
  7287. queryCommandValue: function (cmdName) {
  7288. return this._callCmdFn('queryCommandValue', arguments);
  7289. },
  7290. /**
  7291. * 检查编辑区域中是否有内容
  7292. * @method hasContents
  7293. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7294. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7295. * @return { Boolean } 检查有内容返回true,否则返回false
  7296. * @example
  7297. * ```javascript
  7298. * editor.hasContents()
  7299. * ```
  7300. */
  7301. /**
  7302. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7303. * @method hasContents
  7304. * @param { Array } tags 传入数组判断时用到的节点类型
  7305. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7306. * @example
  7307. * ```javascript
  7308. * editor.hasContents(['span']);
  7309. * ```
  7310. */
  7311. hasContents: function (tags) {
  7312. if (tags) {
  7313. for (var i = 0, ci; ci = tags[i++];) {
  7314. if (this.document.getElementsByTagName(ci).length > 0) {
  7315. return true;
  7316. }
  7317. }
  7318. }
  7319. if (!domUtils.isEmptyBlock(this.body)) {
  7320. return true
  7321. }
  7322. //随时添加,定义的特殊标签如果存在,不能认为是空
  7323. tags = ['div'];
  7324. for (i = 0; ci = tags[i++];) {
  7325. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7326. for (var n = 0, cn; cn = nodes[n++];) {
  7327. if (domUtils.isCustomeNode(cn)) {
  7328. return true;
  7329. }
  7330. }
  7331. }
  7332. return false;
  7333. },
  7334. /**
  7335. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7336. * @method reset
  7337. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7338. * @example
  7339. * ```javascript
  7340. * editor.reset()
  7341. * ```
  7342. */
  7343. reset: function () {
  7344. this.fireEvent('reset');
  7345. },
  7346. /**
  7347. * 设置当前编辑区域可以编辑
  7348. * @method setEnabled
  7349. * @example
  7350. * ```javascript
  7351. * editor.setEnabled()
  7352. * ```
  7353. */
  7354. setEnabled: function () {
  7355. var me = this, range;
  7356. if (me.body.contentEditable == 'false') {
  7357. me.body.contentEditable = true;
  7358. range = me.selection.getRange();
  7359. //有可能内容丢失了
  7360. try {
  7361. range.moveToBookmark(me.lastBk);
  7362. delete me.lastBk
  7363. } catch (e) {
  7364. range.setStartAtFirst(me.body).collapse(true)
  7365. }
  7366. range.select(true);
  7367. if (me.bkqueryCommandState) {
  7368. me.queryCommandState = me.bkqueryCommandState;
  7369. delete me.bkqueryCommandState;
  7370. }
  7371. if (me.bkqueryCommandValue) {
  7372. me.queryCommandValue = me.bkqueryCommandValue;
  7373. delete me.bkqueryCommandValue;
  7374. }
  7375. me.fireEvent('selectionchange');
  7376. }
  7377. },
  7378. enable: function () {
  7379. return this.setEnabled();
  7380. },
  7381. /** 设置当前编辑区域不可编辑
  7382. * @method setDisabled
  7383. */
  7384. /** 设置当前编辑区域不可编辑,except中的命令除外
  7385. * @method setDisabled
  7386. * @param { String } except 例外命令的字符串
  7387. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7388. * @example
  7389. * ```javascript
  7390. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7391. * ```
  7392. */
  7393. /** 设置当前编辑区域不可编辑,except中的命令除外
  7394. * @method setDisabled
  7395. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7396. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7397. * @example
  7398. * ```javascript
  7399. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7400. * ```
  7401. */
  7402. setDisabled: function (except) {
  7403. var me = this;
  7404. except = except ? utils.isArray(except) ? except : [except] : [];
  7405. if (me.body.contentEditable == 'true') {
  7406. if (!me.lastBk) {
  7407. me.lastBk = me.selection.getRange().createBookmark(true);
  7408. }
  7409. me.body.contentEditable = false;
  7410. me.bkqueryCommandState = me.queryCommandState;
  7411. me.bkqueryCommandValue = me.queryCommandValue;
  7412. me.queryCommandState = function (type) {
  7413. if (utils.indexOf(except, type) != -1) {
  7414. return me.bkqueryCommandState.apply(me, arguments);
  7415. }
  7416. return -1;
  7417. };
  7418. me.queryCommandValue = function (type) {
  7419. if (utils.indexOf(except, type) != -1) {
  7420. return me.bkqueryCommandValue.apply(me, arguments);
  7421. }
  7422. return null;
  7423. };
  7424. me.fireEvent('selectionchange');
  7425. }
  7426. },
  7427. disable: function (except) {
  7428. return this.setDisabled(except);
  7429. },
  7430. /**
  7431. * 设置默认内容
  7432. * @method _setDefaultContent
  7433. * @private
  7434. * @param { String } cont 要存入的内容
  7435. */
  7436. _setDefaultContent: function () {
  7437. function clear() {
  7438. var me = this;
  7439. if (me.document.getElementById('initContent')) {
  7440. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7441. me.removeListener('firstBeforeExecCommand focus', clear);
  7442. setTimeout(function () {
  7443. me.focus();
  7444. me._selectionChange();
  7445. }, 0)
  7446. }
  7447. }
  7448. return function (cont) {
  7449. var me = this;
  7450. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7451. me.addListener('firstBeforeExecCommand focus', clear);
  7452. }
  7453. }(),
  7454. /**
  7455. * 显示编辑器
  7456. * @method setShow
  7457. * @example
  7458. * ```javascript
  7459. * editor.setShow()
  7460. * ```
  7461. */
  7462. setShow: function () {
  7463. var me = this, range = me.selection.getRange();
  7464. if (me.container.style.display == 'none') {
  7465. //有可能内容丢失了
  7466. try {
  7467. range.moveToBookmark(me.lastBk);
  7468. delete me.lastBk
  7469. } catch (e) {
  7470. range.setStartAtFirst(me.body).collapse(true)
  7471. }
  7472. //ie下focus实效,所以做了个延迟
  7473. setTimeout(function () {
  7474. range.select(true);
  7475. }, 100);
  7476. me.container.style.display = '';
  7477. }
  7478. },
  7479. show: function () {
  7480. return this.setShow();
  7481. },
  7482. /**
  7483. * 隐藏编辑器
  7484. * @method setHide
  7485. * @example
  7486. * ```javascript
  7487. * editor.setHide()
  7488. * ```
  7489. */
  7490. setHide: function () {
  7491. var me = this;
  7492. if (!me.lastBk) {
  7493. me.lastBk = me.selection.getRange().createBookmark(true);
  7494. }
  7495. me.container.style.display = 'none'
  7496. },
  7497. hide: function () {
  7498. return this.setHide();
  7499. },
  7500. /**
  7501. * 根据指定的路径,获取对应的语言资源
  7502. * @method getLang
  7503. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7504. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7505. * @example
  7506. * ```javascript
  7507. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7508. * ```
  7509. */
  7510. getLang: function (path) {
  7511. // HaoChuan9421
  7512. if(!this.options){
  7513. return '';
  7514. }
  7515. var lang = UE.I18N[this.options.lang];
  7516. if (!lang) {
  7517. throw Error("not import language file");
  7518. }
  7519. path = (path || "").split(".");
  7520. for (var i = 0, ci; ci = path[i++];) {
  7521. lang = lang[ci];
  7522. if (!lang)break;
  7523. }
  7524. return lang;
  7525. },
  7526. /**
  7527. * 计算编辑器html内容字符串的长度
  7528. * @method getContentLength
  7529. * @return { Number } 返回计算的长度
  7530. * @example
  7531. * ```javascript
  7532. * //编辑器html内容<p><strong>132</strong></p>
  7533. * editor.getContentLength() //返回27
  7534. * ```
  7535. */
  7536. /**
  7537. * 计算编辑器当前纯文本内容的长度
  7538. * @method getContentLength
  7539. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7540. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7541. * @example
  7542. * ```javascript
  7543. * //编辑器html内容<p><strong>132</strong></p>
  7544. * editor.getContentLength() //返回3
  7545. * ```
  7546. */
  7547. getContentLength: function (ingoneHtml, tagNames) {
  7548. var count = this.getContent(false,false,true).length;
  7549. if (ingoneHtml) {
  7550. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7551. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7552. for (var i = 0, ci; ci = tagNames[i++];) {
  7553. count += this.document.getElementsByTagName(ci).length;
  7554. }
  7555. }
  7556. return count;
  7557. },
  7558. /**
  7559. * 注册输入过滤规则
  7560. * @method addInputRule
  7561. * @param { Function } rule 要添加的过滤规则
  7562. * @example
  7563. * ```javascript
  7564. * editor.addInputRule(function(root){
  7565. * $.each(root.getNodesByTagName('div'),function(i,node){
  7566. * node.tagName="p";
  7567. * });
  7568. * });
  7569. * ```
  7570. */
  7571. addInputRule: function (rule) {
  7572. this.inputRules.push(rule);
  7573. },
  7574. /**
  7575. * 执行注册的过滤规则
  7576. * @method filterInputRule
  7577. * @param { UE.uNode } root 要过滤的uNode节点
  7578. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7579. * @example
  7580. * ```javascript
  7581. * editor.filterInputRule(editor.body);
  7582. * ```
  7583. * @see UE.Editor:addInputRule
  7584. */
  7585. filterInputRule: function (root) {
  7586. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7587. ci.call(this, root)
  7588. }
  7589. },
  7590. /**
  7591. * 注册输出过滤规则
  7592. * @method addOutputRule
  7593. * @param { Function } rule 要添加的过滤规则
  7594. * @example
  7595. * ```javascript
  7596. * editor.addOutputRule(function(root){
  7597. * $.each(root.getNodesByTagName('p'),function(i,node){
  7598. * node.tagName="div";
  7599. * });
  7600. * });
  7601. * ```
  7602. */
  7603. addOutputRule: function (rule) {
  7604. this.outputRules.push(rule)
  7605. },
  7606. /**
  7607. * 根据输出过滤规则,过滤编辑器内容
  7608. * @method filterOutputRule
  7609. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7610. * @param { UE.uNode } root 要过滤的uNode节点
  7611. * @example
  7612. * ```javascript
  7613. * editor.filterOutputRule(editor.body);
  7614. * ```
  7615. * @see UE.Editor:addOutputRule
  7616. */
  7617. filterOutputRule: function (root) {
  7618. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7619. ci.call(this, root)
  7620. }
  7621. },
  7622. /**
  7623. * 根据action名称获取请求的路径
  7624. * @method getActionUrl
  7625. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7626. * @param { String } action action名称
  7627. * @example
  7628. * ```javascript
  7629. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7630. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7631. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7632. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7633. * ```
  7634. */
  7635. getActionUrl: function(action){
  7636. var actionName = this.getOpt(action) || action,
  7637. imageUrl = this.getOpt('imageUrl'),
  7638. serverUrl = this.getOpt('serverUrl');
  7639. if(!serverUrl && imageUrl) {
  7640. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7641. }
  7642. if(serverUrl) {
  7643. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&') + 'action=' + (actionName || '');
  7644. return utils.formatUrl(serverUrl);
  7645. } else {
  7646. return '';
  7647. }
  7648. }
  7649. };
  7650. utils.inherits(Editor, EventBase);
  7651. })();
  7652. // core/Editor.defaultoptions.js
  7653. //维护编辑器一下默认的不在插件中的配置项
  7654. UE.Editor.defaultOptions = function(editor){
  7655. var _url = editor.options.UEDITOR_HOME_URL;
  7656. return {
  7657. isShow: true,
  7658. initialContent: '',
  7659. initialStyle:'',
  7660. autoClearinitialContent: false,
  7661. iframeCssUrl: _url + 'themes/iframe.css',
  7662. textarea: 'editorValue',
  7663. focus: false,
  7664. focusInEnd: true,
  7665. autoClearEmptyNode: true,
  7666. fullscreen: false,
  7667. readonly: false,
  7668. zIndex: 999,
  7669. imagePopup: true,
  7670. enterTag: 'p',
  7671. customDomain: false,
  7672. lang: 'zh-cn',
  7673. langPath: _url + 'lang/',
  7674. theme: 'default',
  7675. themePath: _url + 'themes/',
  7676. allHtmlEnabled: false,
  7677. scaleEnabled: false,
  7678. tableNativeEditInFF: false,
  7679. autoSyncData : true,
  7680. fileNameFormat: '{time}{rand:6}'
  7681. }
  7682. };
  7683. // core/loadconfig.js
  7684. (function(){
  7685. UE.Editor.prototype.loadServerConfig = function(){
  7686. var me = this;
  7687. setTimeout(function(){
  7688. try{
  7689. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7690. var configUrl = me.getActionUrl('config'),
  7691. isJsonp = utils.isCrossDomainUrl(configUrl);
  7692. /* 发出ajax请求 */
  7693. me._serverConfigLoaded = false;
  7694. configUrl && UE.ajax.request(configUrl,{
  7695. 'method': 'GET',
  7696. 'dataType': isJsonp ? 'jsonp':'',
  7697. 'onsuccess':function(r){
  7698. try {
  7699. var config = isJsonp ? r:eval("("+r.responseText+")");
  7700. utils.extend(me.options, config);
  7701. me.fireEvent('serverConfigLoaded');
  7702. me._serverConfigLoaded = true;
  7703. } catch (e) {
  7704. showErrorMsg(me.getLang('loadconfigFormatError'));
  7705. }
  7706. },
  7707. 'onerror':function(){
  7708. showErrorMsg(me.getLang('loadconfigHttpError'));
  7709. }
  7710. });
  7711. } catch(e){
  7712. showErrorMsg(me.getLang('loadconfigError'));
  7713. }
  7714. });
  7715. function showErrorMsg(msg) {
  7716. console && console.error(msg);
  7717. //me.fireEvent('showMessage', {
  7718. // 'title': msg,
  7719. // 'type': 'error'
  7720. //});
  7721. }
  7722. };
  7723. UE.Editor.prototype.isServerConfigLoaded = function(){
  7724. var me = this;
  7725. return me._serverConfigLoaded || false;
  7726. };
  7727. UE.Editor.prototype.afterConfigReady = function(handler){
  7728. if (!handler || !utils.isFunction(handler)) return;
  7729. var me = this;
  7730. var readyHandler = function(){
  7731. handler.apply(me, arguments);
  7732. me.removeListener('serverConfigLoaded', readyHandler);
  7733. };
  7734. if (me.isServerConfigLoaded()) {
  7735. handler.call(me, 'serverConfigLoaded');
  7736. } else {
  7737. me.addListener('serverConfigLoaded', readyHandler);
  7738. }
  7739. };
  7740. })();
  7741. // core/ajax.js
  7742. /**
  7743. * @file
  7744. * @module UE.ajax
  7745. * @since 1.2.6.1
  7746. */
  7747. /**
  7748. * 提供对ajax请求的支持
  7749. * @module UE.ajax
  7750. */
  7751. UE.ajax = function() {
  7752. //创建一个ajaxRequest对象
  7753. var fnStr = 'XMLHttpRequest()';
  7754. try {
  7755. new ActiveXObject("Msxml2.XMLHTTP");
  7756. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7757. } catch (e) {
  7758. try {
  7759. new ActiveXObject("Microsoft.XMLHTTP");
  7760. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7761. } catch (e) {
  7762. }
  7763. }
  7764. var creatAjaxRequest = new Function('return new ' + fnStr);
  7765. /**
  7766. * 将json参数转化成适合ajax提交的参数列表
  7767. * @param json
  7768. */
  7769. function json2str(json) {
  7770. var strArr = [];
  7771. for (var i in json) {
  7772. //忽略默认的几个参数
  7773. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7774. //忽略控制
  7775. if(json[i] == undefined || json[i] == null) continue;
  7776. //传递过来的对象和函数不在提交之列
  7777. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7778. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7779. } else if (utils.isArray(json[i])) {
  7780. //支持传数组内容
  7781. for(var j = 0; j < json[i].length; j++) {
  7782. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7783. }
  7784. }
  7785. }
  7786. return strArr.join("&");
  7787. }
  7788. function doAjax(url, ajaxOptions) {
  7789. var xhr = creatAjaxRequest(),
  7790. //是否超时
  7791. timeIsOut = false,
  7792. //默认参数
  7793. defaultAjaxOptions = {
  7794. method:"POST",
  7795. timeout:5000,
  7796. async:true,
  7797. data:{},//需要传递对象的话只能覆盖
  7798. onsuccess:function() {
  7799. },
  7800. onerror:function() {
  7801. }
  7802. };
  7803. if (typeof url === "object") {
  7804. ajaxOptions = url;
  7805. url = ajaxOptions.url;
  7806. }
  7807. if (!xhr || !url) return;
  7808. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7809. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7810. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7811. if (!utils.isEmptyObject(ajaxOpts.data)){
  7812. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7813. }
  7814. //超时检测
  7815. var timerID = setTimeout(function() {
  7816. if (xhr.readyState != 4) {
  7817. timeIsOut = true;
  7818. xhr.abort();
  7819. clearTimeout(timerID);
  7820. }
  7821. }, ajaxOpts.timeout);
  7822. var method = ajaxOpts.method.toUpperCase();
  7823. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7824. xhr.open(method, str, ajaxOpts.async);
  7825. xhr.onreadystatechange = function() {
  7826. if (xhr.readyState == 4) {
  7827. if (!timeIsOut && xhr.status == 200) {
  7828. ajaxOpts.onsuccess(xhr);
  7829. } else {
  7830. ajaxOpts.onerror(xhr);
  7831. }
  7832. }
  7833. };
  7834. if (method == "POST") {
  7835. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7836. xhr.send(submitStr);
  7837. } else {
  7838. xhr.send(null);
  7839. }
  7840. }
  7841. function doJsonp(url, opts) {
  7842. var successhandler = opts.onsuccess || function(){},
  7843. scr = document.createElement('SCRIPT'),
  7844. options = opts || {},
  7845. charset = options['charset'],
  7846. callbackField = options['jsonp'] || 'callback',
  7847. callbackFnName,
  7848. timeOut = options['timeOut'] || 0,
  7849. timer,
  7850. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7851. matches;
  7852. if (utils.isFunction(successhandler)) {
  7853. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7854. window[callbackFnName] = getCallBack(0);
  7855. } else if(utils.isString(successhandler)){
  7856. callbackFnName = successhandler;
  7857. } else {
  7858. if (matches = reg.exec(url)) {
  7859. callbackFnName = matches[2];
  7860. }
  7861. }
  7862. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7863. if (url.search(reg) < 0) {
  7864. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7865. }
  7866. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7867. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7868. if (!utils.isEmptyObject(opts.data)){
  7869. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7870. }
  7871. if (queryStr) {
  7872. url = url.replace(/\?/, '?' + queryStr + '&');
  7873. }
  7874. scr.onerror = getCallBack(1);
  7875. if( timeOut ){
  7876. timer = setTimeout(getCallBack(1), timeOut);
  7877. }
  7878. createScriptTag(scr, url, charset);
  7879. function createScriptTag(scr, url, charset) {
  7880. scr.setAttribute('type', 'text/javascript');
  7881. scr.setAttribute('defer', 'defer');
  7882. charset && scr.setAttribute('charset', charset);
  7883. scr.setAttribute('src', url);
  7884. document.getElementsByTagName('head')[0].appendChild(scr);
  7885. }
  7886. function getCallBack(onTimeOut){
  7887. return function(){
  7888. try {
  7889. if(onTimeOut){
  7890. options.onerror && options.onerror();
  7891. }else{
  7892. try{
  7893. clearTimeout(timer);
  7894. successhandler.apply(window, arguments);
  7895. } catch (e){}
  7896. }
  7897. } catch (exception) {
  7898. options.onerror && options.onerror.call(window, exception);
  7899. } finally {
  7900. options.oncomplete && options.oncomplete.apply(window, arguments);
  7901. scr.parentNode && scr.parentNode.removeChild(scr);
  7902. window[callbackFnName] = null;
  7903. try {
  7904. delete window[callbackFnName];
  7905. }catch(e){}
  7906. }
  7907. }
  7908. }
  7909. }
  7910. return {
  7911. /**
  7912. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7913. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7914. * @method request
  7915. * @param { URLString } url ajax请求的url地址
  7916. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7917. * @example
  7918. * ```javascript
  7919. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7920. * UE.ajax.requeset( 'sayhello.php', {
  7921. *
  7922. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7923. * method: 'GET',
  7924. *
  7925. * //超时时间。 默认为5000, 单位是ms
  7926. * timeout: 10000,
  7927. *
  7928. * //是否是异步请求。 true为异步请求, false为同步请求
  7929. * async: true,
  7930. *
  7931. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7932. * data: {
  7933. * name: 'ueditor'
  7934. * },
  7935. *
  7936. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7937. * onsuccess: function ( xhr ) {
  7938. * console.log( xhr.responseText );
  7939. * },
  7940. *
  7941. * //请求失败或者超时后的回调。
  7942. * onerror: function ( xhr ) {
  7943. * alert( 'Ajax请求失败' );
  7944. * }
  7945. *
  7946. * } );
  7947. * ```
  7948. */
  7949. /**
  7950. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7951. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7952. * @method request
  7953. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7954. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7955. * @example
  7956. * ```javascript
  7957. *
  7958. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7959. * UE.ajax.requeset( 'sayhello.php', {
  7960. *
  7961. * //请求的地址, 该项是必须的。
  7962. * url: 'sayhello.php'
  7963. *
  7964. * } );
  7965. * ```
  7966. */
  7967. request:function(url, opts) {
  7968. if (opts && opts.dataType == 'jsonp') {
  7969. doJsonp(url, opts);
  7970. } else {
  7971. doAjax(url, opts);
  7972. }
  7973. },
  7974. getJSONP:function(url, data, fn) {
  7975. var opts = {
  7976. 'data': data,
  7977. 'oncomplete': fn
  7978. };
  7979. doJsonp(url, opts);
  7980. }
  7981. };
  7982. }();
  7983. // core/filterword.js
  7984. /**
  7985. * UE过滤word的静态方法
  7986. * @file
  7987. */
  7988. /**
  7989. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7990. * @module UE
  7991. */
  7992. /**
  7993. * 根据传入html字符串过滤word
  7994. * @module UE
  7995. * @since 1.2.6.1
  7996. * @method filterWord
  7997. * @param { String } html html字符串
  7998. * @return { String } 已过滤后的结果字符串
  7999. * @example
  8000. * ```javascript
  8001. * UE.filterWord(html);
  8002. * ```
  8003. */
  8004. var filterWord = UE.filterWord = function () {
  8005. //是否是word过来的内容
  8006. function isWordDocument( str ) {
  8007. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  8008. }
  8009. //去掉小数
  8010. function transUnit( v ) {
  8011. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  8012. return utils.transUnitToPx(m);
  8013. } );
  8014. return v;
  8015. }
  8016. function filterPasteWord( str ) {
  8017. return str.replace(/[\t\r\n]+/g,' ')
  8018. .replace( /<!--[\s\S]*?-->/ig, "" )
  8019. //转换图片
  8020. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  8021. //opera能自己解析出image所这里直接返回空
  8022. if(browser.opera){
  8023. return '';
  8024. }
  8025. try{
  8026. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8027. if(/Bitmap/i.test(str)){
  8028. return '';
  8029. }
  8030. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8031. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8032. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8033. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  8034. } catch(e){
  8035. return '';
  8036. }
  8037. })
  8038. //针对wps添加的多余标签处理
  8039. .replace(/<\/?div[^>]*>/g,'')
  8040. //去掉多余的属性
  8041. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8042. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8043. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8044. //去掉多余的属性
  8045. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8046. //保留list的标示
  8047. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8048. })
  8049. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8050. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8051. return c.replace(/[\t\r\n ]+/g,' ')
  8052. })
  8053. //处理style的问题
  8054. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8055. var n = [],
  8056. s = style.replace( /^\s+|\s+$/, '' )
  8057. .replace(/&#39;/g,'\'')
  8058. .replace( /&quot;/gi, "'" )
  8059. .replace(/[\d.]+(cm|pt)/g,function(str){
  8060. return utils.transUnitToPx(str)
  8061. })
  8062. .split( /;\s*/g );
  8063. for ( var i = 0,v; v = s[i];i++ ) {
  8064. var name, value,
  8065. parts = v.split( ":" );
  8066. if ( parts.length == 2 ) {
  8067. name = parts[0].toLowerCase();
  8068. value = parts[1].toLowerCase();
  8069. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8070. ||
  8071. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8072. ){
  8073. continue;
  8074. }
  8075. switch ( name ) {
  8076. case "mso-padding-alt":
  8077. case "mso-padding-top-alt":
  8078. case "mso-padding-right-alt":
  8079. case "mso-padding-bottom-alt":
  8080. case "mso-padding-left-alt":
  8081. case "mso-margin-alt":
  8082. case "mso-margin-top-alt":
  8083. case "mso-margin-right-alt":
  8084. case "mso-margin-bottom-alt":
  8085. case "mso-margin-left-alt":
  8086. //ie下会出现挤到一起的情况
  8087. //case "mso-table-layout-alt":
  8088. case "mso-height":
  8089. case "mso-width":
  8090. case "mso-vertical-align-alt":
  8091. //trace:1819 ff下会解析出padding在table上
  8092. if(!/<table/.test(tag))
  8093. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8094. continue;
  8095. case "horiz-align":
  8096. n[i] = "text-align:" + value;
  8097. continue;
  8098. case "vert-align":
  8099. n[i] = "vertical-align:" + value;
  8100. continue;
  8101. case "font-color":
  8102. case "mso-foreground":
  8103. n[i] = "color:" + value;
  8104. continue;
  8105. case "mso-background":
  8106. case "mso-highlight":
  8107. n[i] = "background:" + value;
  8108. continue;
  8109. case "mso-default-height":
  8110. n[i] = "min-height:" + transUnit( value );
  8111. continue;
  8112. case "mso-default-width":
  8113. n[i] = "min-width:" + transUnit( value );
  8114. continue;
  8115. case "mso-padding-between-alt":
  8116. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8117. continue;
  8118. case "text-line-through":
  8119. if ( (value == "single") || (value == "double") ) {
  8120. n[i] = "text-decoration:line-through";
  8121. }
  8122. continue;
  8123. case "mso-zero-height":
  8124. if ( value == "yes" ) {
  8125. n[i] = "display:none";
  8126. }
  8127. continue;
  8128. // case 'background':
  8129. // break;
  8130. case 'margin':
  8131. if ( !/[1-9]/.test( value ) ) {
  8132. continue;
  8133. }
  8134. }
  8135. 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 )
  8136. ||
  8137. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8138. ) {
  8139. continue;
  8140. }
  8141. n[i] = name + ":" + parts[1];
  8142. }
  8143. }
  8144. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8145. })
  8146. }
  8147. return function ( html ) {
  8148. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8149. };
  8150. }();
  8151. // core/node.js
  8152. /**
  8153. * 编辑器模拟的节点类
  8154. * @file
  8155. * @module UE
  8156. * @class uNode
  8157. * @since 1.2.6.1
  8158. */
  8159. /**
  8160. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8161. * @unfile
  8162. * @module UE
  8163. */
  8164. (function () {
  8165. /**
  8166. * 编辑器模拟的节点类
  8167. * @unfile
  8168. * @module UE
  8169. * @class uNode
  8170. */
  8171. /**
  8172. * 通过一个键值对,创建一个uNode对象
  8173. * @constructor
  8174. * @param { Object } attr 传入要创建的uNode的初始属性
  8175. * @example
  8176. * ```javascript
  8177. * var node = new uNode({
  8178. * type:'element',
  8179. * tagName:'span',
  8180. * attrs:{style:'font-size:14px;'}
  8181. * }
  8182. * ```
  8183. */
  8184. var uNode = UE.uNode = function (obj) {
  8185. this.type = obj.type;
  8186. this.data = obj.data;
  8187. this.tagName = obj.tagName;
  8188. this.parentNode = obj.parentNode;
  8189. this.attrs = obj.attrs || {};
  8190. this.children = obj.children;
  8191. };
  8192. var notTransAttrs = {
  8193. 'href':1,
  8194. 'src':1,
  8195. '_src':1,
  8196. '_href':1,
  8197. 'cdata_data':1
  8198. };
  8199. var notTransTagName = {
  8200. style:1,
  8201. script:1
  8202. };
  8203. var indentChar = ' ',
  8204. breakChar = '\n';
  8205. function insertLine(arr, current, begin) {
  8206. arr.push(breakChar);
  8207. return current + (begin ? 1 : -1);
  8208. }
  8209. function insertIndent(arr, current) {
  8210. //插入缩进
  8211. for (var i = 0; i < current; i++) {
  8212. arr.push(indentChar);
  8213. }
  8214. }
  8215. //创建uNode的静态方法
  8216. //支持标签和html
  8217. uNode.createElement = function (html) {
  8218. if (/[<>]/.test(html)) {
  8219. return UE.htmlparser(html).children[0]
  8220. } else {
  8221. return new uNode({
  8222. type:'element',
  8223. children:[],
  8224. tagName:html
  8225. })
  8226. }
  8227. };
  8228. uNode.createText = function (data,noTrans) {
  8229. return new UE.uNode({
  8230. type:'text',
  8231. 'data':noTrans ? data : utils.unhtml(data || '')
  8232. })
  8233. };
  8234. function nodeToHtml(node, arr, formatter, current) {
  8235. switch (node.type) {
  8236. case 'root':
  8237. for (var i = 0, ci; ci = node.children[i++];) {
  8238. //插入新行
  8239. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8240. insertLine(arr, current, true);
  8241. insertIndent(arr, current)
  8242. }
  8243. nodeToHtml(ci, arr, formatter, current)
  8244. }
  8245. break;
  8246. case 'text':
  8247. isText(node, arr);
  8248. break;
  8249. case 'element':
  8250. isElement(node, arr, formatter, current);
  8251. break;
  8252. case 'comment':
  8253. isComment(node, arr, formatter);
  8254. }
  8255. return arr;
  8256. }
  8257. function isText(node, arr) {
  8258. if(node.parentNode.tagName == 'pre'){
  8259. //源码模式下输入html标签,不能做转换处理,直接输出
  8260. arr.push(node.data)
  8261. }else{
  8262. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8263. }
  8264. }
  8265. function isElement(node, arr, formatter, current) {
  8266. var attrhtml = '';
  8267. if (node.attrs) {
  8268. attrhtml = [];
  8269. var attrs = node.attrs;
  8270. for (var a in attrs) {
  8271. //这里就针对
  8272. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8273. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8274. //有可能做的不够
  8275. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8276. return '&quot;'
  8277. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8278. }
  8279. attrhtml = attrhtml.join(' ');
  8280. }
  8281. arr.push('<' + node.tagName +
  8282. (attrhtml ? ' ' + attrhtml : '') +
  8283. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8284. );
  8285. //插入新行
  8286. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8287. if(node.children && node.children.length){
  8288. current = insertLine(arr, current, true);
  8289. insertIndent(arr, current)
  8290. }
  8291. }
  8292. if (node.children && node.children.length) {
  8293. for (var i = 0, ci; ci = node.children[i++];) {
  8294. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8295. insertLine(arr, current);
  8296. insertIndent(arr, current)
  8297. }
  8298. nodeToHtml(ci, arr, formatter, current)
  8299. }
  8300. }
  8301. if (!dtd.$empty[node.tagName]) {
  8302. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8303. if(node.children && node.children.length){
  8304. current = insertLine(arr, current);
  8305. insertIndent(arr, current)
  8306. }
  8307. }
  8308. arr.push('<\/' + node.tagName + '>');
  8309. }
  8310. }
  8311. function isComment(node, arr) {
  8312. arr.push('<!--' + node.data + '-->');
  8313. }
  8314. function getNodeById(root, id) {
  8315. var node;
  8316. if (root.type == 'element' && root.getAttr('id') == id) {
  8317. return root;
  8318. }
  8319. if (root.children && root.children.length) {
  8320. for (var i = 0, ci; ci = root.children[i++];) {
  8321. if (node = getNodeById(ci, id)) {
  8322. return node;
  8323. }
  8324. }
  8325. }
  8326. }
  8327. function getNodesByTagName(node, tagName, arr) {
  8328. if (node.type == 'element' && node.tagName == tagName) {
  8329. arr.push(node);
  8330. }
  8331. if (node.children && node.children.length) {
  8332. for (var i = 0, ci; ci = node.children[i++];) {
  8333. getNodesByTagName(ci, tagName, arr)
  8334. }
  8335. }
  8336. }
  8337. function nodeTraversal(root,fn){
  8338. if(root.children && root.children.length){
  8339. for(var i= 0,ci;ci=root.children[i];){
  8340. nodeTraversal(ci,fn);
  8341. //ci被替换的情况,这里就不再走 fn了
  8342. if(ci.parentNode ){
  8343. if(ci.children && ci.children.length){
  8344. fn(ci)
  8345. }
  8346. if(ci.parentNode) i++
  8347. }
  8348. }
  8349. }else{
  8350. fn(root)
  8351. }
  8352. }
  8353. uNode.prototype = {
  8354. /**
  8355. * 当前节点对象,转换成html文本
  8356. * @method toHtml
  8357. * @return { String } 返回转换后的html字符串
  8358. * @example
  8359. * ```javascript
  8360. * node.toHtml();
  8361. * ```
  8362. */
  8363. /**
  8364. * 当前节点对象,转换成html文本
  8365. * @method toHtml
  8366. * @param { Boolean } formatter 是否格式化返回值
  8367. * @return { String } 返回转换后的html字符串
  8368. * @example
  8369. * ```javascript
  8370. * node.toHtml( true );
  8371. * ```
  8372. */
  8373. toHtml:function (formatter) {
  8374. var arr = [];
  8375. nodeToHtml(this, arr, formatter, 0);
  8376. return arr.join('')
  8377. },
  8378. /**
  8379. * 获取节点的html内容
  8380. * @method innerHTML
  8381. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8382. * @return { String } 返回节点的html内容
  8383. * @example
  8384. * ```javascript
  8385. * var htmlstr = node.innerHTML();
  8386. * ```
  8387. */
  8388. /**
  8389. * 设置节点的html内容
  8390. * @method innerHTML
  8391. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8392. * @param { String } htmlstr 传入要设置的html内容
  8393. * @return { UE.uNode } 返回节点本身
  8394. * @example
  8395. * ```javascript
  8396. * node.innerHTML('<span>text</span>');
  8397. * ```
  8398. */
  8399. innerHTML:function (htmlstr) {
  8400. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8401. return this;
  8402. }
  8403. if (utils.isString(htmlstr)) {
  8404. if(this.children){
  8405. for (var i = 0, ci; ci = this.children[i++];) {
  8406. ci.parentNode = null;
  8407. }
  8408. }
  8409. this.children = [];
  8410. var tmpRoot = UE.htmlparser(htmlstr);
  8411. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8412. this.children.push(ci);
  8413. ci.parentNode = this;
  8414. }
  8415. return this;
  8416. } else {
  8417. var tmpRoot = new UE.uNode({
  8418. type:'root',
  8419. children:this.children
  8420. });
  8421. return tmpRoot.toHtml();
  8422. }
  8423. },
  8424. /**
  8425. * 获取节点的纯文本内容
  8426. * @method innerText
  8427. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8428. * @return { String } 返回节点的存文本内容
  8429. * @example
  8430. * ```javascript
  8431. * var textStr = node.innerText();
  8432. * ```
  8433. */
  8434. /**
  8435. * 设置节点的纯文本内容
  8436. * @method innerText
  8437. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8438. * @param { String } textStr 传入要设置的文本内容
  8439. * @return { UE.uNode } 返回节点本身
  8440. * @example
  8441. * ```javascript
  8442. * node.innerText('<span>text</span>');
  8443. * ```
  8444. */
  8445. innerText:function (textStr,noTrans) {
  8446. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8447. return this;
  8448. }
  8449. if (textStr) {
  8450. if(this.children){
  8451. for (var i = 0, ci; ci = this.children[i++];) {
  8452. ci.parentNode = null;
  8453. }
  8454. }
  8455. this.children = [];
  8456. this.appendChild(uNode.createText(textStr,noTrans));
  8457. return this;
  8458. } else {
  8459. return this.toHtml().replace(/<[^>]+>/g, '');
  8460. }
  8461. },
  8462. /**
  8463. * 获取当前对象的data属性
  8464. * @method getData
  8465. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8466. * @example
  8467. * ```javascript
  8468. * node.getData();
  8469. * ```
  8470. */
  8471. getData:function () {
  8472. if (this.type == 'element')
  8473. return '';
  8474. return this.data
  8475. },
  8476. /**
  8477. * 获取当前节点下的第一个子节点
  8478. * @method firstChild
  8479. * @return { UE.uNode } 返回第一个子节点
  8480. * @example
  8481. * ```javascript
  8482. * node.firstChild(); //返回第一个子节点
  8483. * ```
  8484. */
  8485. firstChild:function () {
  8486. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8487. // return this;
  8488. // }
  8489. return this.children ? this.children[0] : null;
  8490. },
  8491. /**
  8492. * 获取当前节点下的最后一个子节点
  8493. * @method lastChild
  8494. * @return { UE.uNode } 返回最后一个子节点
  8495. * @example
  8496. * ```javascript
  8497. * node.lastChild(); //返回最后一个子节点
  8498. * ```
  8499. */
  8500. lastChild:function () {
  8501. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8502. // return this;
  8503. // }
  8504. return this.children ? this.children[this.children.length - 1] : null;
  8505. },
  8506. /**
  8507. * 获取和当前节点有相同父亲节点的前一个节点
  8508. * @method previousSibling
  8509. * @return { UE.uNode } 返回前一个节点
  8510. * @example
  8511. * ```javascript
  8512. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8513. * ```
  8514. */
  8515. previousSibling : function(){
  8516. var parent = this.parentNode;
  8517. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8518. if (ci === this) {
  8519. return i == 0 ? null : parent.children[i-1];
  8520. }
  8521. }
  8522. },
  8523. /**
  8524. * 获取和当前节点有相同父亲节点的后一个节点
  8525. * @method nextSibling
  8526. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8527. * @example
  8528. * ```javascript
  8529. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8530. * ```
  8531. */
  8532. nextSibling : function(){
  8533. var parent = this.parentNode;
  8534. for (var i = 0, ci; ci = parent.children[i++];) {
  8535. if (ci === this) {
  8536. return parent.children[i];
  8537. }
  8538. }
  8539. },
  8540. /**
  8541. * 用新的节点替换当前节点
  8542. * @method replaceChild
  8543. * @param { UE.uNode } target 要替换成该节点参数
  8544. * @param { UE.uNode } source 要被替换掉的节点
  8545. * @return { UE.uNode } 返回替换之后的节点对象
  8546. * @example
  8547. * ```javascript
  8548. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8549. * ```
  8550. */
  8551. replaceChild:function (target, source) {
  8552. if (this.children) {
  8553. if(target.parentNode){
  8554. target.parentNode.removeChild(target);
  8555. }
  8556. for (var i = 0, ci; ci = this.children[i]; i++) {
  8557. if (ci === source) {
  8558. this.children.splice(i, 1, target);
  8559. source.parentNode = null;
  8560. target.parentNode = this;
  8561. return target;
  8562. }
  8563. }
  8564. }
  8565. },
  8566. /**
  8567. * 在节点的子节点列表最后位置插入一个节点
  8568. * @method appendChild
  8569. * @param { UE.uNode } node 要插入的节点
  8570. * @return { UE.uNode } 返回刚插入的子节点
  8571. * @example
  8572. * ```javascript
  8573. * node.appendChild( newNode ); //在node内插入子节点newNode
  8574. * ```
  8575. */
  8576. appendChild:function (node) {
  8577. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8578. if (!this.children) {
  8579. this.children = []
  8580. }
  8581. if(node.parentNode){
  8582. node.parentNode.removeChild(node);
  8583. }
  8584. for (var i = 0, ci; ci = this.children[i]; i++) {
  8585. if (ci === node) {
  8586. this.children.splice(i, 1);
  8587. break;
  8588. }
  8589. }
  8590. this.children.push(node);
  8591. node.parentNode = this;
  8592. return node;
  8593. }
  8594. },
  8595. /**
  8596. * 在传入节点的前面插入一个节点
  8597. * @method insertBefore
  8598. * @param { UE.uNode } target 要插入的节点
  8599. * @param { UE.uNode } source 在该参数节点前面插入
  8600. * @return { UE.uNode } 返回刚插入的子节点
  8601. * @example
  8602. * ```javascript
  8603. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8604. * ```
  8605. */
  8606. insertBefore:function (target, source) {
  8607. if (this.children) {
  8608. if(target.parentNode){
  8609. target.parentNode.removeChild(target);
  8610. }
  8611. for (var i = 0, ci; ci = this.children[i]; i++) {
  8612. if (ci === source) {
  8613. this.children.splice(i, 0, target);
  8614. target.parentNode = this;
  8615. return target;
  8616. }
  8617. }
  8618. }
  8619. },
  8620. /**
  8621. * 在传入节点的后面插入一个节点
  8622. * @method insertAfter
  8623. * @param { UE.uNode } target 要插入的节点
  8624. * @param { UE.uNode } source 在该参数节点后面插入
  8625. * @return { UE.uNode } 返回刚插入的子节点
  8626. * @example
  8627. * ```javascript
  8628. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8629. * ```
  8630. */
  8631. insertAfter:function (target, source) {
  8632. if (this.children) {
  8633. if(target.parentNode){
  8634. target.parentNode.removeChild(target);
  8635. }
  8636. for (var i = 0, ci; ci = this.children[i]; i++) {
  8637. if (ci === source) {
  8638. this.children.splice(i + 1, 0, target);
  8639. target.parentNode = this;
  8640. return target;
  8641. }
  8642. }
  8643. }
  8644. },
  8645. /**
  8646. * 从当前节点的子节点列表中,移除节点
  8647. * @method removeChild
  8648. * @param { UE.uNode } node 要移除的节点引用
  8649. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8650. * @return { * } 返回刚移除的子节点
  8651. * @example
  8652. * ```javascript
  8653. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8654. * ```
  8655. */
  8656. removeChild:function (node,keepChildren) {
  8657. if (this.children) {
  8658. for (var i = 0, ci; ci = this.children[i]; i++) {
  8659. if (ci === node) {
  8660. this.children.splice(i, 1);
  8661. ci.parentNode = null;
  8662. if(keepChildren && ci.children && ci.children.length){
  8663. for(var j= 0,cj;cj=ci.children[j];j++){
  8664. this.children.splice(i+j,0,cj);
  8665. cj.parentNode = this;
  8666. }
  8667. }
  8668. return ci;
  8669. }
  8670. }
  8671. }
  8672. },
  8673. /**
  8674. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8675. * @method getAttr
  8676. * @param { String } attrName 要获取的属性名称
  8677. * @return { * } 返回attrs对象下的属性值
  8678. * @example
  8679. * ```javascript
  8680. * node.getAttr('title');
  8681. * ```
  8682. */
  8683. getAttr:function (attrName) {
  8684. return this.attrs && this.attrs[attrName.toLowerCase()]
  8685. },
  8686. /**
  8687. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8688. * @method setAttr
  8689. * @param { String } attrName 要设置的属性名称
  8690. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8691. * @return { * } 返回attrs对象下的属性值
  8692. * @example
  8693. * ```javascript
  8694. * node.setAttr('title','标题');
  8695. * ```
  8696. */
  8697. setAttr:function (attrName, attrVal) {
  8698. if (!attrName) {
  8699. delete this.attrs;
  8700. return;
  8701. }
  8702. if(!this.attrs){
  8703. this.attrs = {};
  8704. }
  8705. if (utils.isObject(attrName)) {
  8706. for (var a in attrName) {
  8707. if (!attrName[a]) {
  8708. delete this.attrs[a]
  8709. } else {
  8710. this.attrs[a.toLowerCase()] = attrName[a];
  8711. }
  8712. }
  8713. } else {
  8714. if (!attrVal) {
  8715. delete this.attrs[attrName]
  8716. } else {
  8717. this.attrs[attrName.toLowerCase()] = attrVal;
  8718. }
  8719. }
  8720. },
  8721. /**
  8722. * 获取当前节点在父节点下的位置索引
  8723. * @method getIndex
  8724. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8725. * @example
  8726. * ```javascript
  8727. * node.getIndex();
  8728. * ```
  8729. */
  8730. getIndex:function(){
  8731. var parent = this.parentNode;
  8732. for(var i= 0,ci;ci=parent.children[i];i++){
  8733. if(ci === this){
  8734. return i;
  8735. }
  8736. }
  8737. return -1;
  8738. },
  8739. /**
  8740. * 在当前节点下,根据id查找节点
  8741. * @method getNodeById
  8742. * @param { String } id 要查找的id
  8743. * @return { UE.uNode } 返回找到的节点
  8744. * @example
  8745. * ```javascript
  8746. * node.getNodeById('textId');
  8747. * ```
  8748. */
  8749. getNodeById:function (id) {
  8750. var node;
  8751. if (this.children && this.children.length) {
  8752. for (var i = 0, ci; ci = this.children[i++];) {
  8753. if (node = getNodeById(ci, id)) {
  8754. return node;
  8755. }
  8756. }
  8757. }
  8758. },
  8759. /**
  8760. * 在当前节点下,根据元素名称查找节点列表
  8761. * @method getNodesByTagName
  8762. * @param { String } tagNames 要查找的元素名称
  8763. * @return { Array } 返回找到的节点列表
  8764. * @example
  8765. * ```javascript
  8766. * node.getNodesByTagName('span');
  8767. * ```
  8768. */
  8769. getNodesByTagName:function (tagNames) {
  8770. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8771. var arr = [], me = this;
  8772. utils.each(tagNames, function (tagName) {
  8773. if (me.children && me.children.length) {
  8774. for (var i = 0, ci; ci = me.children[i++];) {
  8775. getNodesByTagName(ci, tagName, arr)
  8776. }
  8777. }
  8778. });
  8779. return arr;
  8780. },
  8781. /**
  8782. * 根据样式名称,获取节点的样式值
  8783. * @method getStyle
  8784. * @param { String } name 要获取的样式名称
  8785. * @return { String } 返回样式值
  8786. * @example
  8787. * ```javascript
  8788. * node.getStyle('font-size');
  8789. * ```
  8790. */
  8791. getStyle:function (name) {
  8792. var cssStyle = this.getAttr('style');
  8793. if (!cssStyle) {
  8794. return ''
  8795. }
  8796. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8797. var match = cssStyle.match(reg);
  8798. if (match && match[0]) {
  8799. return match[2]
  8800. }
  8801. return '';
  8802. },
  8803. /**
  8804. * 给节点设置样式
  8805. * @method setStyle
  8806. * @param { String } name 要设置的的样式名称
  8807. * @param { String } val 要设置的的样值
  8808. * @example
  8809. * ```javascript
  8810. * node.setStyle('font-size', '12px');
  8811. * ```
  8812. */
  8813. setStyle:function (name, val) {
  8814. function exec(name, val) {
  8815. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8816. cssStyle = cssStyle.replace(reg, '$1');
  8817. if (val) {
  8818. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8819. }
  8820. }
  8821. var cssStyle = this.getAttr('style');
  8822. if (!cssStyle) {
  8823. cssStyle = '';
  8824. }
  8825. if (utils.isObject(name)) {
  8826. for (var a in name) {
  8827. exec(a, name[a])
  8828. }
  8829. } else {
  8830. exec(name, val)
  8831. }
  8832. this.setAttr('style', utils.trim(cssStyle))
  8833. },
  8834. /**
  8835. * 传入一个函数,递归遍历当前节点下的所有节点
  8836. * @method traversal
  8837. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8838. * @example
  8839. * ```javascript
  8840. * traversal(node, function(){
  8841. * console.log(node.type);
  8842. * });
  8843. * ```
  8844. */
  8845. traversal:function(fn){
  8846. if(this.children && this.children.length){
  8847. nodeTraversal(this,fn);
  8848. }
  8849. return this;
  8850. }
  8851. }
  8852. })();
  8853. // core/htmlparser.js
  8854. /**
  8855. * html字符串转换成uNode节点
  8856. * @file
  8857. * @module UE
  8858. * @since 1.2.6.1
  8859. */
  8860. /**
  8861. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8862. * @unfile
  8863. * @module UE
  8864. */
  8865. /**
  8866. * html字符串转换成uNode节点的静态方法
  8867. * @method htmlparser
  8868. * @param { String } htmlstr 要转换的html代码
  8869. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8870. * @return { uNode } 给定的html片段转换形成的uNode对象
  8871. * @example
  8872. * ```javascript
  8873. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8874. * ```
  8875. */
  8876. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8877. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8878. //先去掉了,加上的原因忘了,这里先记录
  8879. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8880. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8881. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8882. var allowEmptyTags = {
  8883. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8884. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8885. };
  8886. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8887. if(!ignoreBlank){
  8888. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8889. //br暂时单独处理
  8890. if(b && allowEmptyTags[b.toLowerCase()]){
  8891. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8892. }
  8893. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8894. });
  8895. }
  8896. var notTransAttrs = {
  8897. 'href':1,
  8898. 'src':1
  8899. };
  8900. var uNode = UE.uNode,
  8901. needParentNode = {
  8902. 'td':'tr',
  8903. 'tr':['tbody','thead','tfoot'],
  8904. 'tbody':'table',
  8905. 'th':'tr',
  8906. 'thead':'table',
  8907. 'tfoot':'table',
  8908. 'caption':'table',
  8909. 'li':['ul', 'ol'],
  8910. 'dt':'dl',
  8911. 'dd':'dl',
  8912. 'option':'select'
  8913. },
  8914. needChild = {
  8915. 'ol':'li',
  8916. 'ul':'li'
  8917. };
  8918. function text(parent, data) {
  8919. if(needChild[parent.tagName]){
  8920. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8921. parent.appendChild(tmpNode);
  8922. tmpNode.appendChild(uNode.createText(data));
  8923. parent = tmpNode;
  8924. }else{
  8925. parent.appendChild(uNode.createText(data));
  8926. }
  8927. }
  8928. function element(parent, tagName, htmlattr) {
  8929. var needParentTag;
  8930. if (needParentTag = needParentNode[tagName]) {
  8931. var tmpParent = parent,hasParent;
  8932. while(tmpParent.type != 'root'){
  8933. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8934. parent = tmpParent;
  8935. hasParent = true;
  8936. break;
  8937. }
  8938. tmpParent = tmpParent.parentNode;
  8939. }
  8940. if(!hasParent){
  8941. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8942. }
  8943. }
  8944. //按dtd处理嵌套
  8945. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8946. // parent = parent.parentNode;
  8947. var elm = new uNode({
  8948. parentNode:parent,
  8949. type:'element',
  8950. tagName:tagName.toLowerCase(),
  8951. //是自闭合的处理一下
  8952. children:dtd.$empty[tagName] ? null : []
  8953. });
  8954. //如果属性存在,处理属性
  8955. if (htmlattr) {
  8956. var attrs = {}, match;
  8957. while (match = re_attr.exec(htmlattr)) {
  8958. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8959. }
  8960. elm.attrs = attrs;
  8961. }
  8962. //trace:3970
  8963. // //如果parent下不能放elm
  8964. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8965. // parent = parent.parentNode;
  8966. // elm.parentNode = parent;
  8967. // }
  8968. parent.children.push(elm);
  8969. //如果是自闭合节点返回父亲节点
  8970. return dtd.$empty[tagName] ? parent : elm
  8971. }
  8972. function comment(parent, data) {
  8973. parent.children.push(new uNode({
  8974. type:'comment',
  8975. data:data,
  8976. parentNode:parent
  8977. }));
  8978. }
  8979. var match, currentIndex = 0, nextIndex = 0;
  8980. //设置根节点
  8981. var root = new uNode({
  8982. type:'root',
  8983. children:[]
  8984. });
  8985. var currentParent = root;
  8986. while (match = re_tag.exec(htmlstr)) {
  8987. currentIndex = match.index;
  8988. try{
  8989. if (currentIndex > nextIndex) {
  8990. //text node
  8991. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8992. }
  8993. if (match[3]) {
  8994. if(dtd.$cdata[currentParent.tagName]){
  8995. text(currentParent, match[0]);
  8996. }else{
  8997. //start tag
  8998. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8999. }
  9000. } else if (match[1]) {
  9001. if(currentParent.type != 'root'){
  9002. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  9003. text(currentParent, match[0]);
  9004. }else{
  9005. var tmpParent = currentParent;
  9006. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  9007. currentParent = currentParent.parentNode;
  9008. if(currentParent.type == 'root'){
  9009. currentParent = tmpParent;
  9010. throw 'break'
  9011. }
  9012. }
  9013. //end tag
  9014. currentParent = currentParent.parentNode;
  9015. }
  9016. }
  9017. } else if (match[2]) {
  9018. //comment
  9019. comment(currentParent, match[2])
  9020. }
  9021. }catch(e){}
  9022. nextIndex = re_tag.lastIndex;
  9023. }
  9024. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9025. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9026. if (nextIndex < htmlstr.length) {
  9027. text(currentParent, htmlstr.slice(nextIndex));
  9028. }
  9029. return root;
  9030. };
  9031. // core/filternode.js
  9032. /**
  9033. * UE过滤节点的静态方法
  9034. * @file
  9035. */
  9036. /**
  9037. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9038. * @module UE
  9039. */
  9040. /**
  9041. * 根据传入节点和过滤规则过滤相应节点
  9042. * @module UE
  9043. * @since 1.2.6.1
  9044. * @method filterNode
  9045. * @param { Object } root 指定root节点
  9046. * @param { Object } rules 过滤规则json对象
  9047. * @example
  9048. * ```javascript
  9049. * UE.filterNode(root,editor.options.filterRules);
  9050. * ```
  9051. */
  9052. var filterNode = UE.filterNode = function () {
  9053. function filterNode(node,rules){
  9054. switch (node.type) {
  9055. case 'text':
  9056. break;
  9057. case 'element':
  9058. var val;
  9059. if(val = rules[node.tagName]){
  9060. if(val === '-'){
  9061. node.parentNode.removeChild(node)
  9062. }else if(utils.isFunction(val)){
  9063. var parentNode = node.parentNode,
  9064. index = node.getIndex();
  9065. val(node);
  9066. if(node.parentNode){
  9067. if(node.children){
  9068. for(var i = 0,ci;ci=node.children[i];){
  9069. filterNode(ci,rules);
  9070. if(ci.parentNode){
  9071. i++;
  9072. }
  9073. }
  9074. }
  9075. }else{
  9076. for(var i = index,ci;ci=parentNode.children[i];){
  9077. filterNode(ci,rules);
  9078. if(ci.parentNode){
  9079. i++;
  9080. }
  9081. }
  9082. }
  9083. }else{
  9084. var attrs = val['$'];
  9085. if(attrs && node.attrs){
  9086. var tmpAttrs = {},tmpVal;
  9087. for(var a in attrs){
  9088. tmpVal = node.getAttr(a);
  9089. //todo 只先对style单独处理
  9090. if(a == 'style' && utils.isArray(attrs[a])){
  9091. var tmpCssStyle = [];
  9092. utils.each(attrs[a],function(v){
  9093. var tmp;
  9094. if(tmp = node.getStyle(v)){
  9095. tmpCssStyle.push(v + ':' + tmp);
  9096. }
  9097. });
  9098. tmpVal = tmpCssStyle.join(';')
  9099. }
  9100. if(tmpVal){
  9101. tmpAttrs[a] = tmpVal;
  9102. }
  9103. }
  9104. node.attrs = tmpAttrs;
  9105. }
  9106. if(node.children){
  9107. for(var i = 0,ci;ci=node.children[i];){
  9108. filterNode(ci,rules);
  9109. if(ci.parentNode){
  9110. i++;
  9111. }
  9112. }
  9113. }
  9114. }
  9115. }else{
  9116. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9117. if(dtd.$cdata[node.tagName]){
  9118. node.parentNode.removeChild(node)
  9119. }else{
  9120. var parentNode = node.parentNode,
  9121. index = node.getIndex();
  9122. node.parentNode.removeChild(node,true);
  9123. for(var i = index,ci;ci=parentNode.children[i];){
  9124. filterNode(ci,rules);
  9125. if(ci.parentNode){
  9126. i++;
  9127. }
  9128. }
  9129. }
  9130. }
  9131. break;
  9132. case 'comment':
  9133. node.parentNode.removeChild(node)
  9134. }
  9135. }
  9136. return function(root,rules){
  9137. if(utils.isEmptyObject(rules)){
  9138. return root;
  9139. }
  9140. var val;
  9141. if(val = rules['-']){
  9142. utils.each(val.split(' '),function(k){
  9143. rules[k] = '-'
  9144. })
  9145. }
  9146. for(var i= 0,ci;ci=root.children[i];){
  9147. filterNode(ci,rules);
  9148. if(ci.parentNode){
  9149. i++;
  9150. }
  9151. }
  9152. return root;
  9153. }
  9154. }();
  9155. // core/plugin.js
  9156. /**
  9157. * Created with JetBrains PhpStorm.
  9158. * User: campaign
  9159. * Date: 10/8/13
  9160. * Time: 6:15 PM
  9161. * To change this template use File | Settings | File Templates.
  9162. */
  9163. UE.plugin = function(){
  9164. var _plugins = {};
  9165. return {
  9166. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9167. if(oldOptionName && utils.isFunction(oldOptionName)){
  9168. afterDisabled = oldOptionName;
  9169. oldOptionName = null
  9170. }
  9171. _plugins[pluginName] = {
  9172. optionName : oldOptionName || pluginName,
  9173. execFn : fn,
  9174. //当插件被禁用时执行
  9175. afterDisabled : afterDisabled
  9176. }
  9177. },
  9178. load : function(editor){
  9179. utils.each(_plugins,function(plugin){
  9180. var _export = plugin.execFn.call(editor);
  9181. if(editor.options[plugin.optionName] !== false){
  9182. if(_export){
  9183. //后边需要再做扩展
  9184. utils.each(_export,function(v,k){
  9185. switch(k.toLowerCase()){
  9186. case 'shortcutkey':
  9187. editor.addshortcutkey(v);
  9188. break;
  9189. case 'bindevents':
  9190. utils.each(v,function(fn,eventName){
  9191. editor.addListener(eventName,fn);
  9192. });
  9193. break;
  9194. case 'bindmultievents':
  9195. utils.each(utils.isArray(v) ? v:[v],function(event){
  9196. var types = utils.trim(event.type).split(/\s+/);
  9197. utils.each(types,function(eventName){
  9198. editor.addListener(eventName, event.handler);
  9199. });
  9200. });
  9201. break;
  9202. case 'commands':
  9203. utils.each(v,function(execFn,execName){
  9204. editor.commands[execName] = execFn
  9205. });
  9206. break;
  9207. case 'outputrule':
  9208. editor.addOutputRule(v);
  9209. break;
  9210. case 'inputrule':
  9211. editor.addInputRule(v);
  9212. break;
  9213. case 'defaultoptions':
  9214. editor.setOpt(v)
  9215. }
  9216. })
  9217. }
  9218. }else if(plugin.afterDisabled){
  9219. plugin.afterDisabled.call(editor)
  9220. }
  9221. });
  9222. //向下兼容
  9223. utils.each(UE.plugins,function(plugin){
  9224. plugin.call(editor);
  9225. });
  9226. },
  9227. run : function(pluginName,editor){
  9228. var plugin = _plugins[pluginName];
  9229. if(plugin){
  9230. plugin.exeFn.call(editor)
  9231. }
  9232. }
  9233. }
  9234. }();
  9235. // core/keymap.js
  9236. var keymap = UE.keymap = {
  9237. 'Backspace' : 8,
  9238. 'Tab' : 9,
  9239. 'Enter' : 13,
  9240. 'Shift':16,
  9241. 'Control':17,
  9242. 'Alt':18,
  9243. 'CapsLock':20,
  9244. 'Esc':27,
  9245. 'Spacebar':32,
  9246. 'PageUp':33,
  9247. 'PageDown':34,
  9248. 'End':35,
  9249. 'Home':36,
  9250. 'Left':37,
  9251. 'Up':38,
  9252. 'Right':39,
  9253. 'Down':40,
  9254. 'Insert':45,
  9255. 'Del':46,
  9256. 'NumLock':144,
  9257. 'Cmd':91,
  9258. '=':187,
  9259. '-':189,
  9260. "b":66,
  9261. 'i':73,
  9262. //回退
  9263. 'z':90,
  9264. 'y':89,
  9265. //粘贴
  9266. 'v' : 86,
  9267. 'x' : 88,
  9268. 's' : 83,
  9269. 'n' : 78
  9270. };
  9271. // core/localstorage.js
  9272. //存储媒介封装
  9273. var LocalStorage = UE.LocalStorage = (function () {
  9274. var storage = window.localStorage || getUserData() || null,
  9275. LOCAL_FILE = 'localStorage';
  9276. return {
  9277. saveLocalData: function (key, data) {
  9278. if (storage && data) {
  9279. storage.setItem(key, data);
  9280. return true;
  9281. }
  9282. return false;
  9283. },
  9284. getLocalData: function (key) {
  9285. if (storage) {
  9286. return storage.getItem(key);
  9287. }
  9288. return null;
  9289. },
  9290. removeItem: function (key) {
  9291. storage && storage.removeItem(key);
  9292. }
  9293. };
  9294. function getUserData() {
  9295. var container = document.createElement("div");
  9296. container.style.display = "none";
  9297. if (!container.addBehavior) {
  9298. return null;
  9299. }
  9300. container.addBehavior("#default#userdata");
  9301. return {
  9302. getItem: function (key) {
  9303. var result = null;
  9304. try {
  9305. document.body.appendChild(container);
  9306. container.load(LOCAL_FILE);
  9307. result = container.getAttribute(key);
  9308. document.body.removeChild(container);
  9309. } catch (e) {
  9310. }
  9311. return result;
  9312. },
  9313. setItem: function (key, value) {
  9314. document.body.appendChild(container);
  9315. container.setAttribute(key, value);
  9316. container.save(LOCAL_FILE);
  9317. document.body.removeChild(container);
  9318. },
  9319. //// 暂时没有用到
  9320. //clear: function () {
  9321. //
  9322. // var expiresTime = new Date();
  9323. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9324. // document.body.appendChild(container);
  9325. // container.expires = expiresTime.toUTCString();
  9326. // container.save(LOCAL_FILE);
  9327. // document.body.removeChild(container);
  9328. //
  9329. //},
  9330. removeItem: function (key) {
  9331. document.body.appendChild(container);
  9332. container.removeAttribute(key);
  9333. container.save(LOCAL_FILE);
  9334. document.body.removeChild(container);
  9335. }
  9336. };
  9337. }
  9338. })();
  9339. (function () {
  9340. var ROOTKEY = 'ueditor_preference';
  9341. UE.Editor.prototype.setPreferences = function(key,value){
  9342. var obj = {};
  9343. if (utils.isString(key)) {
  9344. obj[ key ] = value;
  9345. } else {
  9346. obj = key;
  9347. }
  9348. var data = LocalStorage.getLocalData(ROOTKEY);
  9349. if (data && (data = utils.str2json(data))) {
  9350. utils.extend(data, obj);
  9351. } else {
  9352. data = obj;
  9353. }
  9354. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9355. };
  9356. UE.Editor.prototype.getPreferences = function(key){
  9357. var data = LocalStorage.getLocalData(ROOTKEY);
  9358. if (data && (data = utils.str2json(data))) {
  9359. return key ? data[key] : data
  9360. }
  9361. return null;
  9362. };
  9363. UE.Editor.prototype.removePreferences = function (key) {
  9364. var data = LocalStorage.getLocalData(ROOTKEY);
  9365. if (data && (data = utils.str2json(data))) {
  9366. data[key] = undefined;
  9367. delete data[key]
  9368. }
  9369. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9370. };
  9371. })();
  9372. // plugins/defaultfilter.js
  9373. ///import core
  9374. ///plugin 编辑器默认的过滤转换机制
  9375. UE.plugins['defaultfilter'] = function () {
  9376. var me = this;
  9377. me.setOpt({
  9378. 'allowDivTransToP':true,
  9379. 'disabledTableInTable':true
  9380. });
  9381. //默认的过滤处理
  9382. //进入编辑器的内容处理
  9383. me.addInputRule(function (root) {
  9384. var allowDivTransToP = this.options.allowDivTransToP;
  9385. var val;
  9386. function tdParent(node){
  9387. while(node && node.type == 'element'){
  9388. if(node.tagName == 'td'){
  9389. return true;
  9390. }
  9391. node = node.parentNode;
  9392. }
  9393. return false;
  9394. }
  9395. //进行默认的处理
  9396. root.traversal(function (node) {
  9397. if (node.type == 'element') {
  9398. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9399. if (!node.firstChild()) node.parentNode.removeChild(node);
  9400. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9401. node.parentNode.removeChild(node, true)
  9402. }
  9403. return;
  9404. }
  9405. switch (node.tagName) {
  9406. case 'style':
  9407. case 'script':
  9408. node.setAttr({
  9409. cdata_tag: node.tagName,
  9410. cdata_data: (node.innerHTML() || ''),
  9411. '_ue_custom_node_':'true'
  9412. });
  9413. node.tagName = 'div';
  9414. node.innerHTML('');
  9415. break;
  9416. case 'a':
  9417. if (val = node.getAttr('href')) {
  9418. node.setAttr('_href', val)
  9419. }
  9420. break;
  9421. case 'img':
  9422. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9423. if (val = node.getAttr('src')) {
  9424. if (/^data:/.test(val)) {
  9425. node.parentNode.removeChild(node);
  9426. break;
  9427. }
  9428. }
  9429. node.setAttr('_src', node.getAttr('src'));
  9430. break;
  9431. case 'span':
  9432. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9433. if (/nowrap|normal/.test(val)) {
  9434. node.setStyle('white-space', '');
  9435. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9436. node.parentNode.removeChild(node, true)
  9437. }
  9438. }
  9439. }
  9440. val = node.getAttr('id');
  9441. if(val && /^_baidu_bookmark_/i.test(val)){
  9442. node.parentNode.removeChild(node)
  9443. }
  9444. break;
  9445. case 'p':
  9446. if (val = node.getAttr('align')) {
  9447. node.setAttr('align');
  9448. node.setStyle('text-align', val)
  9449. }
  9450. //trace:3431
  9451. // var cssStyle = node.getAttr('style');
  9452. // if (cssStyle) {
  9453. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9454. // node.setAttr('style', cssStyle)
  9455. //
  9456. // }
  9457. //p标签不允许嵌套
  9458. utils.each(node.children,function(n){
  9459. if(n.type == 'element' && n.tagName == 'p'){
  9460. var next = n.nextSibling();
  9461. node.parentNode.insertAfter(n,node);
  9462. var last = n;
  9463. while(next){
  9464. var tmp = next.nextSibling();
  9465. node.parentNode.insertAfter(next,last);
  9466. last = next;
  9467. next = tmp;
  9468. }
  9469. return false;
  9470. }
  9471. });
  9472. if (!node.firstChild()) {
  9473. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9474. }
  9475. break;
  9476. case 'div':
  9477. if(node.getAttr('cdata_tag')){
  9478. break;
  9479. }
  9480. //针对代码这里不处理插入代码的div
  9481. val = node.getAttr('class');
  9482. if(val && /^line number\d+/.test(val)){
  9483. break;
  9484. }
  9485. if(!allowDivTransToP){
  9486. break;
  9487. }
  9488. var tmpNode, p = UE.uNode.createElement('p');
  9489. while (tmpNode = node.firstChild()) {
  9490. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9491. p.appendChild(tmpNode);
  9492. } else {
  9493. if (p.firstChild()) {
  9494. node.parentNode.insertBefore(p, node);
  9495. p = UE.uNode.createElement('p');
  9496. } else {
  9497. node.parentNode.insertBefore(tmpNode, node);
  9498. }
  9499. }
  9500. }
  9501. if (p.firstChild()) {
  9502. node.parentNode.insertBefore(p, node);
  9503. }
  9504. node.parentNode.removeChild(node);
  9505. break;
  9506. case 'dl':
  9507. node.tagName = 'ul';
  9508. break;
  9509. case 'dt':
  9510. case 'dd':
  9511. node.tagName = 'li';
  9512. break;
  9513. case 'li':
  9514. var className = node.getAttr('class');
  9515. if (!className || !/list\-/.test(className)) {
  9516. node.setAttr()
  9517. }
  9518. var tmpNodes = node.getNodesByTagName('ol ul');
  9519. UE.utils.each(tmpNodes, function (n) {
  9520. node.parentNode.insertAfter(n, node);
  9521. });
  9522. break;
  9523. case 'td':
  9524. case 'th':
  9525. case 'caption':
  9526. if(!node.children || !node.children.length){
  9527. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9528. }
  9529. break;
  9530. case 'table':
  9531. if(me.options.disabledTableInTable && tdParent(node)){
  9532. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9533. node.parentNode.removeChild(node)
  9534. }
  9535. }
  9536. }
  9537. // if(node.type == 'comment'){
  9538. // node.parentNode.removeChild(node);
  9539. // }
  9540. })
  9541. });
  9542. //从编辑器出去的内容处理
  9543. me.addOutputRule(function (root) {
  9544. var val;
  9545. root.traversal(function (node) {
  9546. if (node.type == 'element') {
  9547. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9548. if (!node.firstChild()) node.parentNode.removeChild(node);
  9549. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9550. node.parentNode.removeChild(node, true)
  9551. }
  9552. return;
  9553. }
  9554. switch (node.tagName) {
  9555. case 'div':
  9556. if (val = node.getAttr('cdata_tag')) {
  9557. node.tagName = val;
  9558. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9559. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9560. }
  9561. break;
  9562. case 'a':
  9563. if (val = node.getAttr('_href')) {
  9564. node.setAttr({
  9565. 'href': utils.html(val),
  9566. '_href': ''
  9567. })
  9568. }
  9569. break;
  9570. break;
  9571. case 'span':
  9572. val = node.getAttr('id');
  9573. if(val && /^_baidu_bookmark_/i.test(val)){
  9574. node.parentNode.removeChild(node)
  9575. }
  9576. break;
  9577. case 'img':
  9578. if (val = node.getAttr('_src')) {
  9579. node.setAttr({
  9580. 'src': node.getAttr('_src'),
  9581. '_src': ''
  9582. })
  9583. }
  9584. }
  9585. }
  9586. })
  9587. });
  9588. };
  9589. // plugins/inserthtml.js
  9590. /**
  9591. * 插入html字符串插件
  9592. * @file
  9593. * @since 1.2.6.1
  9594. */
  9595. /**
  9596. * 插入html代码
  9597. * @command inserthtml
  9598. * @method execCommand
  9599. * @param { String } cmd 命令字符串
  9600. * @param { String } html 插入的html字符串
  9601. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9602. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9603. * @example
  9604. * ```javascript
  9605. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9606. * //执行命令,插入<b>CC</b>
  9607. * //插入后的效果 xxx<b>CC</b>xxx
  9608. * //<p>xx|xxx</p> 当前选区为闭合状态
  9609. * //插入<p>CC</p>
  9610. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9611. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9612. * //插入 xxxx
  9613. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9614. * ```
  9615. */
  9616. UE.commands['inserthtml'] = {
  9617. execCommand: function (command,html,notNeedFilter){
  9618. var me = this,
  9619. range,
  9620. div;
  9621. if(!html){
  9622. return;
  9623. }
  9624. if(me.fireEvent('beforeinserthtml',html) === true){
  9625. return;
  9626. }
  9627. range = me.selection.getRange();
  9628. div = range.document.createElement( 'div' );
  9629. div.style.display = 'inline';
  9630. if (!notNeedFilter) {
  9631. var root = UE.htmlparser(html);
  9632. //如果给了过滤规则就先进行过滤
  9633. if(me.options.filterRules){
  9634. UE.filterNode(root,me.options.filterRules);
  9635. }
  9636. //执行默认的处理
  9637. me.filterInputRule(root);
  9638. html = root.toHtml()
  9639. }
  9640. div.innerHTML = utils.trim( html );
  9641. if ( !range.collapsed ) {
  9642. var tmpNode = range.startContainer;
  9643. if(domUtils.isFillChar(tmpNode)){
  9644. range.setStartBefore(tmpNode)
  9645. }
  9646. tmpNode = range.endContainer;
  9647. if(domUtils.isFillChar(tmpNode)){
  9648. range.setEndAfter(tmpNode)
  9649. }
  9650. range.txtToElmBoundary();
  9651. //结束边界可能放到了br的前边,要把br包含进来
  9652. // x[xxx]<br/>
  9653. if(range.endContainer && range.endContainer.nodeType == 1){
  9654. tmpNode = range.endContainer.childNodes[range.endOffset];
  9655. if(tmpNode && domUtils.isBr(tmpNode)){
  9656. range.setEndAfter(tmpNode);
  9657. }
  9658. }
  9659. if(range.startOffset == 0){
  9660. tmpNode = range.startContainer;
  9661. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9662. tmpNode = range.endContainer;
  9663. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9664. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9665. range.setStart(me.body.firstChild,0).collapse(true)
  9666. }
  9667. }
  9668. }
  9669. !range.collapsed && range.deleteContents();
  9670. if(range.startContainer.nodeType == 1){
  9671. var child = range.startContainer.childNodes[range.startOffset],pre;
  9672. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9673. range.setEnd(pre,pre.childNodes.length).collapse();
  9674. while(child.firstChild){
  9675. pre.appendChild(child.firstChild);
  9676. }
  9677. domUtils.remove(child);
  9678. }
  9679. }
  9680. }
  9681. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9682. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9683. if(range.inFillChar()){
  9684. child = range.startContainer;
  9685. if(domUtils.isFillChar(child)){
  9686. range.setStartBefore(child).collapse(true);
  9687. domUtils.remove(child);
  9688. }else if(domUtils.isFillChar(child,true)){
  9689. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9690. range.startOffset--;
  9691. range.collapsed && range.collapse(true)
  9692. }
  9693. }
  9694. //列表单独处理
  9695. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9696. if(li){
  9697. var next,last;
  9698. while(child = div.firstChild){
  9699. //针对hr单独处理一下先
  9700. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9701. next = child.nextSibling;
  9702. range.insertNode( child).collapse();
  9703. last = child;
  9704. child = next;
  9705. }
  9706. if(child){
  9707. if(/^(ol|ul)$/i.test(child.tagName)){
  9708. while(child.firstChild){
  9709. last = child.firstChild;
  9710. domUtils.insertAfter(li,child.firstChild);
  9711. li = li.nextSibling;
  9712. }
  9713. domUtils.remove(child)
  9714. }else{
  9715. var tmpLi;
  9716. next = child.nextSibling;
  9717. tmpLi = me.document.createElement('li');
  9718. domUtils.insertAfter(li,tmpLi);
  9719. tmpLi.appendChild(child);
  9720. last = child;
  9721. child = next;
  9722. li = tmpLi;
  9723. }
  9724. }
  9725. }
  9726. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9727. if(domUtils.isEmptyBlock(li)){
  9728. domUtils.remove(li)
  9729. }
  9730. if(last){
  9731. range.setStartAfter(last).collapse(true).select(true)
  9732. }
  9733. }else{
  9734. while ( child = div.firstChild ) {
  9735. if(hadBreak){
  9736. var p = me.document.createElement('p');
  9737. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9738. nextNode = child.nextSibling;
  9739. p.appendChild(child);
  9740. child = nextNode;
  9741. }
  9742. if(p.firstChild){
  9743. child = p
  9744. }
  9745. }
  9746. range.insertNode( child );
  9747. nextNode = child.nextSibling;
  9748. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9749. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9750. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9751. if(!dtd[parent.tagName][child.nodeName]){
  9752. pre = parent;
  9753. }else{
  9754. tmp = child.parentNode;
  9755. while (tmp !== parent){
  9756. pre = tmp;
  9757. tmp = tmp.parentNode;
  9758. }
  9759. }
  9760. domUtils.breakParent( child, pre || tmp );
  9761. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9762. var pre = child.previousSibling;
  9763. domUtils.trimWhiteTextNode(pre);
  9764. if(!pre.childNodes.length){
  9765. domUtils.remove(pre);
  9766. }
  9767. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9768. if(!browser.ie &&
  9769. (next = child.nextSibling) &&
  9770. domUtils.isBlockElm(next) &&
  9771. next.lastChild &&
  9772. !domUtils.isBr(next.lastChild)){
  9773. next.appendChild(me.document.createElement('br'));
  9774. }
  9775. hadBreak = 1;
  9776. }
  9777. }
  9778. var next = child.nextSibling;
  9779. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9780. range.setStart(next,0).collapse(true);
  9781. break;
  9782. }
  9783. range.setEndAfter( child ).collapse();
  9784. }
  9785. child = range.startContainer;
  9786. if(nextNode && domUtils.isBr(nextNode)){
  9787. domUtils.remove(nextNode)
  9788. }
  9789. //用chrome可能有空白展位符
  9790. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9791. if(nextNode = child.nextSibling){
  9792. domUtils.remove(child);
  9793. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9794. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9795. }
  9796. }else{
  9797. try{
  9798. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9799. }catch(e){
  9800. range.setStartBefore(child);
  9801. domUtils.remove(child)
  9802. }
  9803. }
  9804. }
  9805. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9806. try{
  9807. range.select(true);
  9808. }catch(e){}
  9809. }
  9810. setTimeout(function(){
  9811. range = me.selection.getRange();
  9812. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9813. me.fireEvent('afterinserthtml', html);
  9814. },200);
  9815. }
  9816. };
  9817. // plugins/autotypeset.js
  9818. /**
  9819. * 自动排版
  9820. * @file
  9821. * @since 1.2.6.1
  9822. */
  9823. /**
  9824. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9825. * @command autotypeset
  9826. * @method execCommand
  9827. * @param { String } cmd 命令字符串
  9828. * @example
  9829. * ```javascript
  9830. * editor.execCommand( 'autotypeset' );
  9831. * ```
  9832. */
  9833. UE.plugins['autotypeset'] = function(){
  9834. this.setOpt({'autotypeset': {
  9835. mergeEmptyline: true, //合并空行
  9836. removeClass: true, //去掉冗余的class
  9837. removeEmptyline: false, //去掉空行
  9838. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9839. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9840. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9841. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9842. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9843. removeEmptyNode: false, // 去掉空节点
  9844. //可以去掉的标签
  9845. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9846. indent: false, // 行首缩进
  9847. indentValue : '2em', //行首缩进的大小
  9848. bdc2sb: false,
  9849. tobdc: false
  9850. }});
  9851. var me = this,
  9852. opt = me.options.autotypeset,
  9853. remainClass = {
  9854. 'selectTdClass':1,
  9855. 'pagebreak':1,
  9856. 'anchorclass':1
  9857. },
  9858. remainTag = {
  9859. 'li':1
  9860. },
  9861. tags = {
  9862. div:1,
  9863. p:1,
  9864. //trace:2183 这些也认为是行
  9865. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9866. span:1
  9867. },
  9868. highlightCont;
  9869. //升级了版本,但配置项目里没有autotypeset
  9870. if(!opt){
  9871. return;
  9872. }
  9873. readLocalOpts();
  9874. function isLine(node,notEmpty){
  9875. if(!node || node.nodeType == 3)
  9876. return 0;
  9877. if(domUtils.isBr(node))
  9878. return 1;
  9879. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9880. if(highlightCont && highlightCont.contains(node)
  9881. ||
  9882. node.getAttribute('pagebreak')
  9883. ){
  9884. return 0;
  9885. }
  9886. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9887. +']','g'));
  9888. }
  9889. }
  9890. function removeNotAttributeSpan(node){
  9891. if(!node.style.cssText){
  9892. domUtils.removeAttributes(node,['style']);
  9893. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9894. domUtils.remove(node,true);
  9895. }
  9896. }
  9897. }
  9898. function autotype(type,html){
  9899. var me = this,cont;
  9900. if(html){
  9901. if(!opt.pasteFilter){
  9902. return;
  9903. }
  9904. cont = me.document.createElement('div');
  9905. cont.innerHTML = html.html;
  9906. }else{
  9907. cont = me.document.body;
  9908. }
  9909. var nodes = domUtils.getElementsByTagName(cont,'*');
  9910. // 行首缩进,段落方向,段间距,段内间距
  9911. for(var i=0,ci;ci=nodes[i++];){
  9912. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9913. continue;
  9914. }
  9915. //font-size
  9916. if(opt.clearFontSize && ci.style.fontSize){
  9917. domUtils.removeStyle(ci,'font-size');
  9918. removeNotAttributeSpan(ci);
  9919. }
  9920. //font-family
  9921. if(opt.clearFontFamily && ci.style.fontFamily){
  9922. domUtils.removeStyle(ci,'font-family');
  9923. removeNotAttributeSpan(ci);
  9924. }
  9925. if(isLine(ci)){
  9926. //合并空行
  9927. if(opt.mergeEmptyline ){
  9928. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9929. while(isLine(next)){
  9930. tmpNode = next;
  9931. next = tmpNode.nextSibling;
  9932. if(isBr && (!next || next && !domUtils.isBr(next))){
  9933. break;
  9934. }
  9935. domUtils.remove(tmpNode);
  9936. }
  9937. }
  9938. //去掉空行,保留占位的空行
  9939. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9940. if(domUtils.isBr(ci)){
  9941. next = ci.nextSibling;
  9942. if(next && !domUtils.isBr(next)){
  9943. continue;
  9944. }
  9945. }
  9946. domUtils.remove(ci);
  9947. continue;
  9948. }
  9949. }
  9950. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9951. if(opt.indent){
  9952. ci.style.textIndent = opt.indentValue;
  9953. }
  9954. if(opt.textAlign){
  9955. ci.style.textAlign = opt.textAlign;
  9956. }
  9957. // if(opt.lineHeight)
  9958. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9959. }
  9960. //去掉class,保留的class不去掉
  9961. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9962. if(highlightCont && highlightCont.contains(ci)){
  9963. continue;
  9964. }
  9965. domUtils.removeAttributes(ci,['class']);
  9966. }
  9967. //表情不处理
  9968. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9969. if(html){
  9970. var img = ci;
  9971. switch (opt.imageBlockLine){
  9972. case 'left':
  9973. case 'right':
  9974. case 'none':
  9975. var pN = img.parentNode,tmpNode,pre,next;
  9976. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9977. pN = pN.parentNode;
  9978. }
  9979. tmpNode = pN;
  9980. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9981. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9982. pre = tmpNode.previousSibling;
  9983. next = tmpNode.nextSibling;
  9984. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9985. pre.appendChild(tmpNode.firstChild);
  9986. while(next.firstChild){
  9987. pre.appendChild(next.firstChild);
  9988. }
  9989. domUtils.remove(tmpNode);
  9990. domUtils.remove(next);
  9991. }else{
  9992. domUtils.setStyle(tmpNode,'text-align','');
  9993. }
  9994. }
  9995. }
  9996. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9997. break;
  9998. case 'center':
  9999. if(me.queryCommandValue('imagefloat') != 'center'){
  10000. pN = img.parentNode;
  10001. domUtils.setStyle(img,'float','none');
  10002. tmpNode = img;
  10003. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  10004. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  10005. tmpNode = pN;
  10006. pN = pN.parentNode;
  10007. }
  10008. var pNode = me.document.createElement('p');
  10009. domUtils.setAttributes(pNode,{
  10010. style:'text-align:center'
  10011. });
  10012. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  10013. pNode.appendChild(tmpNode);
  10014. domUtils.setStyle(tmpNode,'float','');
  10015. }
  10016. }
  10017. } else {
  10018. var range = me.selection.getRange();
  10019. range.selectNode(ci).select();
  10020. me.execCommand('imagefloat', opt.imageBlockLine);
  10021. }
  10022. }
  10023. //去掉冗余的标签
  10024. if(opt.removeEmptyNode){
  10025. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  10026. domUtils.remove(ci);
  10027. }
  10028. }
  10029. }
  10030. if(opt.tobdc){
  10031. var root = UE.htmlparser(cont.innerHTML);
  10032. root.traversal(function(node){
  10033. if(node.type == 'text'){
  10034. node.data = ToDBC(node.data)
  10035. }
  10036. });
  10037. cont.innerHTML = root.toHtml()
  10038. }
  10039. if(opt.bdc2sb){
  10040. var root = UE.htmlparser(cont.innerHTML);
  10041. root.traversal(function(node){
  10042. if(node.type == 'text'){
  10043. node.data = DBC2SB(node.data)
  10044. }
  10045. });
  10046. cont.innerHTML = root.toHtml()
  10047. }
  10048. if(html){
  10049. html.html = cont.innerHTML;
  10050. }
  10051. }
  10052. if(opt.pasteFilter){
  10053. me.addListener('beforepaste',autotype);
  10054. }
  10055. function DBC2SB(str) {
  10056. var result = '';
  10057. for (var i = 0; i < str.length; i++) {
  10058. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10059. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10060. {
  10061. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10062. } else if (code == 12288)//空格
  10063. {
  10064. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10065. } else {
  10066. result += str.charAt(i);
  10067. }
  10068. }
  10069. return result;
  10070. }
  10071. function ToDBC(txtstring) {
  10072. txtstring = utils.html(txtstring);
  10073. var tmp = "";
  10074. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10075. for (var i = 0; i < txtstring.length; i++) {
  10076. if (txtstring.charCodeAt(i) == 32) {
  10077. tmp = tmp + String.fromCharCode(12288);
  10078. }
  10079. else if (txtstring.charCodeAt(i) < 127) {
  10080. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10081. }
  10082. else {
  10083. tmp += txtstring.charAt(i);
  10084. }
  10085. }
  10086. return tmp;
  10087. }
  10088. function readLocalOpts() {
  10089. var cookieOpt = me.getPreferences('autotypeset');
  10090. utils.extend(me.options.autotypeset, cookieOpt);
  10091. }
  10092. me.commands['autotypeset'] = {
  10093. execCommand:function () {
  10094. me.removeListener('beforepaste',autotype);
  10095. if(opt.pasteFilter){
  10096. me.addListener('beforepaste',autotype);
  10097. }
  10098. autotype.call(me)
  10099. }
  10100. };
  10101. };
  10102. // plugins/autosubmit.js
  10103. /**
  10104. * 快捷键提交
  10105. * @file
  10106. * @since 1.2.6.1
  10107. */
  10108. /**
  10109. * 提交表单
  10110. * @command autosubmit
  10111. * @method execCommand
  10112. * @param { String } cmd 命令字符串
  10113. * @example
  10114. * ```javascript
  10115. * editor.execCommand( 'autosubmit' );
  10116. * ```
  10117. */
  10118. UE.plugin.register('autosubmit',function(){
  10119. return {
  10120. shortcutkey:{
  10121. "autosubmit":"ctrl+13" //手动提交
  10122. },
  10123. commands:{
  10124. 'autosubmit':{
  10125. execCommand:function () {
  10126. var me=this,
  10127. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10128. if (form){
  10129. if(me.fireEvent("beforesubmit")===false){
  10130. return;
  10131. }
  10132. me.sync();
  10133. form.submit();
  10134. }
  10135. }
  10136. }
  10137. }
  10138. }
  10139. });
  10140. // plugins/background.js
  10141. /**
  10142. * 背景插件,为UEditor提供设置背景功能
  10143. * @file
  10144. * @since 1.2.6.1
  10145. */
  10146. UE.plugin.register('background', function () {
  10147. var me = this,
  10148. cssRuleId = 'editor_background',
  10149. isSetColored,
  10150. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10151. function stringToObj(str) {
  10152. var obj = {}, styles = str.split(';');
  10153. utils.each(styles, function (v) {
  10154. var index = v.indexOf(':'),
  10155. key = utils.trim(v.substr(0, index)).toLowerCase();
  10156. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10157. });
  10158. return obj;
  10159. }
  10160. function setBackground(obj) {
  10161. if (obj) {
  10162. var styles = [];
  10163. for (var name in obj) {
  10164. if (obj.hasOwnProperty(name)) {
  10165. styles.push(name + ":" + obj[name] + '; ');
  10166. }
  10167. }
  10168. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10169. } else {
  10170. utils.cssRule(cssRuleId, '', me.document)
  10171. }
  10172. }
  10173. //重写editor.hasContent方法
  10174. var orgFn = me.hasContents;
  10175. me.hasContents = function(){
  10176. if(me.queryCommandValue('background')){
  10177. return true
  10178. }
  10179. return orgFn.apply(me,arguments);
  10180. };
  10181. return {
  10182. bindEvents: {
  10183. 'getAllHtml': function (type, headHtml) {
  10184. var body = this.body,
  10185. su = domUtils.getComputedStyle(body, "background-image"),
  10186. url = "";
  10187. if (su.indexOf(me.options.imagePath) > 0) {
  10188. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10189. } else {
  10190. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10191. }
  10192. var html = '<style type="text/css">body{';
  10193. var bgObj = {
  10194. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10195. 'background-image': url ? 'url(' + url + ')' : '',
  10196. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10197. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10198. 'height': domUtils.getComputedStyle(body, "height")
  10199. };
  10200. for (var name in bgObj) {
  10201. if (bgObj.hasOwnProperty(name)) {
  10202. html += name + ":" + bgObj[name] + "; ";
  10203. }
  10204. }
  10205. html += '}</style> ';
  10206. headHtml.push(html);
  10207. },
  10208. 'aftersetcontent': function () {
  10209. if(isSetColored == false) setBackground();
  10210. }
  10211. },
  10212. inputRule: function (root) {
  10213. isSetColored = false;
  10214. utils.each(root.getNodesByTagName('p'), function (p) {
  10215. var styles = p.getAttr('data-background');
  10216. if (styles) {
  10217. isSetColored = true;
  10218. setBackground(stringToObj(styles));
  10219. p.parentNode.removeChild(p);
  10220. }
  10221. })
  10222. },
  10223. outputRule: function (root) {
  10224. var me = this,
  10225. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10226. if (styles) {
  10227. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10228. }
  10229. },
  10230. commands: {
  10231. 'background': {
  10232. execCommand: function (cmd, obj) {
  10233. setBackground(obj);
  10234. },
  10235. queryCommandValue: function () {
  10236. var me = this,
  10237. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10238. return styles ? stringToObj(styles[1]) : null;
  10239. },
  10240. notNeedUndo: true
  10241. }
  10242. }
  10243. }
  10244. });
  10245. // plugins/image.js
  10246. /**
  10247. * 图片插入、排版插件
  10248. * @file
  10249. * @since 1.2.6.1
  10250. */
  10251. /**
  10252. * 图片对齐方式
  10253. * @command imagefloat
  10254. * @method execCommand
  10255. * @remind 值center为独占一行居中
  10256. * @param { String } cmd 命令字符串
  10257. * @param { String } align 对齐方式,可传left、right、none、center
  10258. * @remaind center表示图片独占一行
  10259. * @example
  10260. * ```javascript
  10261. * editor.execCommand( 'imagefloat', 'center' );
  10262. * ```
  10263. */
  10264. /**
  10265. * 如果选区所在位置是图片区域
  10266. * @command imagefloat
  10267. * @method queryCommandValue
  10268. * @param { String } cmd 命令字符串
  10269. * @return { String } 返回图片对齐方式
  10270. * @example
  10271. * ```javascript
  10272. * editor.queryCommandValue( 'imagefloat' );
  10273. * ```
  10274. */
  10275. UE.commands['imagefloat'] = {
  10276. execCommand:function (cmd, align) {
  10277. var me = this,
  10278. range = me.selection.getRange();
  10279. if (!range.collapsed) {
  10280. var img = range.getClosedNode();
  10281. if (img && img.tagName == 'IMG') {
  10282. switch (align) {
  10283. case 'left':
  10284. case 'right':
  10285. case 'none':
  10286. var pN = img.parentNode, tmpNode, pre, next;
  10287. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10288. pN = pN.parentNode;
  10289. }
  10290. tmpNode = pN;
  10291. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10292. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10293. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10294. }) == 1) {
  10295. pre = tmpNode.previousSibling;
  10296. next = tmpNode.nextSibling;
  10297. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10298. pre.appendChild(tmpNode.firstChild);
  10299. while (next.firstChild) {
  10300. pre.appendChild(next.firstChild);
  10301. }
  10302. domUtils.remove(tmpNode);
  10303. domUtils.remove(next);
  10304. } else {
  10305. domUtils.setStyle(tmpNode, 'text-align', '');
  10306. }
  10307. }
  10308. range.selectNode(img).select();
  10309. }
  10310. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10311. if(align == 'none'){
  10312. domUtils.removeAttributes(img,'align');
  10313. }
  10314. break;
  10315. case 'center':
  10316. if (me.queryCommandValue('imagefloat') != 'center') {
  10317. pN = img.parentNode;
  10318. domUtils.setStyle(img, 'float', '');
  10319. domUtils.removeAttributes(img,'align');
  10320. tmpNode = img;
  10321. while (pN && domUtils.getChildCount(pN, function (node) {
  10322. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10323. }) == 1
  10324. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10325. tmpNode = pN;
  10326. pN = pN.parentNode;
  10327. }
  10328. range.setStartBefore(tmpNode).setCursor(false);
  10329. pN = me.document.createElement('div');
  10330. pN.appendChild(tmpNode);
  10331. domUtils.setStyle(tmpNode, 'float', '');
  10332. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10333. tmpNode = me.document.getElementById('_img_parent_tmp');
  10334. tmpNode.removeAttribute('id');
  10335. tmpNode = tmpNode.firstChild;
  10336. range.selectNode(tmpNode).select();
  10337. //去掉后边多余的元素
  10338. next = tmpNode.parentNode.nextSibling;
  10339. if (next && domUtils.isEmptyNode(next)) {
  10340. domUtils.remove(next);
  10341. }
  10342. }
  10343. break;
  10344. }
  10345. }
  10346. }
  10347. },
  10348. queryCommandValue:function () {
  10349. var range = this.selection.getRange(),
  10350. startNode, floatStyle;
  10351. if (range.collapsed) {
  10352. return 'none';
  10353. }
  10354. startNode = range.getClosedNode();
  10355. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10356. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10357. if (floatStyle == 'none') {
  10358. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10359. }
  10360. return {
  10361. left:1,
  10362. right:1,
  10363. center:1
  10364. }[floatStyle] ? floatStyle : 'none';
  10365. }
  10366. return 'none';
  10367. },
  10368. queryCommandState:function () {
  10369. var range = this.selection.getRange(),
  10370. startNode;
  10371. if (range.collapsed) return -1;
  10372. startNode = range.getClosedNode();
  10373. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10374. return 0;
  10375. }
  10376. return -1;
  10377. }
  10378. };
  10379. /**
  10380. * 插入图片
  10381. * @command insertimage
  10382. * @method execCommand
  10383. * @param { String } cmd 命令字符串
  10384. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10385. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10386. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10387. * @example
  10388. * ```javascript
  10389. * editor.execCommand( 'insertimage', {
  10390. * src:'a/b/c.jpg',
  10391. * width:'100',
  10392. * height:'100'
  10393. * } );
  10394. * ```
  10395. * @example
  10396. * ```javascript
  10397. * editor.execCommand( 'insertimage', [{
  10398. * src:'a/b/c.jpg',
  10399. * width:'100',
  10400. * height:'100'
  10401. * },{
  10402. * src:'a/b/d.jpg',
  10403. * width:'100',
  10404. * height:'100'
  10405. * }] );
  10406. * ```
  10407. */
  10408. UE.commands['insertimage'] = {
  10409. execCommand:function (cmd, opt) {
  10410. opt = utils.isArray(opt) ? opt : [opt];
  10411. if (!opt.length) {
  10412. return;
  10413. }
  10414. var me = this,
  10415. range = me.selection.getRange(),
  10416. img = range.getClosedNode();
  10417. if(me.fireEvent('beforeinsertimage', opt) === true){
  10418. return;
  10419. }
  10420. function unhtmlData(imgCi) {
  10421. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10422. if (imgCi[item]) {
  10423. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10424. }
  10425. });
  10426. utils.each('src,_src'.split(','), function (item) {
  10427. if (imgCi[item]) {
  10428. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10429. }
  10430. });
  10431. utils.each('title,alt'.split(','), function (item) {
  10432. if (imgCi[item]) {
  10433. imgCi[item] = utils.unhtml(imgCi[item]);
  10434. }
  10435. });
  10436. }
  10437. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10438. var first = opt.shift();
  10439. var floatStyle = first['floatStyle'];
  10440. delete first['floatStyle'];
  10441. //// img.style.border = (first.border||0) +"px solid #000";
  10442. //// img.style.margin = (first.margin||0) +"px";
  10443. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10444. domUtils.setAttributes(img, first);
  10445. me.execCommand('imagefloat', floatStyle);
  10446. if (opt.length > 0) {
  10447. range.setStartAfter(img).setCursor(false, true);
  10448. me.execCommand('insertimage', opt);
  10449. }
  10450. } else {
  10451. var html = [], str = '', ci;
  10452. ci = opt[0];
  10453. if (opt.length == 1) {
  10454. unhtmlData(ci);
  10455. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10456. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10457. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10458. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10459. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10460. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10461. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10462. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10463. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10464. if (ci['floatStyle'] == 'center') {
  10465. str = '<p style="text-align: center">' + str + '</p>';
  10466. }
  10467. html.push(str);
  10468. } else {
  10469. for (var i = 0; ci = opt[i++];) {
  10470. unhtmlData(ci);
  10471. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10472. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10473. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10474. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10475. (ci.border || '') + '" ' +
  10476. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10477. html.push(str);
  10478. }
  10479. }
  10480. me.execCommand('insertHtml', html.join(''));
  10481. }
  10482. me.fireEvent('afterinsertimage', opt)
  10483. }
  10484. };
  10485. // plugins/justify.js
  10486. /**
  10487. * 段落格式
  10488. * @file
  10489. * @since 1.2.6.1
  10490. */
  10491. /**
  10492. * 段落对齐方式
  10493. * @command justify
  10494. * @method execCommand
  10495. * @param { String } cmd 命令字符串
  10496. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10497. * @example
  10498. * ```javascript
  10499. * editor.execCommand( 'justify', 'center' );
  10500. * ```
  10501. */
  10502. /**
  10503. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10504. * @command justify
  10505. * @method queryCommandValue
  10506. * @param { String } cmd 命令字符串
  10507. * @return { String } 返回段落对齐方式
  10508. * @example
  10509. * ```javascript
  10510. * editor.queryCommandValue( 'justify' );
  10511. * ```
  10512. */
  10513. UE.plugins['justify']=function(){
  10514. var me=this,
  10515. block = domUtils.isBlockElm,
  10516. defaultValue = {
  10517. left:1,
  10518. right:1,
  10519. center:1,
  10520. justify:1
  10521. },
  10522. doJustify = function (range, style) {
  10523. var bookmark = range.createBookmark(),
  10524. filterFn = function (node) {
  10525. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10526. };
  10527. range.enlarge(true);
  10528. var bookmark2 = range.createBookmark(),
  10529. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10530. tmpRange = range.cloneRange(),
  10531. tmpNode;
  10532. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10533. if (current.nodeType == 3 || !block(current)) {
  10534. tmpRange.setStartBefore(current);
  10535. while (current && current !== bookmark2.end && !block(current)) {
  10536. tmpNode = current;
  10537. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10538. return !block(node);
  10539. });
  10540. }
  10541. tmpRange.setEndAfter(tmpNode);
  10542. var common = tmpRange.getCommonAncestor();
  10543. if (!domUtils.isBody(common) && block(common)) {
  10544. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10545. current = common;
  10546. } else {
  10547. var p = range.document.createElement('p');
  10548. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10549. var frag = tmpRange.extractContents();
  10550. p.appendChild(frag);
  10551. tmpRange.insertNode(p);
  10552. current = p;
  10553. }
  10554. current = domUtils.getNextDomNode(current, false, filterFn);
  10555. } else {
  10556. current = domUtils.getNextDomNode(current, true, filterFn);
  10557. }
  10558. }
  10559. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10560. };
  10561. UE.commands['justify'] = {
  10562. execCommand:function (cmdName, align) {
  10563. var range = this.selection.getRange(),
  10564. txt;
  10565. //闭合时单独处理
  10566. if (range.collapsed) {
  10567. txt = this.document.createTextNode('p');
  10568. range.insertNode(txt);
  10569. }
  10570. doJustify(range, align);
  10571. if (txt) {
  10572. range.setStartBefore(txt).collapse(true);
  10573. domUtils.remove(txt);
  10574. }
  10575. range.select();
  10576. return true;
  10577. },
  10578. queryCommandValue:function () {
  10579. var startNode = this.selection.getStart(),
  10580. value = domUtils.getComputedStyle(startNode, 'text-align');
  10581. return defaultValue[value] ? value : 'left';
  10582. },
  10583. queryCommandState:function () {
  10584. var start = this.selection.getStart(),
  10585. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10586. return cell? -1:0;
  10587. }
  10588. };
  10589. };
  10590. // plugins/font.js
  10591. /**
  10592. * 字体颜色,背景色,字号,字体,下划线,删除线
  10593. * @file
  10594. * @since 1.2.6.1
  10595. */
  10596. /**
  10597. * 字体颜色
  10598. * @command forecolor
  10599. * @method execCommand
  10600. * @param { String } cmd 命令字符串
  10601. * @param { String } value 色值(必须十六进制)
  10602. * @example
  10603. * ```javascript
  10604. * editor.execCommand( 'forecolor', '#000' );
  10605. * ```
  10606. */
  10607. /**
  10608. * 返回选区字体颜色
  10609. * @command forecolor
  10610. * @method queryCommandValue
  10611. * @param { String } cmd 命令字符串
  10612. * @return { String } 返回字体颜色
  10613. * @example
  10614. * ```javascript
  10615. * editor.queryCommandValue( 'forecolor' );
  10616. * ```
  10617. */
  10618. /**
  10619. * 字体背景颜色
  10620. * @command backcolor
  10621. * @method execCommand
  10622. * @param { String } cmd 命令字符串
  10623. * @param { String } value 色值(必须十六进制)
  10624. * @example
  10625. * ```javascript
  10626. * editor.execCommand( 'backcolor', '#000' );
  10627. * ```
  10628. */
  10629. /**
  10630. * 返回选区字体颜色
  10631. * @command backcolor
  10632. * @method queryCommandValue
  10633. * @param { String } cmd 命令字符串
  10634. * @return { String } 返回字体背景颜色
  10635. * @example
  10636. * ```javascript
  10637. * editor.queryCommandValue( 'backcolor' );
  10638. * ```
  10639. */
  10640. /**
  10641. * 字体大小
  10642. * @command fontsize
  10643. * @method execCommand
  10644. * @param { String } cmd 命令字符串
  10645. * @param { String } value 字体大小
  10646. * @example
  10647. * ```javascript
  10648. * editor.execCommand( 'fontsize', '14px' );
  10649. * ```
  10650. */
  10651. /**
  10652. * 返回选区字体大小
  10653. * @command fontsize
  10654. * @method queryCommandValue
  10655. * @param { String } cmd 命令字符串
  10656. * @return { String } 返回字体大小
  10657. * @example
  10658. * ```javascript
  10659. * editor.queryCommandValue( 'fontsize' );
  10660. * ```
  10661. */
  10662. /**
  10663. * 字体样式
  10664. * @command fontfamily
  10665. * @method execCommand
  10666. * @param { String } cmd 命令字符串
  10667. * @param { String } value 字体样式
  10668. * @example
  10669. * ```javascript
  10670. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10671. * ```
  10672. */
  10673. /**
  10674. * 返回选区字体样式
  10675. * @command fontfamily
  10676. * @method queryCommandValue
  10677. * @param { String } cmd 命令字符串
  10678. * @return { String } 返回字体样式
  10679. * @example
  10680. * ```javascript
  10681. * editor.queryCommandValue( 'fontfamily' );
  10682. * ```
  10683. */
  10684. /**
  10685. * 字体下划线,与删除线互斥
  10686. * @command underline
  10687. * @method execCommand
  10688. * @param { String } cmd 命令字符串
  10689. * @example
  10690. * ```javascript
  10691. * editor.execCommand( 'underline' );
  10692. * ```
  10693. */
  10694. /**
  10695. * 字体删除线,与下划线互斥
  10696. * @command strikethrough
  10697. * @method execCommand
  10698. * @param { String } cmd 命令字符串
  10699. * @example
  10700. * ```javascript
  10701. * editor.execCommand( 'strikethrough' );
  10702. * ```
  10703. */
  10704. /**
  10705. * 字体边框
  10706. * @command fontborder
  10707. * @method execCommand
  10708. * @param { String } cmd 命令字符串
  10709. * @example
  10710. * ```javascript
  10711. * editor.execCommand( 'fontborder' );
  10712. * ```
  10713. */
  10714. UE.plugins['font'] = function () {
  10715. var me = this,
  10716. fonts = {
  10717. 'forecolor': 'color',
  10718. 'backcolor': 'background-color',
  10719. 'fontsize': 'font-size',
  10720. 'fontfamily': 'font-family',
  10721. 'underline': 'text-decoration',
  10722. 'strikethrough': 'text-decoration',
  10723. 'fontborder': 'border'
  10724. },
  10725. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10726. needSetChild = {
  10727. 'forecolor': 'color',
  10728. 'backcolor': 'background-color',
  10729. 'fontsize': 'font-size',
  10730. 'fontfamily': 'font-family'
  10731. };
  10732. me.setOpt({
  10733. 'fontfamily': [
  10734. { name: 'songti', val: '宋体,SimSun'},
  10735. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10736. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10737. { name: 'heiti', val: '黑体, SimHei'},
  10738. { name: 'lishu', val: '隶书, SimLi'},
  10739. { name: 'andaleMono', val: 'andale mono'},
  10740. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10741. { name: 'arialBlack', val: 'arial black,avant garde'},
  10742. { name: 'comicSansMs', val: 'comic sans ms'},
  10743. { name: 'impact', val: 'impact,chicago'},
  10744. { name: 'timesNewRoman', val: 'times new roman'}
  10745. ],
  10746. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10747. });
  10748. function mergeWithParent(node){
  10749. var parent;
  10750. while(parent = node.parentNode){
  10751. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10752. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10753. }) == 1) {
  10754. parent.style.cssText += node.style.cssText;
  10755. domUtils.remove(node,true);
  10756. node = parent;
  10757. }else{
  10758. break;
  10759. }
  10760. }
  10761. }
  10762. function mergeChild(rng,cmdName,value){
  10763. if(needSetChild[cmdName]){
  10764. rng.adjustmentBoundary();
  10765. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10766. var start = rng.startContainer.childNodes[rng.startOffset];
  10767. if(start && domUtils.isTagNode(start,'span')){
  10768. var bk = rng.createBookmark();
  10769. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10770. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10771. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10772. return;
  10773. }
  10774. domUtils.removeStyle(span,needSetChild[cmdName]);
  10775. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10776. domUtils.remove(span,true)
  10777. }
  10778. });
  10779. rng.moveToBookmark(bk)
  10780. }
  10781. }
  10782. }
  10783. }
  10784. function mergesibling(rng,cmdName,value) {
  10785. var collapsed = rng.collapsed,
  10786. bk = rng.createBookmark(), common;
  10787. if (collapsed) {
  10788. common = bk.start.parentNode;
  10789. while (dtd.$inline[common.tagName]) {
  10790. common = common.parentNode;
  10791. }
  10792. } else {
  10793. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10794. }
  10795. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10796. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10797. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10798. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10799. domUtils.remove(span, true);
  10800. }else{
  10801. domUtils.removeStyle(span,'border');
  10802. }
  10803. return
  10804. }
  10805. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10806. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10807. }
  10808. if(!(cmdName=='fontborder' && value=='none')){
  10809. var next = span.nextSibling;
  10810. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10811. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10812. span.appendChild(next);
  10813. next = span.nextSibling;
  10814. continue;
  10815. }
  10816. if (next.style.cssText == span.style.cssText) {
  10817. domUtils.moveChild(next, span);
  10818. domUtils.remove(next);
  10819. }
  10820. if (span.nextSibling === next)
  10821. break;
  10822. next = span.nextSibling;
  10823. }
  10824. }
  10825. mergeWithParent(span);
  10826. if(browser.ie && browser.version > 8 ){
  10827. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10828. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10829. if(parent && !/background-color/.test(span.style.cssText)){
  10830. span.style.backgroundColor = parent.style.backgroundColor;
  10831. }
  10832. }
  10833. });
  10834. rng.moveToBookmark(bk);
  10835. mergeChild(rng,cmdName,value)
  10836. }
  10837. me.addInputRule(function (root) {
  10838. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10839. if (node.tagName == 'font') {
  10840. var cssStyle = [];
  10841. for (var p in node.attrs) {
  10842. switch (p) {
  10843. case 'size':
  10844. cssStyle.push('font-size:' +
  10845. ({
  10846. '1':'10',
  10847. '2':'12',
  10848. '3':'16',
  10849. '4':'18',
  10850. '5':'24',
  10851. '6':'32',
  10852. '7':'48'
  10853. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10854. break;
  10855. case 'color':
  10856. cssStyle.push('color:' + node.attrs[p]);
  10857. break;
  10858. case 'face':
  10859. cssStyle.push('font-family:' + node.attrs[p]);
  10860. break;
  10861. case 'style':
  10862. cssStyle.push(node.attrs[p]);
  10863. }
  10864. }
  10865. node.attrs = {
  10866. 'style': cssStyle.join(';')
  10867. };
  10868. } else {
  10869. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10870. node.attrs = {
  10871. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10872. }
  10873. }
  10874. node.tagName = 'span';
  10875. });
  10876. // utils.each(root.getNodesByTagName('span'), function (node) {
  10877. // var val;
  10878. // if(val = node.getAttr('class')){
  10879. // if(/fontstrikethrough/.test(val)){
  10880. // node.setStyle('text-decoration','line-through');
  10881. // if(node.attrs['class']){
  10882. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10883. // }else{
  10884. // node.setAttr('class')
  10885. // }
  10886. // }
  10887. // if(/fontborder/.test(val)){
  10888. // node.setStyle('border','1px solid #000');
  10889. // if(node.attrs['class']){
  10890. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10891. // }else{
  10892. // node.setAttr('class')
  10893. // }
  10894. // }
  10895. // }
  10896. // });
  10897. });
  10898. // me.addOutputRule(function(root){
  10899. // utils.each(root.getNodesByTagName('span'), function (node) {
  10900. // var val;
  10901. // if(val = node.getStyle('text-decoration')){
  10902. // if(/line-through/.test(val)){
  10903. // if(node.attrs['class']){
  10904. // node.attrs['class'] += ' fontstrikethrough';
  10905. // }else{
  10906. // node.setAttr('class','fontstrikethrough')
  10907. // }
  10908. // }
  10909. //
  10910. // node.setStyle('text-decoration')
  10911. // }
  10912. // if(val = node.getStyle('border')){
  10913. // if(/1px/.test(val) && /solid/.test(val)){
  10914. // if(node.attrs['class']){
  10915. // node.attrs['class'] += ' fontborder';
  10916. //
  10917. // }else{
  10918. // node.setAttr('class','fontborder')
  10919. // }
  10920. // }
  10921. // node.setStyle('border')
  10922. //
  10923. // }
  10924. // });
  10925. // });
  10926. for (var p in fonts) {
  10927. (function (cmd, style) {
  10928. UE.commands[cmd] = {
  10929. execCommand: function (cmdName, value) {
  10930. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10931. cmdName == 'fontborder' ? '1px solid #000' :
  10932. 'line-through');
  10933. var me = this,
  10934. range = this.selection.getRange(),
  10935. text;
  10936. if (value == 'default') {
  10937. if (range.collapsed) {
  10938. text = me.document.createTextNode('font');
  10939. range.insertNode(text).select();
  10940. }
  10941. me.execCommand('removeFormat', 'span,a', style);
  10942. if (text) {
  10943. range.setStartBefore(text).collapse(true);
  10944. domUtils.remove(text);
  10945. }
  10946. mergesibling(range,cmdName,value);
  10947. range.select()
  10948. } else {
  10949. if (!range.collapsed) {
  10950. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10951. me.execCommand('removeFormat', 'span,a', style);
  10952. }
  10953. range = me.selection.getRange();
  10954. range.applyInlineStyle('span', {'style': style + ':' + value});
  10955. mergesibling(range, cmdName,value);
  10956. range.select();
  10957. } else {
  10958. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10959. text = me.document.createTextNode('font');
  10960. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10961. //for ie hack when enter
  10962. range.insertNode(text);
  10963. if (needCmd[cmd]) {
  10964. range.selectNode(text).select();
  10965. me.execCommand('removeFormat', 'span,a', style, null);
  10966. span = domUtils.findParentByTagName(text, 'span', true);
  10967. range.setStartBefore(text);
  10968. }
  10969. span && (span.style.cssText += ';' + style + ':' + value);
  10970. range.collapse(true).select();
  10971. } else {
  10972. range.insertNode(text);
  10973. range.selectNode(text).select();
  10974. span = range.document.createElement('span');
  10975. if (needCmd[cmd]) {
  10976. //a标签内的不处理跳过
  10977. if (domUtils.findParentByTagName(text, 'a', true)) {
  10978. range.setStartBefore(text).setCursor();
  10979. domUtils.remove(text);
  10980. return;
  10981. }
  10982. me.execCommand('removeFormat', 'span,a', style);
  10983. }
  10984. span.style.cssText = style + ':' + value;
  10985. text.parentNode.insertBefore(span, text);
  10986. //修复,span套span 但样式不继承的问题
  10987. if (!browser.ie || browser.ie && browser.version == 9) {
  10988. var spanParent = span.parentNode;
  10989. while (!domUtils.isBlockElm(spanParent)) {
  10990. if (spanParent.tagName == 'SPAN') {
  10991. //opera合并style不会加入";"
  10992. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10993. }
  10994. spanParent = spanParent.parentNode;
  10995. }
  10996. }
  10997. if (opera) {
  10998. setTimeout(function () {
  10999. range.setStart(span, 0).collapse(true);
  11000. mergesibling(range, cmdName,value);
  11001. range.select();
  11002. });
  11003. } else {
  11004. range.setStart(span, 0).collapse(true);
  11005. mergesibling(range,cmdName,value);
  11006. range.select();
  11007. }
  11008. //trace:981
  11009. //domUtils.mergeToParent(span)
  11010. }
  11011. domUtils.remove(text);
  11012. }
  11013. }
  11014. return true;
  11015. },
  11016. queryCommandValue: function (cmdName) {
  11017. var startNode = this.selection.getStart();
  11018. //trace:946
  11019. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11020. var tmpNode = startNode, value;
  11021. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11022. if (tmpNode.nodeType == 1) {
  11023. value = domUtils.getComputedStyle(tmpNode, style);
  11024. if (value != 'none') {
  11025. return value;
  11026. }
  11027. }
  11028. tmpNode = tmpNode.parentNode;
  11029. }
  11030. return 'none';
  11031. }
  11032. if (cmdName == 'fontborder') {
  11033. var tmp = startNode, val;
  11034. while (tmp && dtd.$inline[tmp.tagName]) {
  11035. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11036. if (/1px/.test(val) && /solid/.test(val)) {
  11037. return val;
  11038. }
  11039. }
  11040. tmp = tmp.parentNode;
  11041. }
  11042. return ''
  11043. }
  11044. if( cmdName == 'FontSize' ) {
  11045. var styleVal = domUtils.getComputedStyle(startNode, style),
  11046. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  11047. if( tmp ) {
  11048. return Math.floor( tmp[1] ) + tmp[2];
  11049. }
  11050. return styleVal;
  11051. }
  11052. return domUtils.getComputedStyle(startNode, style);
  11053. },
  11054. queryCommandState: function (cmdName) {
  11055. if (!needCmd[cmdName])
  11056. return 0;
  11057. var val = this.queryCommandValue(cmdName);
  11058. if (cmdName == 'fontborder') {
  11059. return /1px/.test(val) && /solid/.test(val)
  11060. } else {
  11061. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11062. }
  11063. }
  11064. };
  11065. })(p, fonts[p]);
  11066. }
  11067. };
  11068. // plugins/link.js
  11069. /**
  11070. * 超链接
  11071. * @file
  11072. * @since 1.2.6.1
  11073. */
  11074. /**
  11075. * 插入超链接
  11076. * @command link
  11077. * @method execCommand
  11078. * @param { String } cmd 命令字符串
  11079. * @param { Object } options 设置自定义属性,例如:url、title、target
  11080. * @example
  11081. * ```javascript
  11082. * editor.execCommand( 'link', '{
  11083. * url:'ueditor.baidu.com',
  11084. * title:'ueditor',
  11085. * target:'_blank'
  11086. * }' );
  11087. * ```
  11088. */
  11089. /**
  11090. * 返回当前选中的第一个超链接节点
  11091. * @command link
  11092. * @method queryCommandValue
  11093. * @param { String } cmd 命令字符串
  11094. * @return { Element } 超链接节点
  11095. * @example
  11096. * ```javascript
  11097. * editor.queryCommandValue( 'link' );
  11098. * ```
  11099. */
  11100. /**
  11101. * 取消超链接
  11102. * @command unlink
  11103. * @method execCommand
  11104. * @param { String } cmd 命令字符串
  11105. * @example
  11106. * ```javascript
  11107. * editor.execCommand( 'unlink');
  11108. * ```
  11109. */
  11110. UE.plugins['link'] = function(){
  11111. function optimize( range ) {
  11112. var start = range.startContainer,end = range.endContainer;
  11113. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11114. range.setStartBefore( start );
  11115. }
  11116. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11117. range.setEndAfter( end );
  11118. }
  11119. }
  11120. UE.commands['unlink'] = {
  11121. execCommand : function() {
  11122. var range = this.selection.getRange(),
  11123. bookmark;
  11124. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11125. return;
  11126. }
  11127. bookmark = range.createBookmark();
  11128. optimize( range );
  11129. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11130. },
  11131. queryCommandState : function(){
  11132. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11133. }
  11134. };
  11135. function doLink(range,opt,me){
  11136. var rngClone = range.cloneRange(),
  11137. link = me.queryCommandValue('link');
  11138. optimize( range = range.adjustmentBoundary() );
  11139. var start = range.startContainer;
  11140. if(start.nodeType == 1 && link){
  11141. start = start.childNodes[range.startOffset];
  11142. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11143. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11144. }
  11145. }
  11146. if( !rngClone.collapsed || link){
  11147. range.removeInlineStyle( 'a' );
  11148. rngClone = range.cloneRange();
  11149. }
  11150. if ( rngClone.collapsed ) {
  11151. var a = range.document.createElement( 'a'),
  11152. text = '';
  11153. if(opt.textValue){
  11154. text = utils.html(opt.textValue);
  11155. delete opt.textValue;
  11156. }else{
  11157. text = utils.html(opt.href);
  11158. }
  11159. domUtils.setAttributes( a, opt );
  11160. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11161. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11162. range.setStartAfter(start).collapse(true);
  11163. }
  11164. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11165. range.insertNode(a).selectNode( a );
  11166. } else {
  11167. range.applyInlineStyle( 'a', opt );
  11168. }
  11169. }
  11170. UE.commands['link'] = {
  11171. execCommand : function( cmdName, opt ) {
  11172. var range;
  11173. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11174. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11175. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11176. doLink(range=this.selection.getRange(),opt,this);
  11177. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11178. range.collapse().select(true);
  11179. },
  11180. queryCommandValue : function() {
  11181. var range = this.selection.getRange(),
  11182. node;
  11183. if ( range.collapsed ) {
  11184. // node = this.selection.getStart();
  11185. //在ie下getstart()取值偏上了
  11186. node = range.startContainer;
  11187. node = node.nodeType == 1 ? node : node.parentNode;
  11188. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11189. return node;
  11190. }
  11191. } else {
  11192. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11193. range.shrinkBoundary();
  11194. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11195. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11196. common = range.getCommonAncestor();
  11197. node = domUtils.findParentByTagName( common, 'a', true );
  11198. if ( !node && common.nodeType == 1){
  11199. var as = common.getElementsByTagName( 'a' ),
  11200. ps,pe;
  11201. for ( var i = 0,ci; ci = as[i++]; ) {
  11202. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11203. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11204. &&
  11205. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11206. ) {
  11207. node = ci;
  11208. break;
  11209. }
  11210. }
  11211. }
  11212. return node;
  11213. }
  11214. },
  11215. queryCommandState : function() {
  11216. //判断如果是视频的话连接不可用
  11217. //fix 853
  11218. var img = this.selection.getRange().getClosedNode(),
  11219. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11220. return flag ? -1 : 0;
  11221. }
  11222. };
  11223. };
  11224. // plugins/iframe.js
  11225. ///import core
  11226. ///import plugins\inserthtml.js
  11227. ///commands 插入框架
  11228. ///commandsName InsertFrame
  11229. ///commandsTitle 插入Iframe
  11230. ///commandsDialog dialogs\insertframe
  11231. UE.plugins['insertframe'] = function() {
  11232. var me =this;
  11233. function deleteIframe(){
  11234. me._iframe && delete me._iframe;
  11235. }
  11236. me.addListener("selectionchange",function(){
  11237. deleteIframe();
  11238. });
  11239. };
  11240. // plugins/scrawl.js
  11241. ///import core
  11242. ///commands 涂鸦
  11243. ///commandsName Scrawl
  11244. ///commandsTitle 涂鸦
  11245. ///commandsDialog dialogs\scrawl
  11246. UE.commands['scrawl'] = {
  11247. queryCommandState : function(){
  11248. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11249. }
  11250. };
  11251. // plugins/removeformat.js
  11252. /**
  11253. * 清除格式
  11254. * @file
  11255. * @since 1.2.6.1
  11256. */
  11257. /**
  11258. * 清除文字样式
  11259. * @command removeformat
  11260. * @method execCommand
  11261. * @param { String } cmd 命令字符串
  11262. * @param {String} tags 以逗号隔开的标签。如:strong
  11263. * @param {String} style 样式如:color
  11264. * @param {String} attrs 属性如:width
  11265. * @example
  11266. * ```javascript
  11267. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11268. * ```
  11269. */
  11270. UE.plugins['removeformat'] = function(){
  11271. var me = this;
  11272. me.setOpt({
  11273. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11274. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11275. });
  11276. me.commands['removeformat'] = {
  11277. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11278. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11279. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11280. range = new dom.Range( this.document ),
  11281. bookmark,node,parent,
  11282. filter = function( node ) {
  11283. return node.nodeType == 1;
  11284. };
  11285. function isRedundantSpan (node) {
  11286. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11287. return 0;
  11288. }
  11289. if (browser.ie) {
  11290. //ie 下判断实效,所以只能简单用style来判断
  11291. //return node.style.cssText == '' ? 1 : 0;
  11292. var attrs = node.attributes;
  11293. if ( attrs.length ) {
  11294. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11295. if ( attrs[i].specified ) {
  11296. return 0;
  11297. }
  11298. }
  11299. return 1;
  11300. }
  11301. }
  11302. return !node.attributes.length;
  11303. }
  11304. function doRemove( range ) {
  11305. var bookmark1 = range.createBookmark();
  11306. if ( range.collapsed ) {
  11307. range.enlarge( true );
  11308. }
  11309. //不能把a标签切了
  11310. if(!notIncludeA){
  11311. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11312. if(aNode){
  11313. range.setStartBefore(aNode);
  11314. }
  11315. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11316. if(aNode){
  11317. range.setEndAfter(aNode);
  11318. }
  11319. }
  11320. bookmark = range.createBookmark();
  11321. node = bookmark.start;
  11322. //切开始
  11323. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11324. domUtils.breakParent( node, parent );
  11325. domUtils.clearEmptySibling( node );
  11326. }
  11327. if ( bookmark.end ) {
  11328. //切结束
  11329. node = bookmark.end;
  11330. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11331. domUtils.breakParent( node, parent );
  11332. domUtils.clearEmptySibling( node );
  11333. }
  11334. //开始去除样式
  11335. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11336. next;
  11337. while ( current ) {
  11338. if ( current == bookmark.end ) {
  11339. break;
  11340. }
  11341. next = domUtils.getNextDomNode( current, true, filter );
  11342. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11343. if ( tagReg.test( current.tagName ) ) {
  11344. if ( style ) {
  11345. domUtils.removeStyle( current, style );
  11346. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11347. domUtils.remove( current, true );
  11348. }
  11349. } else {
  11350. domUtils.remove( current, true );
  11351. }
  11352. } else {
  11353. //trace:939 不能把list上的样式去掉
  11354. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11355. domUtils.removeAttributes( current, removeFormatAttributes );
  11356. if ( isRedundantSpan( current ) ){
  11357. domUtils.remove( current, true );
  11358. }
  11359. }
  11360. }
  11361. }
  11362. current = next;
  11363. }
  11364. }
  11365. //trace:1035
  11366. //trace:1096 不能把td上的样式去掉,比如边框
  11367. var pN = bookmark.start.parentNode;
  11368. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11369. domUtils.removeAttributes( pN,removeFormatAttributes );
  11370. }
  11371. pN = bookmark.end.parentNode;
  11372. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11373. domUtils.removeAttributes( pN,removeFormatAttributes );
  11374. }
  11375. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11376. //清除冗余的代码 <b><bookmark></b>
  11377. var node = range.startContainer,
  11378. tmp,
  11379. collapsed = range.collapsed;
  11380. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11381. tmp = node.parentNode;
  11382. range.setStartBefore(node);
  11383. //trace:937
  11384. //更新结束边界
  11385. if(range.startContainer === range.endContainer){
  11386. range.endOffset--;
  11387. }
  11388. domUtils.remove(node);
  11389. node = tmp;
  11390. }
  11391. if(!collapsed){
  11392. node = range.endContainer;
  11393. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11394. tmp = node.parentNode;
  11395. range.setEndBefore(node);
  11396. domUtils.remove(node);
  11397. node = tmp;
  11398. }
  11399. }
  11400. }
  11401. range = this.selection.getRange();
  11402. doRemove( range );
  11403. range.select();
  11404. }
  11405. };
  11406. };
  11407. // plugins/blockquote.js
  11408. /**
  11409. * 添加引用
  11410. * @file
  11411. * @since 1.2.6.1
  11412. */
  11413. /**
  11414. * 添加引用
  11415. * @command blockquote
  11416. * @method execCommand
  11417. * @param { String } cmd 命令字符串
  11418. * @example
  11419. * ```javascript
  11420. * editor.execCommand( 'blockquote' );
  11421. * ```
  11422. */
  11423. /**
  11424. * 添加引用
  11425. * @command blockquote
  11426. * @method execCommand
  11427. * @param { String } cmd 命令字符串
  11428. * @param { Object } attrs 节点属性
  11429. * @example
  11430. * ```javascript
  11431. * editor.execCommand( 'blockquote',{
  11432. * style: "color: red;"
  11433. * } );
  11434. * ```
  11435. */
  11436. UE.plugins['blockquote'] = function(){
  11437. var me = this;
  11438. function getObj(editor){
  11439. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11440. }
  11441. me.commands['blockquote'] = {
  11442. execCommand : function( cmdName, attrs ) {
  11443. var range = this.selection.getRange(),
  11444. obj = getObj(this),
  11445. blockquote = dtd.blockquote,
  11446. bookmark = range.createBookmark();
  11447. if ( obj ) {
  11448. var start = range.startContainer,
  11449. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11450. end = range.endContainer,
  11451. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11452. //处理一下li
  11453. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11454. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11455. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11456. domUtils.remove(obj,true);
  11457. }else{
  11458. domUtils.breakParent(startBlock,obj);
  11459. }
  11460. if(startBlock !== endBlock){
  11461. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11462. if(obj){
  11463. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11464. obj.parentNode && domUtils.remove(obj,true);
  11465. }else{
  11466. domUtils.breakParent(endBlock,obj);
  11467. }
  11468. }
  11469. }
  11470. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11471. for(var i=0,bi;bi=blockquotes[i++];){
  11472. if(!bi.childNodes.length){
  11473. domUtils.remove(bi);
  11474. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11475. domUtils.remove(bi,true);
  11476. }
  11477. }
  11478. } else {
  11479. var tmpRange = range.cloneRange(),
  11480. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11481. preNode = node,
  11482. doEnd = 1;
  11483. //调整开始
  11484. while ( 1 ) {
  11485. if ( domUtils.isBody(node) ) {
  11486. if ( preNode !== node ) {
  11487. if ( range.collapsed ) {
  11488. tmpRange.selectNode( preNode );
  11489. doEnd = 0;
  11490. } else {
  11491. tmpRange.setStartBefore( preNode );
  11492. }
  11493. }else{
  11494. tmpRange.setStart(node,0);
  11495. }
  11496. break;
  11497. }
  11498. if ( !blockquote[node.tagName] ) {
  11499. if ( range.collapsed ) {
  11500. tmpRange.selectNode( preNode );
  11501. } else{
  11502. tmpRange.setStartBefore( preNode);
  11503. }
  11504. break;
  11505. }
  11506. preNode = node;
  11507. node = node.parentNode;
  11508. }
  11509. //调整结束
  11510. if ( doEnd ) {
  11511. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11512. while ( 1 ) {
  11513. if ( domUtils.isBody( node ) ) {
  11514. if ( preNode !== node ) {
  11515. tmpRange.setEndAfter( preNode );
  11516. } else {
  11517. tmpRange.setEnd( node, node.childNodes.length );
  11518. }
  11519. break;
  11520. }
  11521. if ( !blockquote[node.tagName] ) {
  11522. tmpRange.setEndAfter( preNode );
  11523. break;
  11524. }
  11525. preNode = node;
  11526. node = node.parentNode;
  11527. }
  11528. }
  11529. node = range.document.createElement( 'blockquote' );
  11530. domUtils.setAttributes( node, attrs );
  11531. node.appendChild( tmpRange.extractContents() );
  11532. tmpRange.insertNode( node );
  11533. //去除重复的
  11534. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11535. for(var i=0,ci;ci=childs[i++];){
  11536. if(ci.parentNode){
  11537. domUtils.remove(ci,true);
  11538. }
  11539. }
  11540. }
  11541. range.moveToBookmark( bookmark ).select();
  11542. },
  11543. queryCommandState : function() {
  11544. return getObj(this) ? 1 : 0;
  11545. }
  11546. };
  11547. };
  11548. // plugins/convertcase.js
  11549. /**
  11550. * 大小写转换
  11551. * @file
  11552. * @since 1.2.6.1
  11553. */
  11554. /**
  11555. * 把选区内文本变大写,与“tolowercase”命令互斥
  11556. * @command touppercase
  11557. * @method execCommand
  11558. * @param { String } cmd 命令字符串
  11559. * @example
  11560. * ```javascript
  11561. * editor.execCommand( 'touppercase' );
  11562. * ```
  11563. */
  11564. /**
  11565. * 把选区内文本变小写,与“touppercase”命令互斥
  11566. * @command tolowercase
  11567. * @method execCommand
  11568. * @param { String } cmd 命令字符串
  11569. * @example
  11570. * ```javascript
  11571. * editor.execCommand( 'tolowercase' );
  11572. * ```
  11573. */
  11574. UE.commands['touppercase'] =
  11575. UE.commands['tolowercase'] = {
  11576. execCommand:function (cmd) {
  11577. var me = this;
  11578. var rng = me.selection.getRange();
  11579. if(rng.collapsed){
  11580. return rng;
  11581. }
  11582. var bk = rng.createBookmark(),
  11583. bkEnd = bk.end,
  11584. filterFn = function( node ) {
  11585. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11586. },
  11587. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11588. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11589. if ( curNode.nodeType == 3 ) {
  11590. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11591. }
  11592. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11593. if(curNode === bkEnd){
  11594. break;
  11595. }
  11596. }
  11597. rng.moveToBookmark(bk).select();
  11598. }
  11599. };
  11600. // plugins/indent.js
  11601. /**
  11602. * 首行缩进
  11603. * @file
  11604. * @since 1.2.6.1
  11605. */
  11606. /**
  11607. * 缩进
  11608. * @command indent
  11609. * @method execCommand
  11610. * @param { String } cmd 命令字符串
  11611. * @example
  11612. * ```javascript
  11613. * editor.execCommand( 'indent' );
  11614. * ```
  11615. */
  11616. UE.commands['indent'] = {
  11617. execCommand : function() {
  11618. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11619. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11620. },
  11621. queryCommandState : function() {
  11622. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11623. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11624. }
  11625. };
  11626. // plugins/print.js
  11627. /**
  11628. * 打印
  11629. * @file
  11630. * @since 1.2.6.1
  11631. */
  11632. /**
  11633. * 打印
  11634. * @command print
  11635. * @method execCommand
  11636. * @param { String } cmd 命令字符串
  11637. * @example
  11638. * ```javascript
  11639. * editor.execCommand( 'print' );
  11640. * ```
  11641. */
  11642. UE.commands['print'] = {
  11643. execCommand : function(){
  11644. this.window.print();
  11645. },
  11646. notNeedUndo : 1
  11647. };
  11648. // plugins/preview.js
  11649. /**
  11650. * 预览
  11651. * @file
  11652. * @since 1.2.6.1
  11653. */
  11654. /**
  11655. * 预览
  11656. * @command preview
  11657. * @method execCommand
  11658. * @param { String } cmd 命令字符串
  11659. * @example
  11660. * ```javascript
  11661. * editor.execCommand( 'preview' );
  11662. * ```
  11663. */
  11664. UE.commands['preview'] = {
  11665. execCommand : function(){
  11666. var w = window.open('', '_blank', ''),
  11667. d = w.document;
  11668. d.open();
  11669. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11670. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11671. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11672. d.close();
  11673. },
  11674. notNeedUndo : 1
  11675. };
  11676. // plugins/selectall.js
  11677. /**
  11678. * 全选
  11679. * @file
  11680. * @since 1.2.6.1
  11681. */
  11682. /**
  11683. * 选中所有内容
  11684. * @command selectall
  11685. * @method execCommand
  11686. * @param { String } cmd 命令字符串
  11687. * @example
  11688. * ```javascript
  11689. * editor.execCommand( 'selectall' );
  11690. * ```
  11691. */
  11692. UE.plugins['selectall'] = function(){
  11693. var me = this;
  11694. me.commands['selectall'] = {
  11695. execCommand : function(){
  11696. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11697. var me = this,body = me.body,
  11698. range = me.selection.getRange();
  11699. range.selectNodeContents(body);
  11700. if(domUtils.isEmptyBlock(body)){
  11701. //opera不能自动合并到元素的里边,要手动处理一下
  11702. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11703. range.setStartAtFirst(body.firstChild);
  11704. }
  11705. range.collapse(true);
  11706. }
  11707. range.select(true);
  11708. },
  11709. notNeedUndo : 1
  11710. };
  11711. //快捷键
  11712. me.addshortcutkey({
  11713. "selectAll" : "ctrl+65"
  11714. });
  11715. };
  11716. // plugins/paragraph.js
  11717. /**
  11718. * 段落样式
  11719. * @file
  11720. * @since 1.2.6.1
  11721. */
  11722. /**
  11723. * 段落格式
  11724. * @command paragraph
  11725. * @method execCommand
  11726. * @param { String } cmd 命令字符串
  11727. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11728. * @param {Object} attrs 标签的属性
  11729. * @example
  11730. * ```javascript
  11731. * editor.execCommand( 'Paragraph','h1','{
  11732. * class:'test'
  11733. * }' );
  11734. * ```
  11735. */
  11736. /**
  11737. * 返回选区内节点标签名
  11738. * @command paragraph
  11739. * @method queryCommandValue
  11740. * @param { String } cmd 命令字符串
  11741. * @return { String } 节点标签名
  11742. * @example
  11743. * ```javascript
  11744. * editor.queryCommandValue( 'Paragraph' );
  11745. * ```
  11746. */
  11747. UE.plugins['paragraph'] = function() {
  11748. var me = this,
  11749. block = domUtils.isBlockElm,
  11750. notExchange = ['TD','LI','PRE'],
  11751. doParagraph = function(range,style,attrs,sourceCmdName){
  11752. var bookmark = range.createBookmark(),
  11753. filterFn = function( node ) {
  11754. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11755. },
  11756. para;
  11757. range.enlarge( true );
  11758. var bookmark2 = range.createBookmark(),
  11759. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11760. tmpRange = range.cloneRange(),
  11761. tmpNode;
  11762. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11763. if ( current.nodeType == 3 || !block( current ) ) {
  11764. tmpRange.setStartBefore( current );
  11765. while ( current && current !== bookmark2.end && !block( current ) ) {
  11766. tmpNode = current;
  11767. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11768. return !block( node );
  11769. } );
  11770. }
  11771. tmpRange.setEndAfter( tmpNode );
  11772. para = range.document.createElement( style );
  11773. if(attrs){
  11774. domUtils.setAttributes(para,attrs);
  11775. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11776. para.style.cssText = attrs.style;
  11777. }
  11778. }
  11779. para.appendChild( tmpRange.extractContents() );
  11780. //需要内容占位
  11781. if(domUtils.isEmptyNode(para)){
  11782. domUtils.fillChar(range.document,para);
  11783. }
  11784. tmpRange.insertNode( para );
  11785. var parent = para.parentNode;
  11786. //如果para上一级是一个block元素且不是body,td就删除它
  11787. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11788. //存储dir,style
  11789. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11790. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11791. //trace:1070
  11792. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11793. //trace:1030
  11794. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11795. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11796. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11797. }
  11798. //trace:1706 选择的就是h1-6要删除
  11799. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11800. domUtils.setAttributes(parent,attrs);
  11801. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11802. parent.style.cssText = attrs.style;
  11803. }
  11804. domUtils.remove(para,true);
  11805. para = parent;
  11806. }else{
  11807. domUtils.remove( para.parentNode, true );
  11808. }
  11809. }
  11810. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11811. current = parent;
  11812. }else{
  11813. current = para;
  11814. }
  11815. current = domUtils.getNextDomNode( current, false, filterFn );
  11816. } else {
  11817. current = domUtils.getNextDomNode( current, true, filterFn );
  11818. }
  11819. }
  11820. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11821. };
  11822. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11823. me.commands['paragraph'] = {
  11824. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11825. var range = this.selection.getRange();
  11826. //闭合时单独处理
  11827. if(range.collapsed){
  11828. var txt = this.document.createTextNode('p');
  11829. range.insertNode(txt);
  11830. //去掉冗余的fillchar
  11831. if(browser.ie){
  11832. var node = txt.previousSibling;
  11833. if(node && domUtils.isWhitespace(node)){
  11834. domUtils.remove(node);
  11835. }
  11836. node = txt.nextSibling;
  11837. if(node && domUtils.isWhitespace(node)){
  11838. domUtils.remove(node);
  11839. }
  11840. }
  11841. }
  11842. range = doParagraph(range,style,attrs,sourceCmdName);
  11843. if(txt){
  11844. range.setStartBefore(txt).collapse(true);
  11845. pN = txt.parentNode;
  11846. domUtils.remove(txt);
  11847. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11848. domUtils.fillNode(this.document,pN);
  11849. }
  11850. }
  11851. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11852. var child = range.startContainer.childNodes[range.startOffset];
  11853. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11854. range.setStart(child,0).collapse(true);
  11855. }
  11856. }
  11857. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11858. range.select();
  11859. return true;
  11860. },
  11861. queryCommandValue : function() {
  11862. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11863. return node ? node.tagName.toLowerCase() : '';
  11864. }
  11865. };
  11866. };
  11867. // plugins/directionality.js
  11868. /**
  11869. * 设置文字输入的方向的插件
  11870. * @file
  11871. * @since 1.2.6.1
  11872. */
  11873. (function() {
  11874. var block = domUtils.isBlockElm ,
  11875. getObj = function(editor){
  11876. // var startNode = editor.selection.getStart(),
  11877. // parents;
  11878. // if ( startNode ) {
  11879. // //查找所有的是block的父亲节点
  11880. // parents = domUtils.findParents( startNode, true, block, true );
  11881. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11882. // if ( ci.getAttribute( 'dir' ) ) {
  11883. // return ci;
  11884. // }
  11885. // }
  11886. // }
  11887. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n && n.nodeType == 1 && n.getAttribute('dir')});
  11888. },
  11889. doDirectionality = function(range,editor,forward){
  11890. var bookmark,
  11891. filterFn = function( node ) {
  11892. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11893. },
  11894. obj = getObj( editor );
  11895. if ( obj && range.collapsed ) {
  11896. obj.setAttribute( 'dir', forward );
  11897. return range;
  11898. }
  11899. bookmark = range.createBookmark();
  11900. range.enlarge( true );
  11901. var bookmark2 = range.createBookmark(),
  11902. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11903. tmpRange = range.cloneRange(),
  11904. tmpNode;
  11905. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11906. if ( current.nodeType == 3 || !block( current ) ) {
  11907. tmpRange.setStartBefore( current );
  11908. while ( current && current !== bookmark2.end && !block( current ) ) {
  11909. tmpNode = current;
  11910. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11911. return !block( node );
  11912. } );
  11913. }
  11914. tmpRange.setEndAfter( tmpNode );
  11915. var common = tmpRange.getCommonAncestor();
  11916. if ( !domUtils.isBody( common ) && block( common ) ) {
  11917. //遍历到了block节点
  11918. common.setAttribute( 'dir', forward );
  11919. current = common;
  11920. } else {
  11921. //没有遍历到,添加一个block节点
  11922. var p = range.document.createElement( 'p' );
  11923. p.setAttribute( 'dir', forward );
  11924. var frag = tmpRange.extractContents();
  11925. p.appendChild( frag );
  11926. tmpRange.insertNode( p );
  11927. current = p;
  11928. }
  11929. current = domUtils.getNextDomNode( current, false, filterFn );
  11930. } else {
  11931. current = domUtils.getNextDomNode( current, true, filterFn );
  11932. }
  11933. }
  11934. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11935. };
  11936. /**
  11937. * 文字输入方向
  11938. * @command directionality
  11939. * @method execCommand
  11940. * @param { String } cmdName 命令字符串
  11941. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11942. * @example
  11943. * ```javascript
  11944. * editor.execCommand( 'directionality', 'ltr');
  11945. * ```
  11946. */
  11947. /**
  11948. * 查询当前选区的文字输入方向
  11949. * @command directionality
  11950. * @method queryCommandValue
  11951. * @param { String } cmdName 命令字符串
  11952. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11953. * @example
  11954. * ```javascript
  11955. * editor.queryCommandValue( 'directionality');
  11956. * ```
  11957. */
  11958. UE.commands['directionality'] = {
  11959. execCommand : function( cmdName,forward ) {
  11960. var range = this.selection.getRange();
  11961. //闭合时单独处理
  11962. if(range.collapsed){
  11963. var txt = this.document.createTextNode('d');
  11964. range.insertNode(txt);
  11965. }
  11966. doDirectionality(range,this,forward);
  11967. if(txt){
  11968. range.setStartBefore(txt).collapse(true);
  11969. domUtils.remove(txt);
  11970. }
  11971. range.select();
  11972. return true;
  11973. },
  11974. queryCommandValue : function() {
  11975. var node = getObj(this);
  11976. return node ? node.getAttribute('dir') : 'ltr';
  11977. }
  11978. };
  11979. })();
  11980. // plugins/horizontal.js
  11981. /**
  11982. * 插入分割线插件
  11983. * @file
  11984. * @since 1.2.6.1
  11985. */
  11986. /**
  11987. * 插入分割线
  11988. * @command horizontal
  11989. * @method execCommand
  11990. * @param { String } cmdName 命令字符串
  11991. * @example
  11992. * ```javascript
  11993. * editor.execCommand( 'horizontal' );
  11994. * ```
  11995. */
  11996. UE.plugins['horizontal'] = function(){
  11997. var me = this;
  11998. me.commands['horizontal'] = {
  11999. execCommand : function( cmdName ) {
  12000. var me = this;
  12001. if(me.queryCommandState(cmdName)!==-1){
  12002. me.execCommand('insertHtml','<hr>');
  12003. var range = me.selection.getRange(),
  12004. start = range.startContainer;
  12005. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  12006. var tmp;
  12007. if(tmp = start.childNodes[range.startOffset - 1]){
  12008. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  12009. if(me.options.enterTag == 'p'){
  12010. tmp = me.document.createElement('p');
  12011. range.insertNode(tmp);
  12012. range.setStart(tmp,0).setCursor();
  12013. }else{
  12014. tmp = me.document.createElement('br');
  12015. range.insertNode(tmp);
  12016. range.setStartBefore(tmp).setCursor();
  12017. }
  12018. }
  12019. }
  12020. }
  12021. return true;
  12022. }
  12023. },
  12024. //边界在table里不能加分隔线
  12025. queryCommandState : function() {
  12026. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  12027. }
  12028. };
  12029. // me.addListener('delkeyup',function(){
  12030. // var rng = this.selection.getRange();
  12031. // if(browser.ie && browser.version > 8){
  12032. // rng.txtToElmBoundary(true);
  12033. // if(domUtils.isStartInblock(rng)){
  12034. // var tmpNode = rng.startContainer;
  12035. // var pre = tmpNode.previousSibling;
  12036. // if(pre && domUtils.isTagNode(pre,'hr')){
  12037. // domUtils.remove(pre);
  12038. // rng.select();
  12039. // return;
  12040. // }
  12041. // }
  12042. // }
  12043. // if(domUtils.isBody(rng.startContainer)){
  12044. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12045. // if(hr && hr.nodeName == 'HR'){
  12046. // var next = hr.nextSibling;
  12047. // if(next){
  12048. // rng.setStart(next,0)
  12049. // }else if(hr.previousSibling){
  12050. // rng.setStartAtLast(hr.previousSibling)
  12051. // }else{
  12052. // var p = this.document.createElement('p');
  12053. // hr.parentNode.insertBefore(p,hr);
  12054. // domUtils.fillNode(this.document,p);
  12055. // rng.setStart(p,0);
  12056. // }
  12057. // domUtils.remove(hr);
  12058. // rng.setCursor(false,true);
  12059. // }
  12060. // }
  12061. // })
  12062. me.addListener('delkeydown',function(name,evt){
  12063. var rng = this.selection.getRange();
  12064. rng.txtToElmBoundary(true);
  12065. if(domUtils.isStartInblock(rng)){
  12066. var tmpNode = rng.startContainer;
  12067. var pre = tmpNode.previousSibling;
  12068. if(pre && domUtils.isTagNode(pre,'hr')){
  12069. domUtils.remove(pre);
  12070. rng.select();
  12071. domUtils.preventDefault(evt);
  12072. return true;
  12073. }
  12074. }
  12075. })
  12076. };
  12077. // plugins/time.js
  12078. /**
  12079. * 插入时间和日期
  12080. * @file
  12081. * @since 1.2.6.1
  12082. */
  12083. /**
  12084. * 插入时间,默认格式:12:59:59
  12085. * @command time
  12086. * @method execCommand
  12087. * @param { String } cmd 命令字符串
  12088. * @example
  12089. * ```javascript
  12090. * editor.execCommand( 'time');
  12091. * ```
  12092. */
  12093. /**
  12094. * 插入日期,默认格式:2013-08-30
  12095. * @command date
  12096. * @method execCommand
  12097. * @param { String } cmd 命令字符串
  12098. * @example
  12099. * ```javascript
  12100. * editor.execCommand( 'date');
  12101. * ```
  12102. */
  12103. UE.commands['time'] = UE.commands["date"] = {
  12104. execCommand : function(cmd, format){
  12105. var date = new Date;
  12106. function formatTime(date, format) {
  12107. var hh = ('0' + date.getHours()).slice(-2),
  12108. ii = ('0' + date.getMinutes()).slice(-2),
  12109. ss = ('0' + date.getSeconds()).slice(-2);
  12110. format = format || 'hh:ii:ss';
  12111. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12112. }
  12113. function formatDate(date, format) {
  12114. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12115. yy = yyyy.slice(-2),
  12116. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12117. dd = ('0' + date.getDate()).slice(-2);
  12118. format = format || 'yyyy-mm-dd';
  12119. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12120. }
  12121. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12122. }
  12123. };
  12124. // plugins/rowspacing.js
  12125. /**
  12126. * 段前段后间距插件
  12127. * @file
  12128. * @since 1.2.6.1
  12129. */
  12130. /**
  12131. * 设置段间距
  12132. * @command rowspacing
  12133. * @method execCommand
  12134. * @param { String } cmd 命令字符串
  12135. * @param { String } value 段间距的值,以px为单位
  12136. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12137. * @example
  12138. * ```javascript
  12139. * editor.execCommand( 'rowspacing', '10', 'top' );
  12140. * ```
  12141. */
  12142. UE.plugins['rowspacing'] = function(){
  12143. var me = this;
  12144. me.setOpt({
  12145. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12146. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12147. });
  12148. me.commands['rowspacing'] = {
  12149. execCommand : function( cmdName,value,dir ) {
  12150. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12151. return true;
  12152. },
  12153. queryCommandValue : function(cmdName,dir) {
  12154. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12155. value;
  12156. //trace:1026
  12157. if(pN){
  12158. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12159. return !value ? 0 : value;
  12160. }
  12161. return 0;
  12162. }
  12163. };
  12164. };
  12165. // plugins/lineheight.js
  12166. /**
  12167. * 设置行内间距
  12168. * @file
  12169. * @since 1.2.6.1
  12170. */
  12171. UE.plugins['lineheight'] = function(){
  12172. var me = this;
  12173. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12174. /**
  12175. * 行距
  12176. * @command lineheight
  12177. * @method execCommand
  12178. * @param { String } cmdName 命令字符串
  12179. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12180. * @example
  12181. * ```javascript
  12182. * editor.execCommand( 'lineheight', 1.5);
  12183. * ```
  12184. */
  12185. /**
  12186. * 查询当前选区内容的行高大小
  12187. * @command lineheight
  12188. * @method queryCommandValue
  12189. * @param { String } cmd 命令字符串
  12190. * @return { String } 返回当前行高大小
  12191. * @example
  12192. * ```javascript
  12193. * editor.queryCommandValue( 'lineheight' );
  12194. * ```
  12195. */
  12196. me.commands['lineheight'] = {
  12197. execCommand : function( cmdName,value ) {
  12198. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12199. return true;
  12200. },
  12201. queryCommandValue : function() {
  12202. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12203. if(pN){
  12204. var value = domUtils.getComputedStyle(pN,'line-height');
  12205. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12206. }
  12207. }
  12208. };
  12209. };
  12210. // plugins/insertcode.js
  12211. /**
  12212. * 插入代码插件
  12213. * @file
  12214. * @since 1.2.6.1
  12215. */
  12216. UE.plugins['insertcode'] = function() {
  12217. var me = this;
  12218. me.ready(function(){
  12219. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12220. me.document)
  12221. });
  12222. me.setOpt('insertcode',{
  12223. 'as3':'ActionScript3',
  12224. 'bash':'Bash/Shell',
  12225. 'cpp':'C/C++',
  12226. 'css':'Css',
  12227. 'cf':'CodeFunction',
  12228. 'c#':'C#',
  12229. 'delphi':'Delphi',
  12230. 'diff':'Diff',
  12231. 'erlang':'Erlang',
  12232. 'groovy':'Groovy',
  12233. 'html':'Html',
  12234. 'java':'Java',
  12235. 'jfx':'JavaFx',
  12236. 'js':'Javascript',
  12237. 'pl':'Perl',
  12238. 'php':'Php',
  12239. 'plain':'Plain Text',
  12240. 'ps':'PowerShell',
  12241. 'python':'Python',
  12242. 'ruby':'Ruby',
  12243. 'scala':'Scala',
  12244. 'sql':'Sql',
  12245. 'vb':'Vb',
  12246. 'xml':'Xml'
  12247. });
  12248. /**
  12249. * 插入代码
  12250. * @command insertcode
  12251. * @method execCommand
  12252. * @param { String } cmd 命令字符串
  12253. * @param { String } lang 插入代码的语言
  12254. * @example
  12255. * ```javascript
  12256. * editor.execCommand( 'insertcode', 'javascript' );
  12257. * ```
  12258. */
  12259. /**
  12260. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12261. * @command insertcode
  12262. * @method queryCommandValue
  12263. * @param { String } cmd 命令字符串
  12264. * @return { String } 返回代码的语言
  12265. * @example
  12266. * ```javascript
  12267. * editor.queryCommandValue( 'insertcode' );
  12268. * ```
  12269. */
  12270. me.commands['insertcode'] = {
  12271. execCommand : function(cmd,lang){
  12272. var me = this,
  12273. rng = me.selection.getRange(),
  12274. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12275. if(pre){
  12276. pre.className = 'brush:'+lang+';toolbar:false;';
  12277. }else{
  12278. var code = '';
  12279. if(rng.collapsed){
  12280. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12281. }else{
  12282. var frag = rng.extractContents();
  12283. var div = me.document.createElement('div');
  12284. div.appendChild(frag);
  12285. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12286. if(browser.ie && browser.ie11below && browser.version > 8){
  12287. if(node.type =='element'){
  12288. if(node.tagName == 'br'){
  12289. code += '\n'
  12290. }else if(!dtd.$empty[node.tagName]){
  12291. utils.each(node.children,function(cn){
  12292. if(cn.type =='element'){
  12293. if(cn.tagName == 'br'){
  12294. code += '\n'
  12295. }else if(!dtd.$empty[node.tagName]){
  12296. code += cn.innerText();
  12297. }
  12298. }else{
  12299. code += cn.data
  12300. }
  12301. })
  12302. if(!/\n$/.test(code)){
  12303. code += '\n';
  12304. }
  12305. }
  12306. }else{
  12307. code += node.data + '\n'
  12308. }
  12309. if(!node.nextSibling() && /\n$/.test(code)){
  12310. code = code.replace(/\n$/,'');
  12311. }
  12312. }else{
  12313. if(browser.ie && browser.ie11below){
  12314. if(node.type =='element'){
  12315. if(node.tagName == 'br'){
  12316. code += '<br>'
  12317. }else if(!dtd.$empty[node.tagName]){
  12318. utils.each(node.children,function(cn){
  12319. if(cn.type =='element'){
  12320. if(cn.tagName == 'br'){
  12321. code += '<br>'
  12322. }else if(!dtd.$empty[node.tagName]){
  12323. code += cn.innerText();
  12324. }
  12325. }else{
  12326. code += cn.data
  12327. }
  12328. });
  12329. if(!/br>$/.test(code)){
  12330. code += '<br>';
  12331. }
  12332. }
  12333. }else{
  12334. code += node.data + '<br>'
  12335. }
  12336. if(!node.nextSibling() && /<br>$/.test(code)){
  12337. code = code.replace(/<br>$/,'');
  12338. }
  12339. }else{
  12340. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12341. if(!/br\/?\s*>$/.test(code)){
  12342. if(!node.nextSibling())
  12343. return;
  12344. code += '<br>'
  12345. }
  12346. }
  12347. }
  12348. });
  12349. }
  12350. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12351. pre = me.document.getElementById('coder');
  12352. domUtils.removeAttributes(pre,'id');
  12353. var tmpNode = pre.previousSibling;
  12354. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12355. domUtils.remove(tmpNode)
  12356. }
  12357. var rng = me.selection.getRange();
  12358. if(domUtils.isEmptyBlock(pre)){
  12359. rng.setStart(pre,0).setCursor(false,true)
  12360. }else{
  12361. rng.selectNodeContents(pre).select()
  12362. }
  12363. }
  12364. },
  12365. queryCommandValue : function(){
  12366. var path = this.selection.getStartElementPath();
  12367. var lang = '';
  12368. utils.each(path,function(node){
  12369. if(node.nodeName =='PRE'){
  12370. var match = node.className.match(/brush:([^;]+)/);
  12371. lang = match && match[1] ? match[1] : '';
  12372. return false;
  12373. }
  12374. });
  12375. return lang;
  12376. }
  12377. };
  12378. me.addInputRule(function(root){
  12379. utils.each(root.getNodesByTagName('pre'),function(pre){
  12380. var brs = pre.getNodesByTagName('br');
  12381. if(brs.length){
  12382. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12383. var txt = UE.uNode.createText('\n');
  12384. br.parentNode.insertBefore(txt,br);
  12385. br.parentNode.removeChild(br);
  12386. });
  12387. return;
  12388. }
  12389. if(browser.ie && browser.ie11below && browser.version > 8)
  12390. return;
  12391. var code = pre.innerText().split(/\n/);
  12392. pre.innerHTML('');
  12393. utils.each(code,function(c){
  12394. if(c.length){
  12395. pre.appendChild(UE.uNode.createText(c));
  12396. }
  12397. pre.appendChild(UE.uNode.createElement('br'))
  12398. })
  12399. })
  12400. });
  12401. me.addOutputRule(function(root){
  12402. utils.each(root.getNodesByTagName('pre'),function(pre){
  12403. var code = '';
  12404. utils.each(pre.children,function(n){
  12405. if(n.type == 'text'){
  12406. //在ie下文本内容有可能末尾带有\n要去掉
  12407. //trace:3396
  12408. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12409. }else{
  12410. if(n.tagName == 'br'){
  12411. code += '\n'
  12412. }else{
  12413. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12414. }
  12415. }
  12416. });
  12417. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12418. })
  12419. });
  12420. //不需要判断highlight的command列表
  12421. me.notNeedCodeQuery ={
  12422. help:1,
  12423. undo:1,
  12424. redo:1,
  12425. source:1,
  12426. print:1,
  12427. searchreplace:1,
  12428. fullscreen:1,
  12429. preview:1,
  12430. insertparagraph:1,
  12431. elementpath:1,
  12432. insertcode:1,
  12433. inserthtml:1,
  12434. selectall:1
  12435. };
  12436. //将queyCommamndState重置
  12437. var orgQuery = me.queryCommandState;
  12438. me.queryCommandState = function(cmd){
  12439. var me = this;
  12440. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12441. return -1;
  12442. }
  12443. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12444. };
  12445. me.addListener('beforeenterkeydown',function(){
  12446. var rng = me.selection.getRange();
  12447. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12448. if(pre){
  12449. me.fireEvent('saveScene');
  12450. if(!rng.collapsed){
  12451. rng.deleteContents();
  12452. }
  12453. if(!browser.ie || browser.ie9above){
  12454. var tmpNode = me.document.createElement('br'),pre;
  12455. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12456. var next = tmpNode.nextSibling;
  12457. if(!next && (!browser.ie || browser.version > 10)){
  12458. rng.insertNode(tmpNode.cloneNode(false));
  12459. }else{
  12460. rng.setStartAfter(tmpNode);
  12461. }
  12462. pre = tmpNode.previousSibling;
  12463. var tmp;
  12464. while(pre ){
  12465. tmp = pre;
  12466. pre = pre.previousSibling;
  12467. if(!pre || pre.nodeName == 'BR'){
  12468. pre = tmp;
  12469. break;
  12470. }
  12471. }
  12472. if(pre){
  12473. var str = '';
  12474. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12475. str += pre.nodeValue;
  12476. pre = pre.nextSibling;
  12477. }
  12478. if(pre.nodeName != 'BR'){
  12479. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12480. if(match && match[1]){
  12481. str += match[1]
  12482. }
  12483. }
  12484. if(str){
  12485. str = me.document.createTextNode(str);
  12486. rng.insertNode(str).setStartAfter(str);
  12487. }
  12488. }
  12489. rng.collapse(true).select(true);
  12490. }else{
  12491. if(browser.version > 8){
  12492. var txt = me.document.createTextNode('\n');
  12493. var start = rng.startContainer;
  12494. if(rng.startOffset == 0){
  12495. var preNode = start.previousSibling;
  12496. if(preNode){
  12497. rng.insertNode(txt);
  12498. var fillchar = me.document.createTextNode(' ');
  12499. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12500. }
  12501. }else{
  12502. rng.insertNode(txt).setStartAfter(txt);
  12503. var fillchar = me.document.createTextNode(' ');
  12504. start = rng.startContainer.childNodes[rng.startOffset];
  12505. if(start && !/^\n/.test(start.nodeValue)){
  12506. rng.setStartBefore(txt)
  12507. }
  12508. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12509. }
  12510. }else{
  12511. var tmpNode = me.document.createElement('br');
  12512. rng.insertNode(tmpNode);
  12513. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12514. rng.setStartAfter(tmpNode);
  12515. pre = tmpNode.previousSibling;
  12516. var tmp;
  12517. while(pre ){
  12518. tmp = pre;
  12519. pre = pre.previousSibling;
  12520. if(!pre || pre.nodeName == 'BR'){
  12521. pre = tmp;
  12522. break;
  12523. }
  12524. }
  12525. if(pre){
  12526. var str = '';
  12527. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12528. str += pre.nodeValue;
  12529. pre = pre.nextSibling;
  12530. }
  12531. if(pre.nodeName != 'BR'){
  12532. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12533. if(match && match[1]){
  12534. str += match[1]
  12535. }
  12536. }
  12537. str = me.document.createTextNode(str);
  12538. rng.insertNode(str).setStartAfter(str);
  12539. }
  12540. rng.collapse(true).select();
  12541. }
  12542. }
  12543. me.fireEvent('saveScene');
  12544. return true;
  12545. }
  12546. });
  12547. me.addListener('tabkeydown',function(cmd,evt){
  12548. var rng = me.selection.getRange();
  12549. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12550. if(pre){
  12551. me.fireEvent('saveScene');
  12552. if(evt.shiftKey){
  12553. }else{
  12554. if(!rng.collapsed){
  12555. var bk = rng.createBookmark();
  12556. var start = bk.start.previousSibling;
  12557. while(start){
  12558. if(pre.firstChild === start && !domUtils.isBr(start)){
  12559. pre.insertBefore(me.document.createTextNode(' '),start);
  12560. break;
  12561. }
  12562. if(domUtils.isBr(start)){
  12563. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12564. break;
  12565. }
  12566. start = start.previousSibling;
  12567. }
  12568. var end = bk.end;
  12569. start = bk.start.nextSibling;
  12570. if(pre.firstChild === bk.start){
  12571. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12572. }
  12573. while(start && start !== end){
  12574. if(domUtils.isBr(start) && start.nextSibling){
  12575. if(start.nextSibling === end){
  12576. break;
  12577. }
  12578. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12579. }
  12580. start = start.nextSibling;
  12581. }
  12582. rng.moveToBookmark(bk).select();
  12583. }else{
  12584. var tmpNode = me.document.createTextNode(' ');
  12585. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12586. }
  12587. }
  12588. me.fireEvent('saveScene');
  12589. return true;
  12590. }
  12591. });
  12592. me.addListener('beforeinserthtml',function(evtName,html){
  12593. var me = this,
  12594. rng = me.selection.getRange(),
  12595. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12596. if(pre){
  12597. if(!rng.collapsed){
  12598. rng.deleteContents()
  12599. }
  12600. var htmlstr = '';
  12601. if(browser.ie && browser.version > 8){
  12602. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12603. if(node.type =='element'){
  12604. if(node.tagName == 'br'){
  12605. htmlstr += '\n'
  12606. }else if(!dtd.$empty[node.tagName]){
  12607. utils.each(node.children,function(cn){
  12608. if(cn.type =='element'){
  12609. if(cn.tagName == 'br'){
  12610. htmlstr += '\n'
  12611. }else if(!dtd.$empty[node.tagName]){
  12612. htmlstr += cn.innerText();
  12613. }
  12614. }else{
  12615. htmlstr += cn.data
  12616. }
  12617. })
  12618. if(!/\n$/.test(htmlstr)){
  12619. htmlstr += '\n';
  12620. }
  12621. }
  12622. }else{
  12623. htmlstr += node.data + '\n'
  12624. }
  12625. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12626. htmlstr = htmlstr.replace(/\n$/,'');
  12627. }
  12628. });
  12629. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12630. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12631. }else{
  12632. var frag = me.document.createDocumentFragment();
  12633. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12634. if(node.type =='element'){
  12635. if(node.tagName == 'br'){
  12636. frag.appendChild(me.document.createElement('br'))
  12637. }else if(!dtd.$empty[node.tagName]){
  12638. utils.each(node.children,function(cn){
  12639. if(cn.type =='element'){
  12640. if(cn.tagName == 'br'){
  12641. frag.appendChild(me.document.createElement('br'))
  12642. }else if(!dtd.$empty[node.tagName]){
  12643. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12644. }
  12645. }else{
  12646. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12647. }
  12648. })
  12649. if(frag.lastChild.nodeName != 'BR'){
  12650. frag.appendChild(me.document.createElement('br'))
  12651. }
  12652. }
  12653. }else{
  12654. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12655. }
  12656. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12657. frag.removeChild(frag.lastChild)
  12658. }
  12659. });
  12660. rng.insertNode(frag).select();
  12661. }
  12662. return true;
  12663. }
  12664. });
  12665. //方向键的处理
  12666. me.addListener('keydown',function(cmd,evt){
  12667. var me = this,keyCode = evt.keyCode || evt.which;
  12668. if(keyCode == 40){
  12669. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12670. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12671. var last = pre.lastChild
  12672. while(last && last.nodeName == 'BR'){
  12673. last = last.previousSibling;
  12674. }
  12675. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12676. me.execCommand('insertparagraph');
  12677. domUtils.preventDefault(evt)
  12678. }
  12679. }
  12680. }
  12681. });
  12682. //trace:3395
  12683. me.addListener('delkeydown',function(type,evt){
  12684. var rng = this.selection.getRange();
  12685. rng.txtToElmBoundary(true);
  12686. var start = rng.startContainer;
  12687. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12688. var p = me.document.createElement('p');
  12689. domUtils.fillNode(me.document,p);
  12690. start.parentNode.insertBefore(p,start);
  12691. domUtils.remove(start);
  12692. rng.setStart(p,0).setCursor(false,true);
  12693. domUtils.preventDefault(evt);
  12694. return true;
  12695. }
  12696. })
  12697. };
  12698. // plugins/cleardoc.js
  12699. /**
  12700. * 清空文档插件
  12701. * @file
  12702. * @since 1.2.6.1
  12703. */
  12704. /**
  12705. * 清空文档
  12706. * @command cleardoc
  12707. * @method execCommand
  12708. * @param { String } cmd 命令字符串
  12709. * @example
  12710. * ```javascript
  12711. * //editor 是编辑器实例
  12712. * editor.execCommand('cleardoc');
  12713. * ```
  12714. */
  12715. UE.commands['cleardoc'] = {
  12716. execCommand : function( cmdName) {
  12717. var me = this,
  12718. enterTag = me.options.enterTag,
  12719. range = me.selection.getRange();
  12720. if(enterTag == "br"){
  12721. me.body.innerHTML = "<br/>";
  12722. range.setStart(me.body,0).setCursor();
  12723. }else{
  12724. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12725. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12726. }
  12727. setTimeout(function(){
  12728. me.fireEvent("clearDoc");
  12729. },0);
  12730. }
  12731. };
  12732. // plugins/anchor.js
  12733. /**
  12734. * 锚点插件,为UEditor提供插入锚点支持
  12735. * @file
  12736. * @since 1.2.6.1
  12737. */
  12738. UE.plugin.register('anchor', function (){
  12739. return {
  12740. bindEvents:{
  12741. 'ready':function(){
  12742. utils.cssRule('anchor',
  12743. '.anchorclass{background: url(\''
  12744. + this.options.themePath
  12745. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12746. this.document);
  12747. }
  12748. },
  12749. outputRule: function(root){
  12750. utils.each(root.getNodesByTagName('img'),function(a){
  12751. var val;
  12752. if(val = a.getAttr('anchorname')){
  12753. a.tagName = 'a';
  12754. a.setAttr({
  12755. anchorname : '',
  12756. name : val,
  12757. 'class' : ''
  12758. })
  12759. }
  12760. })
  12761. },
  12762. inputRule:function(root){
  12763. utils.each(root.getNodesByTagName('a'),function(a){
  12764. var val;
  12765. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12766. a.tagName = 'img';
  12767. a.setAttr({
  12768. anchorname :a.getAttr('name'),
  12769. 'class' : 'anchorclass'
  12770. });
  12771. a.setAttr('name')
  12772. }
  12773. })
  12774. },
  12775. commands:{
  12776. /**
  12777. * 插入锚点
  12778. * @command anchor
  12779. * @method execCommand
  12780. * @param { String } cmd 命令字符串
  12781. * @param { String } name 锚点名称字符串
  12782. * @example
  12783. * ```javascript
  12784. * //editor 是编辑器实例
  12785. * editor.execCommand('anchor', 'anchor1');
  12786. * ```
  12787. */
  12788. 'anchor':{
  12789. execCommand:function (cmd, name) {
  12790. var range = this.selection.getRange(),img = range.getClosedNode();
  12791. if (img && img.getAttribute('anchorname')) {
  12792. if (name) {
  12793. img.setAttribute('anchorname', name);
  12794. } else {
  12795. range.setStartBefore(img).setCursor();
  12796. domUtils.remove(img);
  12797. }
  12798. } else {
  12799. if (name) {
  12800. //只在选区的开始插入
  12801. var anchor = this.document.createElement('img');
  12802. range.collapse(true);
  12803. domUtils.setAttributes(anchor,{
  12804. 'anchorname':name,
  12805. 'class':'anchorclass'
  12806. });
  12807. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12808. }
  12809. }
  12810. }
  12811. }
  12812. }
  12813. }
  12814. });
  12815. // plugins/wordcount.js
  12816. ///import core
  12817. ///commands 字数统计
  12818. ///commandsName WordCount,wordCount
  12819. ///commandsTitle 字数统计
  12820. /*
  12821. * Created by JetBrains WebStorm.
  12822. * User: taoqili
  12823. * Date: 11-9-7
  12824. * Time: 下午8:18
  12825. * To change this template use File | Settings | File Templates.
  12826. */
  12827. UE.plugins['wordcount'] = function(){
  12828. var me = this;
  12829. me.setOpt('wordCount',true);
  12830. me.addListener('contentchange',function(){
  12831. me.fireEvent('wordcount');
  12832. });
  12833. var timer;
  12834. me.addListener('ready',function(){
  12835. var me = this;
  12836. domUtils.on(me.body,"keyup",function(evt){
  12837. var code = evt.keyCode||evt.which,
  12838. //忽略的按键,ctr,alt,shift,方向键
  12839. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12840. if(code in ignores) return;
  12841. clearTimeout(timer);
  12842. timer = setTimeout(function(){
  12843. me.fireEvent('wordcount');
  12844. },200)
  12845. })
  12846. });
  12847. };
  12848. // plugins/pagebreak.js
  12849. /**
  12850. * 分页功能插件
  12851. * @file
  12852. * @since 1.2.6.1
  12853. */
  12854. UE.plugins['pagebreak'] = function () {
  12855. var me = this,
  12856. notBreakTags = ['td'];
  12857. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12858. function fillNode(node){
  12859. if(domUtils.isEmptyBlock(node)){
  12860. var firstChild = node.firstChild,tmpNode;
  12861. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12862. tmpNode = firstChild;
  12863. firstChild = firstChild.firstChild;
  12864. }
  12865. !tmpNode && (tmpNode = node);
  12866. domUtils.fillNode(me.document,tmpNode);
  12867. }
  12868. }
  12869. //分页符样式添加
  12870. me.ready(function(){
  12871. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12872. });
  12873. function isHr(node){
  12874. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12875. }
  12876. me.addInputRule(function(root){
  12877. root.traversal(function(node){
  12878. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12879. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12880. node.parentNode.insertBefore(hr,node);
  12881. node.parentNode.removeChild(node)
  12882. }
  12883. })
  12884. });
  12885. me.addOutputRule(function(node){
  12886. utils.each(node.getNodesByTagName('hr'),function(n){
  12887. if(n.getAttr('class') == 'pagebreak'){
  12888. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12889. n.parentNode.insertBefore(txt,n);
  12890. n.parentNode.removeChild(n);
  12891. }
  12892. })
  12893. });
  12894. /**
  12895. * 插入分页符
  12896. * @command pagebreak
  12897. * @method execCommand
  12898. * @param { String } cmd 命令字符串
  12899. * @remind 在表格中插入分页符会把表格切分成两部分
  12900. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12901. * 以便于提交数据到服务器端后处理分页。
  12902. * @example
  12903. * ```javascript
  12904. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12905. * ```
  12906. */
  12907. me.commands['pagebreak'] = {
  12908. execCommand:function () {
  12909. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12910. domUtils.setAttributes(hr,{
  12911. 'class' : 'pagebreak',
  12912. noshade:"noshade",
  12913. size:"5"
  12914. });
  12915. domUtils.unSelectable(hr);
  12916. //table单独处理
  12917. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12918. parents = [], pN;
  12919. if (node) {
  12920. switch (node.tagName) {
  12921. case 'TD':
  12922. pN = node.parentNode;
  12923. if (!pN.previousSibling) {
  12924. var table = domUtils.findParentByTagName(pN, 'table');
  12925. // var tableWrapDiv = table.parentNode;
  12926. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12927. // && tableWrapDiv.tagName == 'DIV'
  12928. // && tableWrapDiv.getAttribute('dropdrag')
  12929. // ){
  12930. // domUtils.remove(tableWrapDiv,true);
  12931. // }
  12932. table.parentNode.insertBefore(hr, table);
  12933. parents = domUtils.findParents(hr, true);
  12934. } else {
  12935. pN.parentNode.insertBefore(hr, pN);
  12936. parents = domUtils.findParents(hr);
  12937. }
  12938. pN = parents[1];
  12939. if (hr !== pN) {
  12940. domUtils.breakParent(hr, pN);
  12941. }
  12942. //table要重写绑定一下拖拽
  12943. me.fireEvent('afteradjusttable',me.document);
  12944. }
  12945. } else {
  12946. if (!range.collapsed) {
  12947. range.deleteContents();
  12948. var start = range.startContainer;
  12949. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12950. range.setStartBefore(start).collapse(true);
  12951. domUtils.remove(start);
  12952. start = range.startContainer;
  12953. }
  12954. }
  12955. range.insertNode(hr);
  12956. var pN = hr.parentNode, nextNode;
  12957. while (!domUtils.isBody(pN)) {
  12958. domUtils.breakParent(hr, pN);
  12959. nextNode = hr.nextSibling;
  12960. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12961. domUtils.remove(nextNode);
  12962. }
  12963. pN = hr.parentNode;
  12964. }
  12965. nextNode = hr.nextSibling;
  12966. var pre = hr.previousSibling;
  12967. if(isHr(pre)){
  12968. domUtils.remove(pre);
  12969. }else{
  12970. pre && fillNode(pre);
  12971. }
  12972. if(!nextNode){
  12973. var p = me.document.createElement('p');
  12974. hr.parentNode.appendChild(p);
  12975. domUtils.fillNode(me.document,p);
  12976. range.setStart(p,0).collapse(true);
  12977. }else{
  12978. if(isHr(nextNode)){
  12979. domUtils.remove(nextNode);
  12980. }else{
  12981. fillNode(nextNode);
  12982. }
  12983. range.setEndAfter(hr).collapse(false);
  12984. }
  12985. range.select(true);
  12986. }
  12987. }
  12988. };
  12989. };
  12990. // plugins/wordimage.js
  12991. ///import core
  12992. ///commands 本地图片引导上传
  12993. ///commandsName WordImage
  12994. ///commandsTitle 本地图片引导上传
  12995. ///commandsDialog dialogs\wordimage
  12996. UE.plugin.register('wordimage',function(){
  12997. var me = this,
  12998. images = [];
  12999. return {
  13000. commands : {
  13001. 'wordimage':{
  13002. execCommand:function () {
  13003. var images = domUtils.getElementsByTagName(me.body, "img");
  13004. var urlList = [];
  13005. for (var i = 0, ci; ci = images[i++];) {
  13006. var url = ci.getAttribute("word_img");
  13007. url && urlList.push(url);
  13008. }
  13009. return urlList;
  13010. },
  13011. queryCommandState:function () {
  13012. images = domUtils.getElementsByTagName(me.body, "img");
  13013. for (var i = 0, ci; ci = images[i++];) {
  13014. if (ci.getAttribute("word_img")) {
  13015. return 1;
  13016. }
  13017. }
  13018. return -1;
  13019. },
  13020. notNeedUndo:true
  13021. }
  13022. },
  13023. inputRule : function (root) {
  13024. utils.each(root.getNodesByTagName('img'), function (img) {
  13025. var attrs = img.attrs,
  13026. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13027. opt = me.options,
  13028. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13029. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13030. img.setAttr({
  13031. width:attrs.width,
  13032. height:attrs.height,
  13033. alt:attrs.alt,
  13034. word_img: attrs.src,
  13035. src:src,
  13036. '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'
  13037. })
  13038. }
  13039. })
  13040. }
  13041. }
  13042. });
  13043. // plugins/dragdrop.js
  13044. UE.plugins['dragdrop'] = function (){
  13045. var me = this;
  13046. me.ready(function(){
  13047. domUtils.on(this.body,'dragend',function(){
  13048. var rng = me.selection.getRange();
  13049. var node = rng.getClosedNode()||me.selection.getStart();
  13050. if(node && node.tagName == 'IMG'){
  13051. var pre = node.previousSibling,next;
  13052. while(next = node.nextSibling){
  13053. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  13054. domUtils.remove(next)
  13055. }else{
  13056. break;
  13057. }
  13058. }
  13059. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13060. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13061. pre.appendChild(node);
  13062. domUtils.moveChild(next,pre);
  13063. domUtils.remove(next);
  13064. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13065. next.insertBefore(node,next.firstChild);
  13066. }
  13067. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13068. domUtils.remove(pre)
  13069. }
  13070. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13071. domUtils.remove(next)
  13072. }
  13073. rng.selectNode(node).select();
  13074. me.fireEvent('saveScene');
  13075. }
  13076. }
  13077. })
  13078. });
  13079. me.addListener('keyup', function(type, evt) {
  13080. var keyCode = evt.keyCode || evt.which;
  13081. if (keyCode == 13) {
  13082. var rng = me.selection.getRange(),node;
  13083. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13084. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13085. domUtils.removeStyle(node,'text-align')
  13086. }
  13087. }
  13088. }
  13089. })
  13090. };
  13091. // plugins/undo.js
  13092. /**
  13093. * undo redo
  13094. * @file
  13095. * @since 1.2.6.1
  13096. */
  13097. /**
  13098. * 撤销上一次执行的命令
  13099. * @command undo
  13100. * @method execCommand
  13101. * @param { String } cmd 命令字符串
  13102. * @example
  13103. * ```javascript
  13104. * editor.execCommand( 'undo' );
  13105. * ```
  13106. */
  13107. /**
  13108. * 重做上一次执行的命令
  13109. * @command redo
  13110. * @method execCommand
  13111. * @param { String } cmd 命令字符串
  13112. * @example
  13113. * ```javascript
  13114. * editor.execCommand( 'redo' );
  13115. * ```
  13116. */
  13117. UE.plugins['undo'] = function () {
  13118. var saveSceneTimer;
  13119. var me = this,
  13120. maxUndoCount = me.options.maxUndoCount || 20,
  13121. maxInputCount = me.options.maxInputCount || 20,
  13122. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13123. var noNeedFillCharTags = {
  13124. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13125. };
  13126. var orgState = me.options.autoClearEmptyNode;
  13127. function compareAddr(indexA, indexB) {
  13128. if (indexA.length != indexB.length)
  13129. return 0;
  13130. for (var i = 0, l = indexA.length; i < l; i++) {
  13131. if (indexA[i] != indexB[i])
  13132. return 0
  13133. }
  13134. return 1;
  13135. }
  13136. function compareRangeAddress(rngAddrA, rngAddrB) {
  13137. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13138. return 0;
  13139. }
  13140. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13141. return 0;
  13142. }
  13143. return 1;
  13144. }
  13145. function UndoManager() {
  13146. this.list = [];
  13147. this.index = 0;
  13148. this.hasUndo = false;
  13149. this.hasRedo = false;
  13150. this.undo = function () {
  13151. if (this.hasUndo) {
  13152. if (!this.list[this.index - 1] && this.list.length == 1) {
  13153. this.reset();
  13154. return;
  13155. }
  13156. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13157. this.index--;
  13158. if (this.index == 0) {
  13159. return this.restore(0);
  13160. }
  13161. }
  13162. this.restore(--this.index);
  13163. }
  13164. };
  13165. this.redo = function () {
  13166. if (this.hasRedo) {
  13167. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13168. this.index++;
  13169. if (this.index == this.list.length - 1) {
  13170. return this.restore(this.index);
  13171. }
  13172. }
  13173. this.restore(++this.index);
  13174. }
  13175. };
  13176. this.restore = function () {
  13177. var me = this.editor;
  13178. var scene = this.list[this.index];
  13179. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13180. me.options.autoClearEmptyNode = false;
  13181. me.filterInputRule(root);
  13182. me.options.autoClearEmptyNode = orgState;
  13183. //trace:873
  13184. //去掉展位符
  13185. me.document.body.innerHTML = root.toHtml();
  13186. me.fireEvent('afterscencerestore');
  13187. //处理undo后空格不展位的问题
  13188. if (browser.ie) {
  13189. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13190. if(domUtils.isEmptyNode(node)){
  13191. domUtils.fillNode(me.document, node);
  13192. }
  13193. })
  13194. }
  13195. try{
  13196. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13197. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13198. }catch(e){}
  13199. this.update();
  13200. this.clearKey();
  13201. //不能把自己reset了
  13202. me.fireEvent('reset', true);
  13203. };
  13204. this.getScene = function () {
  13205. var me = this.editor;
  13206. var rng = me.selection.getRange(),
  13207. rngAddress = rng.createAddress(false,true);
  13208. me.fireEvent('beforegetscene');
  13209. var root = UE.htmlparser(me.body.innerHTML);
  13210. me.options.autoClearEmptyNode = false;
  13211. me.filterOutputRule(root);
  13212. me.options.autoClearEmptyNode = orgState;
  13213. var cont = root.toHtml();
  13214. //trace:3461
  13215. //这个会引起回退时导致空格丢失的情况
  13216. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13217. me.fireEvent('aftergetscene');
  13218. return {
  13219. address:rngAddress,
  13220. content:cont
  13221. }
  13222. };
  13223. this.save = function (notCompareRange,notSetCursor) {
  13224. clearTimeout(saveSceneTimer);
  13225. var currentScene = this.getScene(notSetCursor),
  13226. lastScene = this.list[this.index];
  13227. if(lastScene && lastScene.content != currentScene.content){
  13228. me.trigger('contentchange')
  13229. }
  13230. //内容相同位置相同不存
  13231. if (lastScene && lastScene.content == currentScene.content &&
  13232. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13233. ) {
  13234. return;
  13235. }
  13236. this.list = this.list.slice(0, this.index + 1);
  13237. this.list.push(currentScene);
  13238. //如果大于最大数量了,就把最前的剔除
  13239. if (this.list.length > maxUndoCount) {
  13240. this.list.shift();
  13241. }
  13242. this.index = this.list.length - 1;
  13243. this.clearKey();
  13244. //跟新undo/redo状态
  13245. this.update();
  13246. };
  13247. this.update = function () {
  13248. this.hasRedo = !!this.list[this.index + 1];
  13249. this.hasUndo = !!this.list[this.index - 1];
  13250. };
  13251. this.reset = function () {
  13252. this.list = [];
  13253. this.index = 0;
  13254. this.hasUndo = false;
  13255. this.hasRedo = false;
  13256. this.clearKey();
  13257. };
  13258. this.clearKey = function () {
  13259. keycont = 0;
  13260. lastKeyCode = null;
  13261. };
  13262. }
  13263. me.undoManger = new UndoManager();
  13264. me.undoManger.editor = me;
  13265. function saveScene() {
  13266. this.undoManger.save();
  13267. }
  13268. me.addListener('saveScene', function () {
  13269. var args = Array.prototype.splice.call(arguments,1);
  13270. this.undoManger.save.apply(this.undoManger,args);
  13271. });
  13272. // me.addListener('beforeexeccommand', saveScene);
  13273. // me.addListener('afterexeccommand', saveScene);
  13274. me.addListener('reset', function (type, exclude) {
  13275. if (!exclude) {
  13276. this.undoManger.reset();
  13277. }
  13278. });
  13279. me.commands['redo'] = me.commands['undo'] = {
  13280. execCommand:function (cmdName) {
  13281. this.undoManger[cmdName]();
  13282. },
  13283. queryCommandState:function (cmdName) {
  13284. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13285. },
  13286. notNeedUndo:1
  13287. };
  13288. var keys = {
  13289. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13290. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13291. 37:1, 38:1, 39:1, 40:1
  13292. },
  13293. keycont = 0,
  13294. lastKeyCode;
  13295. //输入法状态下不计算字符数
  13296. var inputType = false;
  13297. me.addListener('ready', function () {
  13298. domUtils.on(this.body, 'compositionstart', function () {
  13299. inputType = true;
  13300. });
  13301. domUtils.on(this.body, 'compositionend', function () {
  13302. inputType = false;
  13303. })
  13304. });
  13305. //快捷键
  13306. me.addshortcutkey({
  13307. "Undo":"ctrl+90", //undo
  13308. "Redo":"ctrl+89" //redo
  13309. });
  13310. var isCollapsed = true;
  13311. me.addListener('keydown', function (type, evt) {
  13312. var me = this;
  13313. var keyCode = evt.keyCode || evt.which;
  13314. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13315. if (inputType)
  13316. return;
  13317. if(!me.selection.getRange().collapsed){
  13318. me.undoManger.save(false,true);
  13319. isCollapsed = false;
  13320. return;
  13321. }
  13322. if (me.undoManger.list.length == 0) {
  13323. me.undoManger.save(true);
  13324. }
  13325. clearTimeout(saveSceneTimer);
  13326. function save(cont){
  13327. cont.undoManger.save(false,true);
  13328. cont.fireEvent('selectionchange');
  13329. }
  13330. saveSceneTimer = setTimeout(function(){
  13331. if(inputType){
  13332. var interalTimer = setInterval(function(){
  13333. if(!inputType){
  13334. save(me);
  13335. clearInterval(interalTimer)
  13336. }
  13337. },300)
  13338. return;
  13339. }
  13340. save(me);
  13341. },200);
  13342. lastKeyCode = keyCode;
  13343. keycont++;
  13344. if (keycont >= maxInputCount ) {
  13345. save(me)
  13346. }
  13347. }
  13348. });
  13349. me.addListener('keyup', function (type, evt) {
  13350. var keyCode = evt.keyCode || evt.which;
  13351. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13352. if (inputType)
  13353. return;
  13354. if(!isCollapsed){
  13355. this.undoManger.save(false,true);
  13356. isCollapsed = true;
  13357. }
  13358. }
  13359. });
  13360. //扩展实例,添加关闭和开启命令undo
  13361. me.stopCmdUndo = function(){
  13362. me.__hasEnterExecCommand = true;
  13363. };
  13364. me.startCmdUndo = function(){
  13365. me.__hasEnterExecCommand = false;
  13366. }
  13367. };
  13368. // plugins/copy.js
  13369. UE.plugin.register('copy', function () {
  13370. var me = this;
  13371. function initZeroClipboard() {
  13372. ZeroClipboard.config({
  13373. debug: false,
  13374. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13375. });
  13376. var client = me.zeroclipboard = new ZeroClipboard();
  13377. // 复制内容
  13378. client.on('copy', function (e) {
  13379. var client = e.client,
  13380. rng = me.selection.getRange(),
  13381. div = document.createElement('div');
  13382. div.appendChild(rng.cloneContents());
  13383. client.setText(div.innerText || div.textContent);
  13384. client.setHtml(div.innerHTML);
  13385. rng.select();
  13386. });
  13387. // hover事件传递到target
  13388. client.on('mouseover mouseout', function (e) {
  13389. var target = e.target;
  13390. if (e.type == 'mouseover') {
  13391. domUtils.addClass(target, 'edui-state-hover');
  13392. } else if (e.type == 'mouseout') {
  13393. domUtils.removeClasses(target, 'edui-state-hover');
  13394. }
  13395. });
  13396. // flash加载不成功
  13397. client.on('wrongflash noflash', function () {
  13398. ZeroClipboard.destroy();
  13399. });
  13400. }
  13401. return {
  13402. bindEvents: {
  13403. 'ready': function () {
  13404. if (!browser.ie) {
  13405. if (window.ZeroClipboard) {
  13406. initZeroClipboard();
  13407. } else {
  13408. utils.loadFile(document, {
  13409. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13410. tag: "script",
  13411. type: "text/javascript",
  13412. defer: "defer"
  13413. }, function () {
  13414. initZeroClipboard();
  13415. });
  13416. }
  13417. }
  13418. }
  13419. },
  13420. commands: {
  13421. 'copy': {
  13422. execCommand: function (cmd) {
  13423. if (!me.document.execCommand('copy')) {
  13424. alert(me.getLang('copymsg'));
  13425. }
  13426. }
  13427. }
  13428. }
  13429. }
  13430. });
  13431. // plugins/paste.js
  13432. ///import core
  13433. ///import plugins/inserthtml.js
  13434. ///import plugins/undo.js
  13435. ///import plugins/serialize.js
  13436. ///commands 粘贴
  13437. ///commandsName PastePlain
  13438. ///commandsTitle 纯文本粘贴模式
  13439. /**
  13440. * @description 粘贴
  13441. * @author zhanyi
  13442. */
  13443. UE.plugins['paste'] = function () {
  13444. function getClipboardData(callback) {
  13445. var doc = this.document;
  13446. if (doc.getElementById('baidu_pastebin')) {
  13447. return;
  13448. }
  13449. var range = this.selection.getRange(),
  13450. bk = range.createBookmark(),
  13451. //创建剪贴的容器div
  13452. pastebin = doc.createElement('div');
  13453. pastebin.id = 'baidu_pastebin';
  13454. // Safari 要求div必须有内容,才能粘贴内容进来
  13455. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13456. doc.body.appendChild(pastebin);
  13457. //trace:717 隐藏的span不能得到top
  13458. //bk.start.innerHTML = '&nbsp;';
  13459. bk.start.style.display = '';
  13460. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13461. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13462. domUtils.getXY(bk.start).y + 'px';
  13463. range.selectNodeContents(pastebin).select(true);
  13464. setTimeout(function () {
  13465. if (browser.webkit) {
  13466. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13467. if (domUtils.isEmptyNode(pi)) {
  13468. domUtils.remove(pi);
  13469. } else {
  13470. pastebin = pi;
  13471. break;
  13472. }
  13473. }
  13474. }
  13475. try {
  13476. pastebin.parentNode.removeChild(pastebin);
  13477. } catch (e) {
  13478. }
  13479. range.moveToBookmark(bk).select(true);
  13480. callback(pastebin);
  13481. }, 0);
  13482. }
  13483. var me = this;
  13484. me.setOpt({
  13485. retainOnlyLabelPasted : false
  13486. });
  13487. var txtContent, htmlContent, address;
  13488. function getPureHtml(html){
  13489. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13490. tagName = tagName.toLowerCase();
  13491. if ({img: 1}[tagName]) {
  13492. return a;
  13493. }
  13494. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13495. if ({
  13496. 'src': 1,
  13497. 'href': 1,
  13498. 'name': 1
  13499. }[atr.toLowerCase()]) {
  13500. return atr + '=' + val + ' '
  13501. }
  13502. return ''
  13503. });
  13504. if ({
  13505. 'span': 1,
  13506. 'div': 1
  13507. }[tagName]) {
  13508. return ''
  13509. } else {
  13510. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13511. }
  13512. });
  13513. }
  13514. function filter(div) {
  13515. var html;
  13516. if (div.firstChild) {
  13517. //去掉cut中添加的边界值
  13518. var nodes = domUtils.getElementsByTagName(div, 'span');
  13519. for (var i = 0, ni; ni = nodes[i++];) {
  13520. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13521. domUtils.remove(ni);
  13522. }
  13523. }
  13524. if (browser.webkit) {
  13525. var brs = div.querySelectorAll('div br');
  13526. for (var i = 0, bi; bi = brs[i++];) {
  13527. var pN = bi.parentNode;
  13528. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13529. pN.innerHTML = '<p><br/></p>';
  13530. domUtils.remove(pN);
  13531. }
  13532. }
  13533. var divs = div.querySelectorAll('#baidu_pastebin');
  13534. for (var i = 0, di; di = divs[i++];) {
  13535. var tmpP = me.document.createElement('p');
  13536. di.parentNode.insertBefore(tmpP, di);
  13537. while (di.firstChild) {
  13538. tmpP.appendChild(di.firstChild);
  13539. }
  13540. domUtils.remove(di);
  13541. }
  13542. var metas = div.querySelectorAll('meta');
  13543. for (var i = 0, ci; ci = metas[i++];) {
  13544. domUtils.remove(ci);
  13545. }
  13546. var brs = div.querySelectorAll('br');
  13547. for (i = 0; ci = brs[i++];) {
  13548. if (/^apple-/i.test(ci.className)) {
  13549. domUtils.remove(ci);
  13550. }
  13551. }
  13552. }
  13553. if (browser.gecko) {
  13554. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13555. for (i = 0; ci = dirtyNodes[i++];) {
  13556. ci.removeAttribute('_moz_dirty');
  13557. }
  13558. }
  13559. if (!browser.ie) {
  13560. var spans = div.querySelectorAll('span.Apple-style-span');
  13561. for (var i = 0, ci; ci = spans[i++];) {
  13562. domUtils.remove(ci, true);
  13563. }
  13564. }
  13565. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13566. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13567. //过滤word粘贴过来的冗余属性
  13568. html = UE.filterWord(html);
  13569. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13570. var root = UE.htmlparser(html);
  13571. //如果给了过滤规则就先进行过滤
  13572. if (me.options.filterRules) {
  13573. UE.filterNode(root, me.options.filterRules);
  13574. }
  13575. //执行默认的处理
  13576. me.filterInputRule(root);
  13577. //针对chrome的处理
  13578. if (browser.webkit) {
  13579. var br = root.lastChild();
  13580. if (br && br.type == 'element' && br.tagName == 'br') {
  13581. root.removeChild(br)
  13582. }
  13583. utils.each(me.body.querySelectorAll('div'), function (node) {
  13584. if (domUtils.isEmptyBlock(node)) {
  13585. domUtils.remove(node,true)
  13586. }
  13587. })
  13588. }
  13589. html = {'html': root.toHtml()};
  13590. me.fireEvent('beforepaste', html, root);
  13591. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13592. if(!html.html){
  13593. return;
  13594. }
  13595. root = UE.htmlparser(html.html,true);
  13596. //如果开启了纯文本模式
  13597. if (me.queryCommandState('pasteplain') === 1) {
  13598. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13599. } else {
  13600. //文本模式
  13601. UE.filterNode(root, me.options.filterTxtRules);
  13602. txtContent = root.toHtml();
  13603. //完全模式
  13604. htmlContent = html.html;
  13605. address = me.selection.getRange().createAddress(true);
  13606. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13607. }
  13608. me.fireEvent("afterpaste", html);
  13609. }
  13610. }
  13611. me.addListener('pasteTransfer', function (cmd, plainType) {
  13612. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13613. var range = me.selection.getRange();
  13614. range.moveToAddress(address, true);
  13615. if (!range.collapsed) {
  13616. while (!domUtils.isBody(range.startContainer)
  13617. ) {
  13618. var start = range.startContainer;
  13619. if(start.nodeType == 1){
  13620. start = start.childNodes[range.startOffset];
  13621. if(!start){
  13622. range.setStartBefore(range.startContainer);
  13623. continue;
  13624. }
  13625. var pre = start.previousSibling;
  13626. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13627. range.setStartBefore(pre)
  13628. }
  13629. }
  13630. if(range.startOffset == 0){
  13631. range.setStartBefore(range.startContainer);
  13632. }else{
  13633. break;
  13634. }
  13635. }
  13636. while (!domUtils.isBody(range.endContainer)
  13637. ) {
  13638. var end = range.endContainer;
  13639. if(end.nodeType == 1){
  13640. end = end.childNodes[range.endOffset];
  13641. if(!end){
  13642. range.setEndAfter(range.endContainer);
  13643. continue;
  13644. }
  13645. var next = end.nextSibling;
  13646. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13647. range.setEndAfter(next)
  13648. }
  13649. }
  13650. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13651. range.setEndAfter(range.endContainer);
  13652. }else{
  13653. break;
  13654. }
  13655. }
  13656. }
  13657. range.deleteContents();
  13658. range.select(true);
  13659. me.__hasEnterExecCommand = true;
  13660. var html = htmlContent;
  13661. if (plainType === 2 ) {
  13662. html = getPureHtml(html);
  13663. } else if (plainType) {
  13664. html = txtContent;
  13665. }
  13666. me.execCommand('inserthtml', html, true);
  13667. me.__hasEnterExecCommand = false;
  13668. var rng = me.selection.getRange();
  13669. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13670. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13671. ) {
  13672. rng.setStartBefore(rng.startContainer);
  13673. }
  13674. var tmpAddress = rng.createAddress(true);
  13675. address.endAddress = tmpAddress.startAddress;
  13676. }
  13677. });
  13678. me.addListener('ready', function () {
  13679. domUtils.on(me.body, 'cut', function () {
  13680. var range = me.selection.getRange();
  13681. if (!range.collapsed && me.undoManger) {
  13682. me.undoManger.save();
  13683. }
  13684. });
  13685. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13686. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13687. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13688. return;
  13689. }
  13690. getClipboardData.call(me, function (div) {
  13691. filter(div);
  13692. });
  13693. });
  13694. });
  13695. me.commands['paste'] = {
  13696. execCommand: function (cmd) {
  13697. if (browser.ie) {
  13698. getClipboardData.call(me, function (div) {
  13699. filter(div);
  13700. });
  13701. me.document.execCommand('paste');
  13702. } else {
  13703. alert(me.getLang('pastemsg'));
  13704. }
  13705. }
  13706. }
  13707. };
  13708. // plugins/puretxtpaste.js
  13709. /**
  13710. * 纯文本粘贴插件
  13711. * @file
  13712. * @since 1.2.6.1
  13713. */
  13714. UE.plugins['pasteplain'] = function(){
  13715. var me = this;
  13716. me.setOpt({
  13717. 'pasteplain':false,
  13718. 'filterTxtRules' : function(){
  13719. function transP(node){
  13720. node.tagName = 'p';
  13721. node.setStyle();
  13722. }
  13723. function removeNode(node){
  13724. node.parentNode.removeChild(node,true)
  13725. }
  13726. return {
  13727. //直接删除及其字节点内容
  13728. '-' : 'script style object iframe embed input select',
  13729. 'p': {$:{}},
  13730. 'br':{$:{}},
  13731. div: function (node) {
  13732. var tmpNode, p = UE.uNode.createElement('p');
  13733. while (tmpNode = node.firstChild()) {
  13734. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13735. p.appendChild(tmpNode);
  13736. } else {
  13737. if (p.firstChild()) {
  13738. node.parentNode.insertBefore(p, node);
  13739. p = UE.uNode.createElement('p');
  13740. } else {
  13741. node.parentNode.insertBefore(tmpNode, node);
  13742. }
  13743. }
  13744. }
  13745. if (p.firstChild()) {
  13746. node.parentNode.insertBefore(p, node);
  13747. }
  13748. node.parentNode.removeChild(node);
  13749. },
  13750. ol: removeNode,
  13751. ul: removeNode,
  13752. dl:removeNode,
  13753. dt:removeNode,
  13754. dd:removeNode,
  13755. 'li':removeNode,
  13756. 'caption':transP,
  13757. 'th':transP,
  13758. 'tr':transP,
  13759. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13760. 'td':function(node){
  13761. //没有内容的td直接删掉
  13762. var txt = !!node.innerText();
  13763. if(txt){
  13764. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13765. }
  13766. node.parentNode.removeChild(node,node.innerText())
  13767. }
  13768. }
  13769. }()
  13770. });
  13771. //暂时这里支持一下老版本的属性
  13772. var pasteplain = me.options.pasteplain;
  13773. /**
  13774. * 启用或取消纯文本粘贴模式
  13775. * @command pasteplain
  13776. * @method execCommand
  13777. * @param { String } cmd 命令字符串
  13778. * @example
  13779. * ```javascript
  13780. * editor.queryCommandState( 'pasteplain' );
  13781. * ```
  13782. */
  13783. /**
  13784. * 查询当前是否处于纯文本粘贴模式
  13785. * @command pasteplain
  13786. * @method queryCommandState
  13787. * @param { String } cmd 命令字符串
  13788. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13789. * @example
  13790. * ```javascript
  13791. * editor.queryCommandState( 'pasteplain' );
  13792. * ```
  13793. */
  13794. me.commands['pasteplain'] = {
  13795. queryCommandState: function (){
  13796. return pasteplain ? 1 : 0;
  13797. },
  13798. execCommand: function (){
  13799. pasteplain = !pasteplain|0;
  13800. },
  13801. notNeedUndo : 1
  13802. };
  13803. };
  13804. // plugins/list.js
  13805. /**
  13806. * 有序列表,无序列表插件
  13807. * @file
  13808. * @since 1.2.6.1
  13809. */
  13810. UE.plugins['list'] = function () {
  13811. var me = this,
  13812. notExchange = {
  13813. 'TD':1,
  13814. 'PRE':1,
  13815. 'BLOCKQUOTE':1
  13816. };
  13817. var customStyle = {
  13818. 'cn' : 'cn-1-',
  13819. 'cn1' : 'cn-2-',
  13820. 'cn2' : 'cn-3-',
  13821. 'num': 'num-1-',
  13822. 'num1' : 'num-2-',
  13823. 'num2' : 'num-3-',
  13824. 'dash' : 'dash',
  13825. 'dot':'dot'
  13826. };
  13827. me.setOpt( {
  13828. 'autoTransWordToList':false,
  13829. 'insertorderedlist':{
  13830. 'num':'',
  13831. 'num1':'',
  13832. 'num2':'',
  13833. 'cn':'',
  13834. 'cn1':'',
  13835. 'cn2':'',
  13836. 'decimal':'',
  13837. 'lower-alpha':'',
  13838. 'lower-roman':'',
  13839. 'upper-alpha':'',
  13840. 'upper-roman':''
  13841. },
  13842. 'insertunorderedlist':{
  13843. 'circle':'',
  13844. 'disc':'',
  13845. 'square':'',
  13846. 'dash' : '',
  13847. 'dot':''
  13848. },
  13849. listDefaultPaddingLeft : '30',
  13850. listiconpath : 'http://bs.baidu.com/listicon/',
  13851. maxListLevel : -1,//-1不限制
  13852. disablePInList:false
  13853. } );
  13854. function listToArray(list){
  13855. var arr = [];
  13856. for(var p in list){
  13857. arr.push(p)
  13858. }
  13859. return arr;
  13860. }
  13861. var listStyle = {
  13862. 'OL':listToArray(me.options.insertorderedlist),
  13863. 'UL':listToArray(me.options.insertunorderedlist)
  13864. };
  13865. var liiconpath = me.options.listiconpath;
  13866. //根据用户配置,调整customStyle
  13867. for(var s in customStyle){
  13868. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13869. delete customStyle[s];
  13870. }
  13871. }
  13872. me.ready(function () {
  13873. var customCss = [];
  13874. for(var p in customStyle){
  13875. if(p == 'dash' || p == 'dot'){
  13876. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13877. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13878. }else{
  13879. for(var i= 0;i<99;i++){
  13880. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13881. }
  13882. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13883. }
  13884. switch(p){
  13885. case 'cn':
  13886. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13887. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13888. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13889. break;
  13890. case 'cn1':
  13891. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13892. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13893. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13894. break;
  13895. case 'cn2':
  13896. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13897. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13898. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13899. break;
  13900. case 'num':
  13901. case 'num1':
  13902. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13903. break;
  13904. case 'num2':
  13905. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13906. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13907. break;
  13908. case 'dash':
  13909. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13910. break;
  13911. case 'dot':
  13912. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13913. }
  13914. }
  13915. customCss.push('.list-paddingleft-1{padding-left:0}');
  13916. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13917. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13918. //如果不给宽度会在自定应样式里出现滚动条
  13919. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13920. });
  13921. //单独处理剪切的问题
  13922. me.ready(function(){
  13923. domUtils.on(me.body,'cut',function(){
  13924. setTimeout(function(){
  13925. var rng = me.selection.getRange(),li;
  13926. //trace:3416
  13927. if(!rng.collapsed){
  13928. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13929. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13930. var pn = li.parentNode,node;
  13931. if(node = pn.previousSibling){
  13932. domUtils.remove(pn);
  13933. rng.setStartAtLast(node).collapse(true);
  13934. rng.select(true);
  13935. }else if(node = pn.nextSibling){
  13936. domUtils.remove(pn);
  13937. rng.setStartAtFirst(node).collapse(true);
  13938. rng.select(true);
  13939. }else{
  13940. var tmpNode = me.document.createElement('p');
  13941. domUtils.fillNode(me.document,tmpNode);
  13942. pn.parentNode.insertBefore(tmpNode,pn);
  13943. domUtils.remove(pn);
  13944. rng.setStart(tmpNode,0).collapse(true);
  13945. rng.select(true);
  13946. }
  13947. }
  13948. }
  13949. }
  13950. })
  13951. })
  13952. });
  13953. function getStyle(node){
  13954. var cls = node.className;
  13955. if(domUtils.hasClass(node,/custom_/)){
  13956. return cls.match(/custom_(\w+)/)[1]
  13957. }
  13958. return domUtils.getStyle(node, 'list-style-type')
  13959. }
  13960. me.addListener('beforepaste',function(type,html){
  13961. var me = this,
  13962. rng = me.selection.getRange(),li;
  13963. var root = UE.htmlparser(html.html,true);
  13964. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13965. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13966. utils.each(root.getNodesByTagName(tagName),function(n){
  13967. n.tagName = list.tagName;
  13968. n.setAttr();
  13969. if(n.parentNode === root){
  13970. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13971. }else{
  13972. var className = n.parentNode.getAttr('class');
  13973. if(className && /custom_/.test(className)){
  13974. type = className.match(/custom_(\w+)/)[1]
  13975. }else{
  13976. type = n.parentNode.getStyle('list-style-type');
  13977. }
  13978. if(!type){
  13979. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13980. }
  13981. }
  13982. var index = utils.indexOf(listStyle[list.tagName], type);
  13983. if(n.parentNode !== root)
  13984. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13985. var currentStyle = listStyle[list.tagName][index];
  13986. if(customStyle[currentStyle]){
  13987. n.setAttr('class', 'custom_' + currentStyle)
  13988. }else{
  13989. n.setStyle('list-style-type',currentStyle)
  13990. }
  13991. })
  13992. }
  13993. html.html = root.toHtml();
  13994. });
  13995. //导出时,去掉p标签
  13996. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13997. utils.each(root.getNodesByTagName('li'),function(li){
  13998. var newChildrens = [],index=0;
  13999. utils.each(li.children,function(n){
  14000. if(n.tagName == 'p'){
  14001. var tmpNode;
  14002. while(tmpNode = n.children.pop()) {
  14003. newChildrens.splice(index,0,tmpNode);
  14004. tmpNode.parentNode = li;
  14005. lastNode = tmpNode;
  14006. }
  14007. tmpNode = newChildrens[newChildrens.length-1];
  14008. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  14009. var br = UE.uNode.createElement('br');
  14010. br.parentNode = li;
  14011. newChildrens.push(br);
  14012. }
  14013. index = newChildrens.length;
  14014. }
  14015. });
  14016. if(newChildrens.length){
  14017. li.children = newChildrens;
  14018. }
  14019. });
  14020. });
  14021. //进入编辑器的li要套p标签
  14022. me.addInputRule(function(root){
  14023. utils.each(root.getNodesByTagName('li'),function(li){
  14024. var tmpP = UE.uNode.createElement('p');
  14025. for(var i= 0,ci;ci=li.children[i];){
  14026. if(ci.type == 'text' || dtd.p[ci.tagName]){
  14027. tmpP.appendChild(ci);
  14028. }else{
  14029. if(tmpP.firstChild()){
  14030. li.insertBefore(tmpP,ci);
  14031. tmpP = UE.uNode.createElement('p');
  14032. i = i + 2;
  14033. }else{
  14034. i++;
  14035. }
  14036. }
  14037. }
  14038. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  14039. li.appendChild(tmpP);
  14040. }
  14041. //trace:3357
  14042. //p不能为空
  14043. if (!tmpP.firstChild()) {
  14044. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14045. }
  14046. //去掉末尾的空白
  14047. var p = li.firstChild();
  14048. var lastChild = p.lastChild();
  14049. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  14050. p.removeChild(lastChild)
  14051. }
  14052. });
  14053. if(me.options.autoTransWordToList){
  14054. var orderlisttype = {
  14055. 'num1':/^\d+\)/,
  14056. 'decimal':/^\d+\./,
  14057. 'lower-alpha':/^[a-z]+\)/,
  14058. 'upper-alpha':/^[A-Z]+\./,
  14059. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14060. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14061. },
  14062. unorderlisttype = {
  14063. 'square':'n'
  14064. };
  14065. function checkListType(content,container){
  14066. var span = container.firstChild();
  14067. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14068. for(var p in unorderlisttype){
  14069. if(unorderlisttype[p] == span.data){
  14070. return p
  14071. }
  14072. }
  14073. return 'disc'
  14074. }
  14075. for(var p in orderlisttype){
  14076. if(orderlisttype[p].test(content)){
  14077. return p;
  14078. }
  14079. }
  14080. }
  14081. utils.each(root.getNodesByTagName('p'),function(node){
  14082. if(node.getAttr('class') != 'MsoListParagraph'){
  14083. return
  14084. }
  14085. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14086. node.setStyle('margin','');
  14087. node.setStyle('margin-left','');
  14088. node.setAttr('class','');
  14089. function appendLi(list,p,type){
  14090. if(list.tagName == 'ol'){
  14091. if(browser.ie){
  14092. var first = p.firstChild();
  14093. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14094. p.removeChild(first);
  14095. }
  14096. }else{
  14097. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14098. }
  14099. }else{
  14100. p.removeChild(p.firstChild())
  14101. }
  14102. var li = UE.uNode.createElement('li');
  14103. li.appendChild(p);
  14104. list.appendChild(li);
  14105. }
  14106. var tmp = node,type,cacheNode = node;
  14107. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14108. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14109. if(customStyle[type]){
  14110. list.setAttr('class','custom_'+type)
  14111. }else{
  14112. list.setStyle('list-style-type',type)
  14113. }
  14114. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14115. tmp = node.nextSibling();
  14116. if(!tmp){
  14117. node.parentNode.insertBefore(list,node)
  14118. }
  14119. appendLi(list,node,type);
  14120. node = tmp;
  14121. }
  14122. if(!list.parentNode && node && node.parentNode){
  14123. node.parentNode.insertBefore(list,node)
  14124. }
  14125. }
  14126. var span = cacheNode.firstChild();
  14127. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14128. span.parentNode.removeChild(span)
  14129. }
  14130. })
  14131. }
  14132. });
  14133. //调整索引标签
  14134. me.addListener('contentchange',function(){
  14135. adjustListStyle(me.document)
  14136. });
  14137. function adjustListStyle(doc,ignore){
  14138. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14139. if(!domUtils.inDoc(node,doc))
  14140. return;
  14141. var parent = node.parentNode;
  14142. if(parent.tagName == node.tagName){
  14143. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14144. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14145. if(nodeStyleType == parentStyleType){
  14146. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14147. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14148. setListStyle(node,listStyle[node.tagName][styleIndex])
  14149. }
  14150. }
  14151. var index = 0,type = 2;
  14152. if( domUtils.hasClass(node,/custom_/)){
  14153. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14154. type = 1;
  14155. }
  14156. }else{
  14157. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14158. type = 3;
  14159. }
  14160. }
  14161. var style = domUtils.getStyle(node, 'list-style-type');
  14162. style && (node.style.cssText = 'list-style-type:' + style);
  14163. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14164. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14165. li.style.cssText && (li.style.cssText = '');
  14166. if(!li.firstChild){
  14167. domUtils.remove(li);
  14168. return;
  14169. }
  14170. if(li.parentNode !== node){
  14171. return;
  14172. }
  14173. index++;
  14174. if(domUtils.hasClass(node,/custom_/) ){
  14175. var paddingLeft = 1,currentStyle = getStyle(node);
  14176. if(node.tagName == 'OL'){
  14177. if(currentStyle){
  14178. switch(currentStyle){
  14179. case 'cn' :
  14180. case 'cn1':
  14181. case 'cn2':
  14182. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14183. paddingLeft = 2
  14184. }else if(index > 20){
  14185. paddingLeft = 3
  14186. }
  14187. break;
  14188. case 'num2' :
  14189. if(index > 9){
  14190. paddingLeft = 2
  14191. }
  14192. }
  14193. }
  14194. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14195. }else{
  14196. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14197. }
  14198. }else{
  14199. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14200. }
  14201. var className = li.getAttribute('class');
  14202. if(className !== null && !className.replace(/\s/g,'')){
  14203. domUtils.removeAttributes(li,'class')
  14204. }
  14205. });
  14206. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14207. })
  14208. }
  14209. function adjustList(list, tag, style,ignoreEmpty) {
  14210. var nextList = list.nextSibling;
  14211. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14212. domUtils.moveChild(nextList, list);
  14213. if (nextList.childNodes.length == 0) {
  14214. domUtils.remove(nextList);
  14215. }
  14216. }
  14217. if(nextList && domUtils.isFillChar(nextList)){
  14218. domUtils.remove(nextList);
  14219. }
  14220. var preList = list.previousSibling;
  14221. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14222. domUtils.moveChild(list, preList);
  14223. }
  14224. if(preList && domUtils.isFillChar(preList)){
  14225. domUtils.remove(preList);
  14226. }
  14227. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14228. if(getStyle(list)){
  14229. adjustListStyle(list.ownerDocument,true)
  14230. }
  14231. }
  14232. function setListStyle(list,style){
  14233. if(customStyle[style]){
  14234. list.className = 'custom_' + style;
  14235. }
  14236. try{
  14237. domUtils.setStyle(list, 'list-style-type', style);
  14238. }catch(e){}
  14239. }
  14240. function clearEmptySibling(node) {
  14241. var tmpNode = node.previousSibling;
  14242. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14243. domUtils.remove(tmpNode);
  14244. }
  14245. tmpNode = node.nextSibling;
  14246. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14247. domUtils.remove(tmpNode);
  14248. }
  14249. }
  14250. me.addListener('keydown', function (type, evt) {
  14251. function preventAndSave() {
  14252. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14253. me.fireEvent('contentchange');
  14254. me.undoManger && me.undoManger.save();
  14255. }
  14256. function findList(node,filterFn){
  14257. while(node && !domUtils.isBody(node)){
  14258. if(filterFn(node)){
  14259. return null
  14260. }
  14261. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14262. return node;
  14263. }
  14264. node = node.parentNode;
  14265. }
  14266. return null;
  14267. }
  14268. var keyCode = evt.keyCode || evt.which;
  14269. if (keyCode == 13 && !evt.shiftKey) {//回车
  14270. var rng = me.selection.getRange(),
  14271. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14272. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14273. if(parent && parent.tagName != 'PRE' && !li){
  14274. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14275. if(/^\s*1\s*\.[^\d]/.test(html)){
  14276. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14277. rng.setStartAtLast(parent).collapse(true).select();
  14278. me.__hasEnterExecCommand = true;
  14279. me.execCommand('insertorderedlist');
  14280. me.__hasEnterExecCommand = false;
  14281. }
  14282. }
  14283. var range = me.selection.getRange(),
  14284. start = findList(range.startContainer,function (node) {
  14285. return node.tagName == 'TABLE';
  14286. }),
  14287. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14288. return node.tagName == 'TABLE';
  14289. });
  14290. if (start && end && start === end) {
  14291. if (!range.collapsed) {
  14292. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14293. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14294. if (start && end && start === end) {
  14295. range.deleteContents();
  14296. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14297. if (li && domUtils.isEmptyBlock(li)) {
  14298. pre = li.previousSibling;
  14299. next = li.nextSibling;
  14300. p = me.document.createElement('p');
  14301. domUtils.fillNode(me.document, p);
  14302. parentList = li.parentNode;
  14303. if (pre && next) {
  14304. range.setStart(next, 0).collapse(true).select(true);
  14305. domUtils.remove(li);
  14306. } else {
  14307. if (!pre && !next || !pre) {
  14308. parentList.parentNode.insertBefore(p, parentList);
  14309. } else {
  14310. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14311. }
  14312. domUtils.remove(li);
  14313. if (!parentList.firstChild) {
  14314. domUtils.remove(parentList);
  14315. }
  14316. range.setStart(p, 0).setCursor();
  14317. }
  14318. preventAndSave();
  14319. return;
  14320. }
  14321. } else {
  14322. var tmpRange = range.cloneRange(),
  14323. bk = tmpRange.collapse(false).createBookmark();
  14324. range.deleteContents();
  14325. tmpRange.moveToBookmark(bk);
  14326. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14327. clearEmptySibling(li);
  14328. tmpRange.select();
  14329. preventAndSave();
  14330. return;
  14331. }
  14332. }
  14333. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14334. if (li) {
  14335. if (domUtils.isEmptyBlock(li)) {
  14336. bk = range.createBookmark();
  14337. var parentList = li.parentNode;
  14338. if (li !== parentList.lastChild) {
  14339. domUtils.breakParent(li, parentList);
  14340. clearEmptySibling(li);
  14341. } else {
  14342. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14343. if (domUtils.isEmptyNode(parentList)) {
  14344. domUtils.remove(parentList);
  14345. }
  14346. }
  14347. //嵌套不处理
  14348. if (!dtd.$list[li.parentNode.tagName]) {
  14349. if (!domUtils.isBlockElm(li.firstChild)) {
  14350. p = me.document.createElement('p');
  14351. li.parentNode.insertBefore(p, li);
  14352. while (li.firstChild) {
  14353. p.appendChild(li.firstChild);
  14354. }
  14355. domUtils.remove(li);
  14356. } else {
  14357. domUtils.remove(li, true);
  14358. }
  14359. }
  14360. range.moveToBookmark(bk).select();
  14361. } else {
  14362. var first = li.firstChild;
  14363. if (!first || !domUtils.isBlockElm(first)) {
  14364. var p = me.document.createElement('p');
  14365. !li.firstChild && domUtils.fillNode(me.document, p);
  14366. while (li.firstChild) {
  14367. p.appendChild(li.firstChild);
  14368. }
  14369. li.appendChild(p);
  14370. first = p;
  14371. }
  14372. var span = me.document.createElement('span');
  14373. range.insertNode(span);
  14374. domUtils.breakParent(span, li);
  14375. var nextLi = span.nextSibling;
  14376. first = nextLi.firstChild;
  14377. if (!first) {
  14378. p = me.document.createElement('p');
  14379. domUtils.fillNode(me.document, p);
  14380. nextLi.appendChild(p);
  14381. first = p;
  14382. }
  14383. if (domUtils.isEmptyNode(first)) {
  14384. first.innerHTML = '';
  14385. domUtils.fillNode(me.document, first);
  14386. }
  14387. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14388. domUtils.remove(span);
  14389. var pre = nextLi.previousSibling;
  14390. if (pre && domUtils.isEmptyBlock(pre)) {
  14391. pre.innerHTML = '<p></p>';
  14392. domUtils.fillNode(me.document, pre.firstChild);
  14393. }
  14394. }
  14395. // }
  14396. preventAndSave();
  14397. }
  14398. }
  14399. }
  14400. if (keyCode == 8) {
  14401. //修中ie中li下的问题
  14402. range = me.selection.getRange();
  14403. if (range.collapsed && domUtils.isStartInblock(range)) {
  14404. tmpRange = range.cloneRange().trimBoundary();
  14405. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14406. //要在li的最左边,才能处理
  14407. if (li && domUtils.isStartInblock(tmpRange)) {
  14408. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14409. if (start && start !== li.firstChild) {
  14410. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14411. domUtils.breakParent(start,parentList);
  14412. clearEmptySibling(start);
  14413. me.fireEvent('contentchange');
  14414. range.setStart(start,0).setCursor(false,true);
  14415. me.fireEvent('saveScene');
  14416. domUtils.preventDefault(evt);
  14417. return;
  14418. }
  14419. if (li && (pre = li.previousSibling)) {
  14420. if (keyCode == 46 && li.childNodes.length) {
  14421. return;
  14422. }
  14423. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14424. if (dtd.$list[pre.tagName]) {
  14425. pre = pre.lastChild;
  14426. }
  14427. me.undoManger && me.undoManger.save();
  14428. first = li.firstChild;
  14429. if (domUtils.isBlockElm(first)) {
  14430. if (domUtils.isEmptyNode(first)) {
  14431. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14432. pre.appendChild(first);
  14433. range.setStart(first, 0).setCursor(false, true);
  14434. //first不是唯一的节点
  14435. while (li.firstChild) {
  14436. pre.appendChild(li.firstChild);
  14437. }
  14438. } else {
  14439. span = me.document.createElement('span');
  14440. range.insertNode(span);
  14441. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14442. if (domUtils.isEmptyBlock(pre)) {
  14443. pre.innerHTML = '';
  14444. }
  14445. domUtils.moveChild(li, pre);
  14446. range.setStartBefore(span).collapse(true).select(true);
  14447. domUtils.remove(span);
  14448. }
  14449. } else {
  14450. if (domUtils.isEmptyNode(li)) {
  14451. var p = me.document.createElement('p');
  14452. pre.appendChild(p);
  14453. range.setStart(p, 0).setCursor();
  14454. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14455. } else {
  14456. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14457. while (li.firstChild) {
  14458. pre.appendChild(li.firstChild);
  14459. }
  14460. }
  14461. }
  14462. domUtils.remove(li);
  14463. me.fireEvent('contentchange');
  14464. me.fireEvent('saveScene');
  14465. domUtils.preventDefault(evt);
  14466. return;
  14467. }
  14468. //trace:980
  14469. if (li && !li.previousSibling) {
  14470. var parentList = li.parentNode;
  14471. var bk = range.createBookmark();
  14472. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14473. parentList.parentNode.insertBefore(li,parentList);
  14474. if(domUtils.isEmptyNode(parentList)){
  14475. domUtils.remove(parentList)
  14476. }
  14477. }else{
  14478. while(li.firstChild){
  14479. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14480. }
  14481. domUtils.remove(li);
  14482. if(domUtils.isEmptyNode(parentList)){
  14483. domUtils.remove(parentList)
  14484. }
  14485. }
  14486. range.moveToBookmark(bk).setCursor(false,true);
  14487. me.fireEvent('contentchange');
  14488. me.fireEvent('saveScene');
  14489. domUtils.preventDefault(evt);
  14490. return;
  14491. }
  14492. }
  14493. }
  14494. }
  14495. });
  14496. me.addListener('keyup',function(type, evt){
  14497. var keyCode = evt.keyCode || evt.which;
  14498. if (keyCode == 8) {
  14499. var rng = me.selection.getRange(),list;
  14500. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14501. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14502. }
  14503. }
  14504. });
  14505. //处理tab键
  14506. me.addListener('tabkeydown',function(){
  14507. var range = me.selection.getRange();
  14508. //控制级数
  14509. function checkLevel(li){
  14510. if(me.options.maxListLevel != -1){
  14511. var level = li.parentNode,levelNum = 0;
  14512. while(/[ou]l/i.test(level.tagName)){
  14513. levelNum++;
  14514. level = level.parentNode;
  14515. }
  14516. if(levelNum >= me.options.maxListLevel){
  14517. return true;
  14518. }
  14519. }
  14520. }
  14521. //只以开始为准
  14522. //todo 后续改进
  14523. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14524. if(li){
  14525. var bk;
  14526. if(range.collapsed){
  14527. if(checkLevel(li))
  14528. return true;
  14529. var parentLi = li.parentNode,
  14530. list = me.document.createElement(parentLi.tagName),
  14531. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14532. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14533. var currentStyle = listStyle[list.tagName][index];
  14534. setListStyle(list,currentStyle);
  14535. if(domUtils.isStartInblock(range)){
  14536. me.fireEvent('saveScene');
  14537. bk = range.createBookmark();
  14538. parentLi.insertBefore(list, li);
  14539. list.appendChild(li);
  14540. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14541. me.fireEvent('contentchange');
  14542. range.moveToBookmark(bk).select(true);
  14543. return true;
  14544. }
  14545. }else{
  14546. me.fireEvent('saveScene');
  14547. bk = range.createBookmark();
  14548. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14549. if(domUtils.isTagNode(ci,'ol ul')){
  14550. closeList = ci;
  14551. break;
  14552. }
  14553. }
  14554. var current = li;
  14555. if(bk.end){
  14556. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14557. if(checkLevel(current)){
  14558. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14559. continue;
  14560. }
  14561. var parentLi = current.parentNode,
  14562. list = me.document.createElement(parentLi.tagName),
  14563. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14564. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14565. var currentStyle = listStyle[list.tagName][currentIndex];
  14566. setListStyle(list,currentStyle);
  14567. parentLi.insertBefore(list, current);
  14568. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14569. li = current.nextSibling;
  14570. list.appendChild(current);
  14571. if(!li || domUtils.isTagNode(li,'ol ul')){
  14572. if(li){
  14573. while(li = li.firstChild){
  14574. if(li.tagName == 'LI'){
  14575. break;
  14576. }
  14577. }
  14578. }else{
  14579. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14580. }
  14581. break;
  14582. }
  14583. current = li;
  14584. }
  14585. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14586. current = li;
  14587. }
  14588. }
  14589. me.fireEvent('contentchange');
  14590. range.moveToBookmark(bk).select();
  14591. return true;
  14592. }
  14593. }
  14594. });
  14595. function getLi(start){
  14596. while(start && !domUtils.isBody(start)){
  14597. if(start.nodeName == 'TABLE'){
  14598. return null;
  14599. }
  14600. if(start.nodeName == 'LI'){
  14601. return start
  14602. }
  14603. start = start.parentNode;
  14604. }
  14605. }
  14606. /**
  14607. * 有序列表,与“insertunorderedlist”命令互斥
  14608. * @command insertorderedlist
  14609. * @method execCommand
  14610. * @param { String } command 命令字符串
  14611. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14612. * @example
  14613. * ```javascript
  14614. * editor.execCommand( 'insertorderedlist','decimal');
  14615. * ```
  14616. */
  14617. /**
  14618. * 查询当前选区内容是否有序列表
  14619. * @command insertorderedlist
  14620. * @method queryCommandState
  14621. * @param { String } cmd 命令字符串
  14622. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14623. * @example
  14624. * ```javascript
  14625. * editor.queryCommandState( 'insertorderedlist' );
  14626. * ```
  14627. */
  14628. /**
  14629. * 查询当前选区内容是否有序列表
  14630. * @command insertorderedlist
  14631. * @method queryCommandValue
  14632. * @param { String } cmd 命令字符串
  14633. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14634. * @example
  14635. * ```javascript
  14636. * editor.queryCommandValue( 'insertorderedlist' );
  14637. * ```
  14638. */
  14639. /**
  14640. * 无序列表,与“insertorderedlist”命令互斥
  14641. * @command insertunorderedlist
  14642. * @method execCommand
  14643. * @param { String } command 命令字符串
  14644. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14645. * @example
  14646. * ```javascript
  14647. * editor.execCommand( 'insertunorderedlist','circle');
  14648. * ```
  14649. */
  14650. /**
  14651. * 查询当前是否有word文档粘贴进来的图片
  14652. * @command insertunorderedlist
  14653. * @method insertunorderedlist
  14654. * @param { String } command 命令字符串
  14655. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14656. * @example
  14657. * ```javascript
  14658. * editor.queryCommandState( 'insertunorderedlist' );
  14659. * ```
  14660. */
  14661. /**
  14662. * 查询当前选区内容是否有序列表
  14663. * @command insertunorderedlist
  14664. * @method queryCommandValue
  14665. * @param { String } command 命令字符串
  14666. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14667. * @example
  14668. * ```javascript
  14669. * editor.queryCommandValue( 'insertunorderedlist' );
  14670. * ```
  14671. */
  14672. me.commands['insertorderedlist'] =
  14673. me.commands['insertunorderedlist'] = {
  14674. execCommand:function (command, style) {
  14675. if (!style) {
  14676. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14677. }
  14678. var me = this,
  14679. range = this.selection.getRange(),
  14680. filterFn = function (node) {
  14681. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14682. },
  14683. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14684. frag = me.document.createDocumentFragment();
  14685. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14686. //range.shrinkBoundary();//.adjustmentBoundary();
  14687. range.adjustmentBoundary().shrinkBoundary();
  14688. var bko = range.createBookmark(true),
  14689. start = getLi(me.document.getElementById(bko.start)),
  14690. modifyStart = 0,
  14691. end = getLi(me.document.getElementById(bko.end)),
  14692. modifyEnd = 0,
  14693. startParent, endParent,
  14694. list, tmp;
  14695. if (start || end) {
  14696. start && (startParent = start.parentNode);
  14697. if (!bko.end) {
  14698. end = start;
  14699. }
  14700. end && (endParent = end.parentNode);
  14701. if (startParent === endParent) {
  14702. while (start !== end) {
  14703. tmp = start;
  14704. start = start.nextSibling;
  14705. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14706. var p = me.document.createElement('p');
  14707. while (tmp.firstChild) {
  14708. p.appendChild(tmp.firstChild);
  14709. }
  14710. tmp.appendChild(p);
  14711. }
  14712. frag.appendChild(tmp);
  14713. }
  14714. tmp = me.document.createElement('span');
  14715. startParent.insertBefore(tmp, end);
  14716. if (!domUtils.isBlockElm(end.firstChild)) {
  14717. p = me.document.createElement('p');
  14718. while (end.firstChild) {
  14719. p.appendChild(end.firstChild);
  14720. }
  14721. end.appendChild(p);
  14722. }
  14723. frag.appendChild(end);
  14724. domUtils.breakParent(tmp, startParent);
  14725. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14726. domUtils.remove(tmp.previousSibling);
  14727. }
  14728. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14729. domUtils.remove(tmp.nextSibling)
  14730. }
  14731. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14732. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14733. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14734. if(domUtils.isTagNode(ci,'ol ul')){
  14735. // 删除时,子列表不处理
  14736. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14737. // while(li.firstChild){
  14738. // tmpFrag.appendChild(li.firstChild);
  14739. // }
  14740. //
  14741. // });
  14742. tmpFrag.appendChild(ci);
  14743. }else{
  14744. while (ci.firstChild) {
  14745. tmpFrag.appendChild(ci.firstChild);
  14746. domUtils.remove(ci);
  14747. }
  14748. }
  14749. }
  14750. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14751. } else {
  14752. list = me.document.createElement(tag);
  14753. setListStyle(list,style);
  14754. list.appendChild(frag);
  14755. tmp.parentNode.insertBefore(list, tmp);
  14756. }
  14757. domUtils.remove(tmp);
  14758. list && adjustList(list, tag, style);
  14759. range.moveToBookmark(bko).select();
  14760. return;
  14761. }
  14762. //开始
  14763. if (start) {
  14764. while (start) {
  14765. tmp = start.nextSibling;
  14766. if (domUtils.isTagNode(start, 'ol ul')) {
  14767. frag.appendChild(start);
  14768. } else {
  14769. var tmpfrag = me.document.createDocumentFragment(),
  14770. hasBlock = 0;
  14771. while (start.firstChild) {
  14772. if (domUtils.isBlockElm(start.firstChild)) {
  14773. hasBlock = 1;
  14774. }
  14775. tmpfrag.appendChild(start.firstChild);
  14776. }
  14777. if (!hasBlock) {
  14778. var tmpP = me.document.createElement('p');
  14779. tmpP.appendChild(tmpfrag);
  14780. frag.appendChild(tmpP);
  14781. } else {
  14782. frag.appendChild(tmpfrag);
  14783. }
  14784. domUtils.remove(start);
  14785. }
  14786. start = tmp;
  14787. }
  14788. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14789. if (domUtils.isEmptyNode(startParent)) {
  14790. range.setStartBefore(startParent);
  14791. domUtils.remove(startParent);
  14792. } else {
  14793. range.setStartAfter(startParent);
  14794. }
  14795. modifyStart = 1;
  14796. }
  14797. if (end && domUtils.inDoc(endParent, me.document)) {
  14798. //结束
  14799. start = endParent.firstChild;
  14800. while (start && start !== end) {
  14801. tmp = start.nextSibling;
  14802. if (domUtils.isTagNode(start, 'ol ul')) {
  14803. frag.appendChild(start);
  14804. } else {
  14805. tmpfrag = me.document.createDocumentFragment();
  14806. hasBlock = 0;
  14807. while (start.firstChild) {
  14808. if (domUtils.isBlockElm(start.firstChild)) {
  14809. hasBlock = 1;
  14810. }
  14811. tmpfrag.appendChild(start.firstChild);
  14812. }
  14813. if (!hasBlock) {
  14814. tmpP = me.document.createElement('p');
  14815. tmpP.appendChild(tmpfrag);
  14816. frag.appendChild(tmpP);
  14817. } else {
  14818. frag.appendChild(tmpfrag);
  14819. }
  14820. domUtils.remove(start);
  14821. }
  14822. start = tmp;
  14823. }
  14824. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14825. 'tmpDiv':1
  14826. });
  14827. domUtils.moveChild(end, tmpDiv);
  14828. frag.appendChild(tmpDiv);
  14829. domUtils.remove(end);
  14830. endParent.parentNode.insertBefore(frag, endParent);
  14831. range.setEndBefore(endParent);
  14832. if (domUtils.isEmptyNode(endParent)) {
  14833. domUtils.remove(endParent);
  14834. }
  14835. modifyEnd = 1;
  14836. }
  14837. }
  14838. if (!modifyStart) {
  14839. range.setStartBefore(me.document.getElementById(bko.start));
  14840. }
  14841. if (bko.end && !modifyEnd) {
  14842. range.setEndAfter(me.document.getElementById(bko.end));
  14843. }
  14844. range.enlarge(true, function (node) {
  14845. return notExchange[node.tagName];
  14846. });
  14847. frag = me.document.createDocumentFragment();
  14848. var bk = range.createBookmark(),
  14849. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14850. tmpRange = range.cloneRange(),
  14851. tmpNode,
  14852. block = domUtils.isBlockElm;
  14853. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14854. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14855. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14856. while (current.firstChild) {
  14857. frag.appendChild(current.firstChild);
  14858. }
  14859. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14860. domUtils.remove(current);
  14861. current = tmpNode;
  14862. continue;
  14863. }
  14864. tmpNode = current;
  14865. tmpRange.setStartBefore(current);
  14866. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14867. tmpNode = current;
  14868. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14869. return !notExchange[node.tagName];
  14870. });
  14871. }
  14872. if (current && block(current)) {
  14873. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14874. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14875. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14876. tmpNode = tmp;
  14877. }
  14878. }
  14879. tmpRange.setEndAfter(tmpNode);
  14880. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14881. var li = range.document.createElement('li');
  14882. li.appendChild(tmpRange.extractContents());
  14883. if(domUtils.isEmptyNode(li)){
  14884. var tmpNode = range.document.createElement('p');
  14885. while(li.firstChild){
  14886. tmpNode.appendChild(li.firstChild)
  14887. }
  14888. li.appendChild(tmpNode);
  14889. }
  14890. frag.appendChild(li);
  14891. } else {
  14892. current = domUtils.getNextDomNode(current, true, filterFn);
  14893. }
  14894. }
  14895. range.moveToBookmark(bk).collapse(true);
  14896. list = me.document.createElement(tag);
  14897. setListStyle(list,style);
  14898. list.appendChild(frag);
  14899. range.insertNode(list);
  14900. //当前list上下看能否合并
  14901. adjustList(list, tag, style);
  14902. //去掉冗余的tmpDiv
  14903. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14904. if (ci.getAttribute('tmpDiv')) {
  14905. domUtils.remove(ci, true)
  14906. }
  14907. }
  14908. range.moveToBookmark(bko).select();
  14909. },
  14910. queryCommandState:function (command) {
  14911. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14912. var path = this.selection.getStartElementPath();
  14913. for(var i= 0,ci;ci = path[i++];){
  14914. if(ci.nodeName == 'TABLE'){
  14915. return 0
  14916. }
  14917. if(tag == ci.nodeName.toLowerCase()){
  14918. return 1
  14919. };
  14920. }
  14921. return 0;
  14922. },
  14923. queryCommandValue:function (command) {
  14924. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14925. var path = this.selection.getStartElementPath(),
  14926. node;
  14927. for(var i= 0,ci;ci = path[i++];){
  14928. if(ci.nodeName == 'TABLE'){
  14929. node = null;
  14930. break;
  14931. }
  14932. if(tag == ci.nodeName.toLowerCase()){
  14933. node = ci;
  14934. break;
  14935. };
  14936. }
  14937. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14938. }
  14939. };
  14940. };
  14941. // plugins/source.js
  14942. /**
  14943. * 源码编辑插件
  14944. * @file
  14945. * @since 1.2.6.1
  14946. */
  14947. (function (){
  14948. var sourceEditors = {
  14949. textarea: function (editor, holder){
  14950. var textarea = holder.ownerDocument.createElement('textarea');
  14951. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14952. // todo: IE下只有onresize属性可用... 很纠结
  14953. if (browser.ie && browser.version < 8) {
  14954. textarea.style.width = holder.offsetWidth + 'px';
  14955. textarea.style.height = holder.offsetHeight + 'px';
  14956. holder.onresize = function (){
  14957. textarea.style.width = holder.offsetWidth + 'px';
  14958. textarea.style.height = holder.offsetHeight + 'px';
  14959. };
  14960. }
  14961. holder.appendChild(textarea);
  14962. return {
  14963. setContent: function (content){
  14964. textarea.value = content;
  14965. },
  14966. getContent: function (){
  14967. return textarea.value;
  14968. },
  14969. select: function (){
  14970. var range;
  14971. if (browser.ie) {
  14972. range = textarea.createTextRange();
  14973. range.collapse(true);
  14974. range.select();
  14975. } else {
  14976. //todo: chrome下无法设置焦点
  14977. textarea.setSelectionRange(0, 0);
  14978. textarea.focus();
  14979. }
  14980. },
  14981. dispose: function (){
  14982. holder.removeChild(textarea);
  14983. // todo
  14984. holder.onresize = null;
  14985. textarea = null;
  14986. holder = null;
  14987. }
  14988. };
  14989. },
  14990. codemirror: function (editor, holder){
  14991. var codeEditor = window.CodeMirror(holder, {
  14992. mode: "text/html",
  14993. tabMode: "indent",
  14994. lineNumbers: true,
  14995. lineWrapping:true
  14996. });
  14997. var dom = codeEditor.getWrapperElement();
  14998. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14999. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  15000. codeEditor.refresh();
  15001. return {
  15002. getCodeMirror:function(){
  15003. return codeEditor;
  15004. },
  15005. setContent: function (content){
  15006. codeEditor.setValue(content);
  15007. },
  15008. getContent: function (){
  15009. return codeEditor.getValue();
  15010. },
  15011. select: function (){
  15012. codeEditor.focus();
  15013. },
  15014. dispose: function (){
  15015. holder.removeChild(dom);
  15016. dom = null;
  15017. codeEditor = null;
  15018. }
  15019. };
  15020. }
  15021. };
  15022. UE.plugins['source'] = function (){
  15023. var me = this;
  15024. var opt = this.options;
  15025. var sourceMode = false;
  15026. var sourceEditor;
  15027. var orgSetContent;
  15028. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15029. me.setOpt({
  15030. sourceEditorFirst:false
  15031. });
  15032. function createSourceEditor(holder){
  15033. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15034. }
  15035. var bakCssText;
  15036. //解决在源码模式下getContent不能得到最新的内容问题
  15037. var oldGetContent,
  15038. bakAddress;
  15039. /**
  15040. * 切换源码模式和编辑模式
  15041. * @command source
  15042. * @method execCommand
  15043. * @param { String } cmd 命令字符串
  15044. * @example
  15045. * ```javascript
  15046. * editor.execCommand( 'source');
  15047. * ```
  15048. */
  15049. /**
  15050. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15051. * @command source
  15052. * @method queryCommandState
  15053. * @param { String } cmd 命令字符串
  15054. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15055. * @example
  15056. * ```javascript
  15057. * editor.queryCommandState( 'source' );
  15058. * ```
  15059. */
  15060. me.commands['source'] = {
  15061. execCommand: function (){
  15062. sourceMode = !sourceMode;
  15063. if (sourceMode) {
  15064. bakAddress = me.selection.getRange().createAddress(false,true);
  15065. me.undoManger && me.undoManger.save(true);
  15066. if(browser.gecko){
  15067. me.body.contentEditable = false;
  15068. }
  15069. bakCssText = me.iframe.style.cssText;
  15070. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15071. me.fireEvent('beforegetcontent');
  15072. var root = UE.htmlparser(me.body.innerHTML);
  15073. me.filterOutputRule(root);
  15074. root.traversal(function (node) {
  15075. if (node.type == 'element') {
  15076. switch (node.tagName) {
  15077. case 'td':
  15078. case 'th':
  15079. case 'caption':
  15080. if(node.children && node.children.length == 1){
  15081. if(node.firstChild().tagName == 'br' ){
  15082. node.removeChild(node.firstChild())
  15083. }
  15084. };
  15085. break;
  15086. case 'pre':
  15087. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15088. }
  15089. }
  15090. });
  15091. me.fireEvent('aftergetcontent');
  15092. var content = root.toHtml(true);
  15093. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15094. sourceEditor.setContent(content);
  15095. orgSetContent = me.setContent;
  15096. me.setContent = function(html){
  15097. //这里暂时不触发事件,防止报错
  15098. var root = UE.htmlparser(html);
  15099. me.filterInputRule(root);
  15100. html = root.toHtml();
  15101. sourceEditor.setContent(html);
  15102. };
  15103. setTimeout(function (){
  15104. sourceEditor.select();
  15105. me.addListener('fullscreenchanged', function(){
  15106. try{
  15107. sourceEditor.getCodeMirror().refresh()
  15108. }catch(e){}
  15109. });
  15110. });
  15111. //重置getContent,源码模式下取值也能是最新的数据
  15112. oldGetContent = me.getContent;
  15113. me.getContent = function (){
  15114. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15115. };
  15116. } else {
  15117. me.iframe.style.cssText = bakCssText;
  15118. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15119. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15120. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15121. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15122. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15123. }
  15124. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15125. });
  15126. me.setContent = orgSetContent;
  15127. me.setContent(cont);
  15128. sourceEditor.dispose();
  15129. sourceEditor = null;
  15130. //还原getContent方法
  15131. me.getContent = oldGetContent;
  15132. var first = me.body.firstChild;
  15133. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15134. if(!first){
  15135. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15136. first = me.body.firstChild;
  15137. }
  15138. //要在ifm为显示时ff才能取到selection,否则报错
  15139. //这里不能比较位置了
  15140. me.undoManger && me.undoManger.save(true);
  15141. if(browser.gecko){
  15142. var input = document.createElement('input');
  15143. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15144. document.body.appendChild(input);
  15145. me.body.contentEditable = false;
  15146. setTimeout(function(){
  15147. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15148. input.focus();
  15149. setTimeout(function(){
  15150. me.body.contentEditable = true;
  15151. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15152. domUtils.remove(input);
  15153. });
  15154. });
  15155. }else{
  15156. //ie下有可能报错,比如在代码顶头的情况
  15157. try{
  15158. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15159. }catch(e){}
  15160. }
  15161. }
  15162. this.fireEvent('sourcemodechanged', sourceMode);
  15163. },
  15164. queryCommandState: function (){
  15165. return sourceMode|0;
  15166. },
  15167. notNeedUndo : 1
  15168. };
  15169. var oldQueryCommandState = me.queryCommandState;
  15170. me.queryCommandState = function (cmdName){
  15171. cmdName = cmdName.toLowerCase();
  15172. if (sourceMode) {
  15173. //源码模式下可以开启的命令
  15174. return cmdName in {
  15175. 'source' : 1,
  15176. 'fullscreen' : 1
  15177. } ? 1 : -1
  15178. }
  15179. return oldQueryCommandState.apply(this, arguments);
  15180. };
  15181. if(opt.sourceEditor == "codemirror"){
  15182. me.addListener("ready",function(){
  15183. utils.loadFile(document,{
  15184. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15185. tag : "script",
  15186. type : "text/javascript",
  15187. defer : "defer"
  15188. },function(){
  15189. if(opt.sourceEditorFirst){
  15190. setTimeout(function(){
  15191. me.execCommand("source");
  15192. },0);
  15193. }
  15194. });
  15195. utils.loadFile(document,{
  15196. tag : "link",
  15197. rel : "stylesheet",
  15198. type : "text/css",
  15199. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15200. });
  15201. });
  15202. }
  15203. };
  15204. })();
  15205. // plugins/enterkey.js
  15206. ///import core
  15207. ///import plugins/undo.js
  15208. ///commands 设置回车标签p或br
  15209. ///commandsName EnterKey
  15210. ///commandsTitle 设置回车标签p或br
  15211. /**
  15212. * @description 处理回车
  15213. * @author zhanyi
  15214. */
  15215. UE.plugins['enterkey'] = function() {
  15216. var hTag,
  15217. me = this,
  15218. tag = me.options.enterTag;
  15219. me.addListener('keyup', function(type, evt) {
  15220. var keyCode = evt.keyCode || evt.which;
  15221. if (keyCode == 13) {
  15222. var range = me.selection.getRange(),
  15223. start = range.startContainer,
  15224. doSave;
  15225. //修正在h1-h6里边回车后不能嵌套p的问题
  15226. if (!browser.ie) {
  15227. if (/h\d/i.test(hTag)) {
  15228. if (browser.gecko) {
  15229. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15230. if (!h) {
  15231. me.document.execCommand('formatBlock', false, '<p>');
  15232. doSave = 1;
  15233. }
  15234. } else {
  15235. //chrome remove div
  15236. if (start.nodeType == 1) {
  15237. var tmp = me.document.createTextNode(''),div;
  15238. range.insertNode(tmp);
  15239. div = domUtils.findParentByTagName(tmp, 'div', true);
  15240. if (div) {
  15241. var p = me.document.createElement('p');
  15242. while (div.firstChild) {
  15243. p.appendChild(div.firstChild);
  15244. }
  15245. div.parentNode.insertBefore(p, div);
  15246. domUtils.remove(div);
  15247. range.setStartBefore(tmp).setCursor();
  15248. doSave = 1;
  15249. }
  15250. domUtils.remove(tmp);
  15251. }
  15252. }
  15253. if (me.undoManger && doSave) {
  15254. me.undoManger.save();
  15255. }
  15256. }
  15257. //没有站位符,会出现多行的问题
  15258. browser.opera && range.select();
  15259. }else{
  15260. me.fireEvent('saveScene',true,true)
  15261. }
  15262. }
  15263. });
  15264. me.addListener('keydown', function(type, evt) {
  15265. var keyCode = evt.keyCode || evt.which;
  15266. if (keyCode == 13) {//回车
  15267. if(me.fireEvent('beforeenterkeydown')){
  15268. domUtils.preventDefault(evt);
  15269. return;
  15270. }
  15271. me.fireEvent('saveScene',true,true);
  15272. hTag = '';
  15273. var range = me.selection.getRange();
  15274. if (!range.collapsed) {
  15275. //跨td不能删
  15276. var start = range.startContainer,
  15277. end = range.endContainer,
  15278. startTd = domUtils.findParentByTagName(start, 'td', true),
  15279. endTd = domUtils.findParentByTagName(end, 'td', true);
  15280. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15281. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15282. return;
  15283. }
  15284. }
  15285. if (tag == 'p') {
  15286. if (!browser.ie) {
  15287. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15288. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15289. //trace:2431
  15290. if (!start && !browser.opera) {
  15291. me.document.execCommand('formatBlock', false, '<p>');
  15292. if (browser.gecko) {
  15293. range = me.selection.getRange();
  15294. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15295. start && domUtils.removeDirtyAttr(start);
  15296. }
  15297. } else {
  15298. hTag = start.tagName;
  15299. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15300. }
  15301. }
  15302. } else {
  15303. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15304. if (!range.collapsed) {
  15305. range.deleteContents();
  15306. start = range.startContainer;
  15307. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15308. while (start.nodeType == 1) {
  15309. if (dtd.$empty[start.tagName]) {
  15310. range.setStartBefore(start).setCursor();
  15311. if (me.undoManger) {
  15312. me.undoManger.save();
  15313. }
  15314. return false;
  15315. }
  15316. if (!start.firstChild) {
  15317. var br = range.document.createElement('br');
  15318. start.appendChild(br);
  15319. range.setStart(start, 0).setCursor();
  15320. if (me.undoManger) {
  15321. me.undoManger.save();
  15322. }
  15323. return false;
  15324. }
  15325. start = start.firstChild;
  15326. }
  15327. if (start === range.startContainer.childNodes[range.startOffset]) {
  15328. br = range.document.createElement('br');
  15329. range.insertNode(br).setCursor();
  15330. } else {
  15331. range.setStart(start, 0).setCursor();
  15332. }
  15333. } else {
  15334. br = range.document.createElement('br');
  15335. range.insertNode(br).setStartAfter(br).setCursor();
  15336. }
  15337. } else {
  15338. br = range.document.createElement('br');
  15339. range.insertNode(br);
  15340. var parent = br.parentNode;
  15341. if (parent.lastChild === br) {
  15342. br.parentNode.insertBefore(br.cloneNode(true), br);
  15343. range.setStartBefore(br);
  15344. } else {
  15345. range.setStartAfter(br);
  15346. }
  15347. range.setCursor();
  15348. }
  15349. }
  15350. }
  15351. });
  15352. };
  15353. // plugins/keystrokes.js
  15354. /* 处理特殊键的兼容性问题 */
  15355. UE.plugins['keystrokes'] = function() {
  15356. var me = this;
  15357. var collapsed = true;
  15358. me.addListener('keydown', function(type, evt) {
  15359. var keyCode = evt.keyCode || evt.which,
  15360. rng = me.selection.getRange();
  15361. //处理全选的情况
  15362. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15363. || keyCode >= 48 && keyCode <= 57 ||
  15364. keyCode >= 96 && keyCode <= 111 || {
  15365. 13:1,
  15366. 8:1,
  15367. 46:1
  15368. }[keyCode])
  15369. ){
  15370. var tmpNode = rng.startContainer;
  15371. if(domUtils.isFillChar(tmpNode)){
  15372. rng.setStartBefore(tmpNode)
  15373. }
  15374. tmpNode = rng.endContainer;
  15375. if(domUtils.isFillChar(tmpNode)){
  15376. rng.setEndAfter(tmpNode)
  15377. }
  15378. rng.txtToElmBoundary();
  15379. //结束边界可能放到了br的前边,要把br包含进来
  15380. // x[xxx]<br/>
  15381. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15382. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15383. if(tmpNode && domUtils.isBr(tmpNode)){
  15384. rng.setEndAfter(tmpNode);
  15385. }
  15386. }
  15387. if(rng.startOffset == 0){
  15388. tmpNode = rng.startContainer;
  15389. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15390. tmpNode = rng.endContainer;
  15391. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15392. me.fireEvent('saveScene');
  15393. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15394. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15395. me._selectionChange();
  15396. return;
  15397. }
  15398. }
  15399. }
  15400. }
  15401. //处理backspace
  15402. if (keyCode == keymap.Backspace) {
  15403. rng = me.selection.getRange();
  15404. collapsed = rng.collapsed;
  15405. if(me.fireEvent('delkeydown',evt)){
  15406. return;
  15407. }
  15408. var start,end;
  15409. //避免按两次删除才能生效的问题
  15410. if(rng.collapsed && rng.inFillChar()){
  15411. start = rng.startContainer;
  15412. if(domUtils.isFillChar(start)){
  15413. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15414. domUtils.remove(start)
  15415. }else{
  15416. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15417. rng.startOffset--;
  15418. rng.collapse(true).select(true)
  15419. }
  15420. }
  15421. //解决选中control元素不能删除的问题
  15422. if (start = rng.getClosedNode()) {
  15423. me.fireEvent('saveScene');
  15424. rng.setStartBefore(start);
  15425. domUtils.remove(start);
  15426. rng.setCursor();
  15427. me.fireEvent('saveScene');
  15428. domUtils.preventDefault(evt);
  15429. return;
  15430. }
  15431. //阻止在table上的删除
  15432. if (!browser.ie) {
  15433. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15434. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15435. if (start && !end || !start && end || start !== end) {
  15436. evt.preventDefault();
  15437. return;
  15438. }
  15439. }
  15440. }
  15441. //处理tab键的逻辑
  15442. if (keyCode == keymap.Tab) {
  15443. //不处理以下标签
  15444. var excludeTagNameForTabKey = {
  15445. 'ol' : 1,
  15446. 'ul' : 1,
  15447. 'table':1
  15448. };
  15449. //处理组件里的tab按下事件
  15450. if(me.fireEvent('tabkeydown',evt)){
  15451. domUtils.preventDefault(evt);
  15452. return;
  15453. }
  15454. var range = me.selection.getRange();
  15455. me.fireEvent('saveScene');
  15456. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15457. txt += tabNode;
  15458. }
  15459. var span = me.document.createElement('span');
  15460. span.innerHTML = txt + domUtils.fillChar;
  15461. if (range.collapsed) {
  15462. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15463. } else {
  15464. var filterFn = function(node) {
  15465. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15466. };
  15467. //普通的情况
  15468. start = domUtils.findParent(range.startContainer, filterFn,true);
  15469. end = domUtils.findParent(range.endContainer, filterFn,true);
  15470. if (start && end && start === end) {
  15471. range.deleteContents();
  15472. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15473. } else {
  15474. var bookmark = range.createBookmark();
  15475. range.enlarge(true);
  15476. var bookmark2 = range.createBookmark(),
  15477. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15478. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15479. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15480. current = domUtils.getNextDomNode(current, false, filterFn);
  15481. }
  15482. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15483. }
  15484. }
  15485. domUtils.preventDefault(evt)
  15486. }
  15487. //trace:1634
  15488. //ff的del键在容器空的时候,也会删除
  15489. if(browser.gecko && keyCode == 46){
  15490. range = me.selection.getRange();
  15491. if(range.collapsed){
  15492. start = range.startContainer;
  15493. if(domUtils.isEmptyBlock(start)){
  15494. var parent = start.parentNode;
  15495. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15496. start = parent;
  15497. parent = parent.parentNode;
  15498. }
  15499. if(start === parent.lastChild)
  15500. evt.preventDefault();
  15501. return;
  15502. }
  15503. }
  15504. }
  15505. });
  15506. me.addListener('keyup', function(type, evt) {
  15507. var keyCode = evt.keyCode || evt.which,
  15508. rng,me = this;
  15509. if(keyCode == keymap.Backspace){
  15510. if(me.fireEvent('delkeyup')){
  15511. return;
  15512. }
  15513. rng = me.selection.getRange();
  15514. if(rng.collapsed){
  15515. var tmpNode,
  15516. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15517. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15518. if(domUtils.isEmptyBlock(tmpNode)){
  15519. var pre = tmpNode.previousSibling;
  15520. if(pre && pre.nodeName != 'TABLE'){
  15521. domUtils.remove(tmpNode);
  15522. rng.setStartAtLast(pre).setCursor(false,true);
  15523. return;
  15524. }else{
  15525. var next = tmpNode.nextSibling;
  15526. if(next && next.nodeName != 'TABLE'){
  15527. domUtils.remove(tmpNode);
  15528. rng.setStartAtFirst(next).setCursor(false,true);
  15529. return;
  15530. }
  15531. }
  15532. }
  15533. }
  15534. //处理当删除到body时,要重新给p标签展位
  15535. if(domUtils.isBody(rng.startContainer)){
  15536. var tmpNode = domUtils.createElement(me.document,'p',{
  15537. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15538. });
  15539. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15540. }
  15541. }
  15542. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15543. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15544. if(browser.ie){
  15545. var span = rng.document.createElement('span');
  15546. rng.insertNode(span).setStartBefore(span).collapse(true);
  15547. rng.select();
  15548. domUtils.remove(span)
  15549. }else{
  15550. rng.select()
  15551. }
  15552. }
  15553. }
  15554. })
  15555. };
  15556. // plugins/fiximgclick.js
  15557. ///import core
  15558. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15559. ///commandsName FixImgClick
  15560. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15561. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15562. UE.plugins['fiximgclick'] = (function () {
  15563. var elementUpdated = false;
  15564. function Scale() {
  15565. this.editor = null;
  15566. this.resizer = null;
  15567. this.cover = null;
  15568. this.doc = document;
  15569. this.prePos = {x: 0, y: 0};
  15570. this.startPos = {x: 0, y: 0};
  15571. }
  15572. (function () {
  15573. var rect = [
  15574. //[left, top, width, height]
  15575. [0, 0, -1, -1],
  15576. [0, 0, 0, -1],
  15577. [0, 0, 1, -1],
  15578. [0, 0, -1, 0],
  15579. [0, 0, 1, 0],
  15580. [0, 0, -1, 1],
  15581. [0, 0, 0, 1],
  15582. [0, 0, 1, 1]
  15583. ];
  15584. Scale.prototype = {
  15585. init: function (editor) {
  15586. var me = this;
  15587. me.editor = editor;
  15588. me.startPos = this.prePos = {x: 0, y: 0};
  15589. me.dragId = -1;
  15590. var hands = [],
  15591. cover = me.cover = document.createElement('div'),
  15592. resizer = me.resizer = document.createElement('div');
  15593. cover.id = me.editor.ui.id + '_imagescale_cover';
  15594. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15595. domUtils.on(cover, 'mousedown click', function () {
  15596. me.hide();
  15597. });
  15598. for (i = 0; i < 8; i++) {
  15599. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15600. }
  15601. resizer.id = me.editor.ui.id + '_imagescale';
  15602. resizer.className = 'edui-editor-imagescale';
  15603. resizer.innerHTML = hands.join('');
  15604. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15605. me.editor.ui.getDom().appendChild(cover);
  15606. me.editor.ui.getDom().appendChild(resizer);
  15607. me.initStyle();
  15608. me.initEvents();
  15609. },
  15610. initStyle: function () {
  15611. utils.cssRule('imagescale', '.edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15612. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15613. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15614. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15615. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15616. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15617. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15618. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15619. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15620. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15621. },
  15622. initEvents: function () {
  15623. var me = this;
  15624. me.startPos.x = me.startPos.y = 0;
  15625. me.isDraging = false;
  15626. },
  15627. _eventHandler: function (e) {
  15628. var me = this;
  15629. switch (e.type) {
  15630. case 'mousedown':
  15631. var hand = e.target || e.srcElement, hand;
  15632. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15633. me.dragId = hand.className.slice(-1);
  15634. me.startPos.x = me.prePos.x = e.clientX;
  15635. me.startPos.y = me.prePos.y = e.clientY;
  15636. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15637. }
  15638. break;
  15639. case 'mousemove':
  15640. if (me.dragId != -1) {
  15641. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15642. me.prePos.x = e.clientX;
  15643. me.prePos.y = e.clientY;
  15644. elementUpdated = true;
  15645. me.updateTargetElement();
  15646. }
  15647. break;
  15648. case 'mouseup':
  15649. if (me.dragId != -1) {
  15650. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15651. me.updateTargetElement();
  15652. if (me.target.parentNode) me.attachTo(me.target);
  15653. me.dragId = -1;
  15654. }
  15655. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15656. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15657. if(elementUpdated){
  15658. elementUpdated = false;
  15659. me.editor.fireEvent('contentchange');
  15660. }
  15661. break;
  15662. default:
  15663. break;
  15664. }
  15665. },
  15666. updateTargetElement: function () {
  15667. var me = this;
  15668. domUtils.setStyles(me.target, {
  15669. 'width': me.resizer.style.width,
  15670. 'height': me.resizer.style.height
  15671. });
  15672. me.target.width = parseInt(me.resizer.style.width);
  15673. me.target.height = parseInt(me.resizer.style.height);
  15674. me.attachTo(me.target);
  15675. },
  15676. updateContainerStyle: function (dir, offset) {
  15677. var me = this,
  15678. dom = me.resizer, tmp;
  15679. if (rect[dir][0] != 0) {
  15680. tmp = parseInt(dom.style.left) + offset.x;
  15681. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15682. }
  15683. if (rect[dir][1] != 0) {
  15684. tmp = parseInt(dom.style.top) + offset.y;
  15685. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15686. }
  15687. if (rect[dir][2] != 0) {
  15688. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15689. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15690. }
  15691. if (rect[dir][3] != 0) {
  15692. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15693. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15694. }
  15695. },
  15696. _validScaledProp: function (prop, value) {
  15697. var ele = this.resizer,
  15698. wrap = document;
  15699. value = isNaN(value) ? 0 : value;
  15700. switch (prop) {
  15701. case 'left':
  15702. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15703. case 'top':
  15704. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15705. case 'width':
  15706. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15707. case 'height':
  15708. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15709. }
  15710. },
  15711. hideCover: function () {
  15712. this.cover.style.display = 'none';
  15713. },
  15714. showCover: function () {
  15715. var me = this,
  15716. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15717. iframePos = domUtils.getXY(me.editor.iframe);
  15718. domUtils.setStyles(me.cover, {
  15719. 'width': me.editor.iframe.offsetWidth + 'px',
  15720. 'height': me.editor.iframe.offsetHeight + 'px',
  15721. 'top': iframePos.y - editorPos.y + 'px',
  15722. 'left': iframePos.x - editorPos.x + 'px',
  15723. 'position': 'absolute',
  15724. 'display': ''
  15725. })
  15726. },
  15727. show: function (targetObj) {
  15728. var me = this;
  15729. me.resizer.style.display = 'block';
  15730. if(targetObj) me.attachTo(targetObj);
  15731. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15732. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15733. me.showCover();
  15734. me.editor.fireEvent('afterscaleshow', me);
  15735. me.editor.fireEvent('saveScene');
  15736. },
  15737. hide: function () {
  15738. var me = this;
  15739. me.hideCover();
  15740. me.resizer.style.display = 'none';
  15741. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15742. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15743. me.editor.fireEvent('afterscalehide', me);
  15744. },
  15745. proxy: function( fn, context ) {
  15746. return function(e) {
  15747. return fn.apply( context || this, arguments);
  15748. };
  15749. },
  15750. attachTo: function (targetObj) {
  15751. var me = this,
  15752. target = me.target = targetObj,
  15753. resizer = this.resizer,
  15754. imgPos = domUtils.getXY(target),
  15755. iframePos = domUtils.getXY(me.editor.iframe),
  15756. editorPos = domUtils.getXY(resizer.parentNode);
  15757. domUtils.setStyles(resizer, {
  15758. 'width': target.width + 'px',
  15759. 'height': target.height + 'px',
  15760. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15761. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15762. });
  15763. }
  15764. }
  15765. })();
  15766. return function () {
  15767. var me = this,
  15768. imageScale;
  15769. me.setOpt('imageScaleEnabled', true);
  15770. if ( !browser.ie && me.options.imageScaleEnabled) {
  15771. me.addListener('click', function (type, e) {
  15772. var range = me.selection.getRange(),
  15773. img = range.getClosedNode();
  15774. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15775. if (img.className.indexOf("edui-faked-music") != -1 ||
  15776. img.getAttribute("anchorname") ||
  15777. domUtils.hasClass(img, 'loadingclass') ||
  15778. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15779. if (!imageScale) {
  15780. imageScale = new Scale();
  15781. imageScale.init(me);
  15782. me.ui.getDom().appendChild(imageScale.resizer);
  15783. var _keyDownHandler = function (e) {
  15784. imageScale.hide();
  15785. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15786. }, _mouseDownHandler = function (e) {
  15787. var ele = e.target || e.srcElement;
  15788. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15789. _keyDownHandler(e);
  15790. }
  15791. }, timer;
  15792. me.addListener('afterscaleshow', function (e) {
  15793. me.addListener('beforekeydown', _keyDownHandler);
  15794. me.addListener('beforemousedown', _mouseDownHandler);
  15795. domUtils.on(document, 'keydown', _keyDownHandler);
  15796. domUtils.on(document,'mousedown', _mouseDownHandler);
  15797. me.selection.getNative().removeAllRanges();
  15798. });
  15799. me.addListener('afterscalehide', function (e) {
  15800. me.removeListener('beforekeydown', _keyDownHandler);
  15801. me.removeListener('beforemousedown', _mouseDownHandler);
  15802. domUtils.un(document, 'keydown', _keyDownHandler);
  15803. domUtils.un(document,'mousedown', _mouseDownHandler);
  15804. var target = imageScale.target;
  15805. if (target.parentNode) {
  15806. me.selection.getRange().selectNode(target).select();
  15807. }
  15808. });
  15809. //TODO 有iframe的情况,mousedown不能往下传。。
  15810. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15811. me.selection.getNative().removeAllRanges();
  15812. var ele = e.target || e.srcElement;
  15813. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15814. timer = setTimeout(function () {
  15815. imageScale.hide();
  15816. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15817. }, 200);
  15818. }
  15819. });
  15820. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15821. var ele = e.target || e.srcElement;
  15822. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15823. clearTimeout(timer);
  15824. }
  15825. });
  15826. }
  15827. imageScale.show(img);
  15828. } else {
  15829. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15830. }
  15831. });
  15832. }
  15833. if (browser.webkit) {
  15834. me.addListener('click', function (type, e) {
  15835. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15836. var range = new dom.Range(me.document);
  15837. range.selectNode(e.target).select();
  15838. }
  15839. });
  15840. }
  15841. }
  15842. })();
  15843. // plugins/autolink.js
  15844. ///import core
  15845. ///commands 为非ie浏览器自动添加a标签
  15846. ///commandsName AutoLink
  15847. ///commandsTitle 自动增加链接
  15848. /**
  15849. * @description 为非ie浏览器自动添加a标签
  15850. * @author zhanyi
  15851. */
  15852. UE.plugin.register('autolink',function(){
  15853. var cont = 0;
  15854. return !browser.ie ? {
  15855. bindEvents:{
  15856. 'reset' : function(){
  15857. cont = 0;
  15858. },
  15859. 'keydown':function(type, evt) {
  15860. var me = this;
  15861. var keyCode = evt.keyCode || evt.which;
  15862. if (keyCode == 32 || keyCode == 13) {
  15863. var sel = me.selection.getNative(),
  15864. range = sel.getRangeAt(0).cloneRange(),
  15865. offset,
  15866. charCode;
  15867. var start = range.startContainer;
  15868. while (start.nodeType == 1 && range.startOffset > 0) {
  15869. start = range.startContainer.childNodes[range.startOffset - 1];
  15870. if (!start){
  15871. break;
  15872. }
  15873. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15874. range.collapse(true);
  15875. start = range.startContainer;
  15876. }
  15877. do{
  15878. if (range.startOffset == 0) {
  15879. start = range.startContainer.previousSibling;
  15880. while (start && start.nodeType == 1) {
  15881. start = start.lastChild;
  15882. }
  15883. if (!start || domUtils.isFillChar(start)){
  15884. break;
  15885. }
  15886. offset = start.nodeValue.length;
  15887. } else {
  15888. start = range.startContainer;
  15889. offset = range.startOffset;
  15890. }
  15891. range.setStart(start, offset - 1);
  15892. charCode = range.toString().charCodeAt(0);
  15893. } while (charCode != 160 && charCode != 32);
  15894. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15895. while(range.toString().length){
  15896. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15897. break;
  15898. }
  15899. try{
  15900. range.setStart(range.startContainer,range.startOffset+1);
  15901. }catch(e){
  15902. //trace:2121
  15903. var start = range.startContainer;
  15904. while(!(next = start.nextSibling)){
  15905. if(domUtils.isBody(start)){
  15906. return;
  15907. }
  15908. start = start.parentNode;
  15909. }
  15910. range.setStart(next,0);
  15911. }
  15912. }
  15913. //range的开始边界已经在a标签里的不再处理
  15914. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15915. return;
  15916. }
  15917. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15918. me.undoManger && me.undoManger.save();
  15919. a.appendChild(range.extractContents());
  15920. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15921. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15922. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15923. a.setAttribute('_src',utils.html(href));
  15924. a.href = utils.html(href);
  15925. range.insertNode(a);
  15926. a.parentNode.insertBefore(text, a.nextSibling);
  15927. range.setStart(text, 0);
  15928. range.collapse(true);
  15929. sel.removeAllRanges();
  15930. sel.addRange(range);
  15931. me.undoManger && me.undoManger.save();
  15932. }
  15933. }
  15934. }
  15935. }
  15936. }:{}
  15937. },function(){
  15938. var keyCodes = {
  15939. 37:1, 38:1, 39:1, 40:1,
  15940. 13:1,32:1
  15941. };
  15942. function checkIsCludeLink(node){
  15943. if(node.nodeType == 3){
  15944. return null
  15945. }
  15946. if(node.nodeName == 'A'){
  15947. return node;
  15948. }
  15949. var lastChild = node.lastChild;
  15950. while(lastChild){
  15951. if(lastChild.nodeName == 'A'){
  15952. return lastChild;
  15953. }
  15954. if(lastChild.nodeType == 3){
  15955. if(domUtils.isWhitespace(lastChild)){
  15956. lastChild = lastChild.previousSibling;
  15957. continue;
  15958. }
  15959. return null
  15960. }
  15961. lastChild = lastChild.lastChild;
  15962. }
  15963. }
  15964. browser.ie && this.addListener('keyup',function(cmd,evt){
  15965. var me = this,keyCode = evt.keyCode;
  15966. if(keyCodes[keyCode]){
  15967. var rng = me.selection.getRange();
  15968. var start = rng.startContainer;
  15969. if(keyCode == 13){
  15970. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15971. start = start.parentNode;
  15972. }
  15973. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15974. var pre = start.previousSibling;
  15975. if(pre && pre.nodeType == 1){
  15976. var pre = checkIsCludeLink(pre);
  15977. if(pre && !pre.getAttribute('_href')){
  15978. domUtils.remove(pre,true);
  15979. }
  15980. }
  15981. }
  15982. }else if(keyCode == 32 ){
  15983. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15984. start = start.previousSibling;
  15985. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15986. domUtils.remove(start,true);
  15987. }
  15988. }
  15989. }else {
  15990. start = domUtils.findParentByTagName(start,'a',true);
  15991. if(start && !start.getAttribute('_href')){
  15992. var bk = rng.createBookmark();
  15993. domUtils.remove(start,true);
  15994. rng.moveToBookmark(bk).select(true)
  15995. }
  15996. }
  15997. }
  15998. });
  15999. }
  16000. );
  16001. // plugins/autoheight.js
  16002. ///import core
  16003. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  16004. ///commandsName AutoHeight,autoHeightEnabled
  16005. ///commandsTitle 自动增高
  16006. /**
  16007. * @description 自动伸展
  16008. * @author zhanyi
  16009. */
  16010. UE.plugins['autoheight'] = function () {
  16011. var me = this;
  16012. //提供开关,就算加载也可以关闭
  16013. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16014. if (!me.autoHeightEnabled) {
  16015. return;
  16016. }
  16017. var bakOverflow,
  16018. lastHeight = 0,
  16019. options = me.options,
  16020. currentHeight,
  16021. timer;
  16022. function adjustHeight() {
  16023. var me = this;
  16024. clearTimeout(timer);
  16025. if(isFullscreen)return;
  16026. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16027. timer = setTimeout(function(){
  16028. var node = me.body.lastChild;
  16029. while(node && node.nodeType != 1){
  16030. node = node.previousSibling;
  16031. }
  16032. if(node && node.nodeType == 1){
  16033. node.style.clear = 'both';
  16034. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  16035. if (currentHeight != lastHeight) {
  16036. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16037. me.iframe.parentNode.style.height = currentHeight + 'px';
  16038. }
  16039. me.body.style.height = currentHeight + 'px';
  16040. lastHeight = currentHeight;
  16041. }
  16042. domUtils.removeStyle(node,'clear');
  16043. }
  16044. },50)
  16045. }
  16046. }
  16047. var isFullscreen;
  16048. me.addListener('fullscreenchanged',function(cmd,f){
  16049. isFullscreen = f
  16050. });
  16051. me.addListener('destroy', function () {
  16052. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  16053. });
  16054. me.enableAutoHeight = function () {
  16055. var me = this;
  16056. if (!me.autoHeightEnabled) {
  16057. return;
  16058. }
  16059. var doc = me.document;
  16060. me.autoHeightEnabled = true;
  16061. bakOverflow = doc.body.style.overflowY;
  16062. doc.body.style.overflowY = 'hidden';
  16063. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16064. //ff不给事件算得不对
  16065. setTimeout(function () {
  16066. adjustHeight.call(me);
  16067. }, browser.gecko ? 100 : 0);
  16068. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16069. };
  16070. me.disableAutoHeight = function () {
  16071. me.body.style.overflowY = bakOverflow || '';
  16072. me.removeListener('contentchange', adjustHeight);
  16073. me.removeListener('keyup', adjustHeight);
  16074. me.removeListener('mouseup', adjustHeight);
  16075. me.autoHeightEnabled = false;
  16076. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16077. };
  16078. me.on('setHeight',function(){
  16079. me.disableAutoHeight()
  16080. });
  16081. me.addListener('ready', function () {
  16082. me.enableAutoHeight();
  16083. //trace:1764
  16084. var timer;
  16085. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16086. clearTimeout(timer);
  16087. timer = setTimeout(function () {
  16088. //trace:3681
  16089. adjustHeight.call(me);
  16090. }, 100);
  16091. });
  16092. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16093. var lastScrollY;
  16094. window.onscroll = function(){
  16095. if(lastScrollY === null){
  16096. lastScrollY = this.scrollY
  16097. }else if(this.scrollY == 0 && lastScrollY != 0){
  16098. me.window.scrollTo(0,0);
  16099. lastScrollY = null;
  16100. }
  16101. }
  16102. });
  16103. };
  16104. // plugins/autofloat.js
  16105. ///import core
  16106. ///commands 悬浮工具栏
  16107. ///commandsName AutoFloat,autoFloatEnabled
  16108. ///commandsTitle 悬浮工具栏
  16109. /**
  16110. * modified by chengchao01
  16111. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16112. */
  16113. UE.plugins['autofloat'] = function() {
  16114. var me = this,
  16115. lang = me.getLang();
  16116. me.setOpt({
  16117. topOffset:0
  16118. });
  16119. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16120. topOffset = me.options.topOffset;
  16121. //如果不固定toolbar的位置,则直接退出
  16122. if(!optsAutoFloatEnabled){
  16123. return;
  16124. }
  16125. var uiUtils = UE.ui.uiUtils,
  16126. LteIE6 = browser.ie && browser.version <= 6,
  16127. quirks = browser.quirks;
  16128. function checkHasUI(){
  16129. if(!UE.ui){
  16130. alert(lang.autofloatMsg);
  16131. return 0;
  16132. }
  16133. return 1;
  16134. }
  16135. function fixIE6FixedPos(){
  16136. var docStyle = document.body.style;
  16137. docStyle.backgroundImage = 'url("about:blank")';
  16138. docStyle.backgroundAttachment = 'fixed';
  16139. }
  16140. var bakCssText,
  16141. placeHolder = document.createElement('div'),
  16142. toolbarBox,orgTop,
  16143. getPosition,
  16144. flag =true; //ie7模式下需要偏移
  16145. function setFloating(){
  16146. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16147. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16148. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16149. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16150. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16151. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16152. if (LteIE6 || (quirks && browser.ie)) {
  16153. if(toolbarBox.style.position != 'absolute'){
  16154. toolbarBox.style.position = 'absolute';
  16155. }
  16156. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16157. } else {
  16158. if (browser.ie7Compat && flag) {
  16159. flag = false;
  16160. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16161. }
  16162. if(toolbarBox.style.position != 'fixed'){
  16163. toolbarBox.style.position = 'fixed';
  16164. toolbarBox.style.top = topOffset +"px";
  16165. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16166. }
  16167. }
  16168. }
  16169. function unsetFloating(){
  16170. flag = true;
  16171. if(placeHolder.parentNode){
  16172. placeHolder.parentNode.removeChild(placeHolder);
  16173. }
  16174. toolbarBox.style.cssText = bakCssText;
  16175. }
  16176. function updateFloating(){
  16177. var rect3 = getPosition(me.container);
  16178. var offset=me.options.toolbarTopOffset||0;
  16179. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16180. setFloating();
  16181. }else{
  16182. unsetFloating();
  16183. }
  16184. }
  16185. var defer_updateFloating = utils.defer(function(){
  16186. updateFloating();
  16187. },browser.ie ? 200 : 100,true);
  16188. me.addListener('destroy',function(){
  16189. domUtils.un(window, ['scroll','resize'], updateFloating);
  16190. me.removeListener('keydown', defer_updateFloating);
  16191. });
  16192. me.addListener('ready', function(){
  16193. if(checkHasUI(me)){
  16194. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16195. if(!me.ui){
  16196. return;
  16197. }
  16198. getPosition = uiUtils.getClientRect;
  16199. toolbarBox = me.ui.getDom('toolbarbox');
  16200. orgTop = getPosition(toolbarBox).top;
  16201. bakCssText = toolbarBox.style.cssText;
  16202. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16203. if(LteIE6){
  16204. fixIE6FixedPos();
  16205. }
  16206. domUtils.on(window, ['scroll','resize'], updateFloating);
  16207. me.addListener('keydown', defer_updateFloating);
  16208. me.addListener('beforefullscreenchange', function (t, enabled){
  16209. if (enabled) {
  16210. unsetFloating();
  16211. }
  16212. });
  16213. me.addListener('fullscreenchanged', function (t, enabled){
  16214. if (!enabled) {
  16215. updateFloating();
  16216. }
  16217. });
  16218. me.addListener('sourcemodechanged', function (t, enabled){
  16219. setTimeout(function (){
  16220. updateFloating();
  16221. },0);
  16222. });
  16223. me.addListener("clearDoc",function(){
  16224. setTimeout(function(){
  16225. updateFloating();
  16226. },0);
  16227. })
  16228. }
  16229. });
  16230. };
  16231. // plugins/video.js
  16232. /**
  16233. * video插件, 为UEditor提供视频插入支持
  16234. * @file
  16235. * @since 1.2.6.1
  16236. */
  16237. UE.plugins['video'] = function (){
  16238. var me =this;
  16239. /**
  16240. * 创建插入视频字符窜
  16241. * @param url 视频地址
  16242. * @param width 视频宽度
  16243. * @param height 视频高度
  16244. * @param align 视频对齐
  16245. * @param toEmbed 是否以flash代替显示
  16246. * @param addParagraph 是否需要添加P 标签
  16247. */
  16248. function creatInsertStr(url,width,height,id,align,classname,type){
  16249. url = utils.unhtmlForUrl(url);
  16250. align = utils.unhtml(align);
  16251. classname = utils.unhtml(classname).trim();
  16252. width = parseInt(width, 10) || 0;
  16253. height = parseInt(height, 10) || 0;
  16254. var str;
  16255. switch (type){
  16256. case 'image':
  16257. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16258. ' 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 + ';': '')+'" />'
  16259. break;
  16260. case 'embed':
  16261. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16262. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16263. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16264. break;
  16265. case 'video':
  16266. var ext = url.substr(url.lastIndexOf('.') + 1);
  16267. if(ext == 'ogv') ext = 'ogg';
  16268. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16269. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16270. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16271. break;
  16272. }
  16273. return str;
  16274. }
  16275. function switchImgAndVideo(root,img2video){
  16276. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16277. var className = node.getAttr('class');
  16278. if(className && className.indexOf('edui-faked-video') != -1){
  16279. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16280. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16281. }
  16282. if(className && className.indexOf('edui-upload-video') != -1){
  16283. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16284. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16285. }
  16286. })
  16287. }
  16288. me.addOutputRule(function(root){
  16289. switchImgAndVideo(root,true)
  16290. });
  16291. me.addInputRule(function(root){
  16292. switchImgAndVideo(root)
  16293. });
  16294. /**
  16295. * 插入视频
  16296. * @command insertvideo
  16297. * @method execCommand
  16298. * @param { String } cmd 命令字符串
  16299. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16300. * @example
  16301. * ```javascript
  16302. *
  16303. * var videoAttr = {
  16304. * //视频地址
  16305. * url: 'http://www.youku.com/xxx',
  16306. * //视频宽高值, 单位px
  16307. * width: 200,
  16308. * height: 100
  16309. * };
  16310. *
  16311. * //editor 是编辑器实例
  16312. * //向编辑器插入单个视频
  16313. * editor.execCommand( 'insertvideo', videoAttr );
  16314. * ```
  16315. */
  16316. /**
  16317. * 插入视频
  16318. * @command insertvideo
  16319. * @method execCommand
  16320. * @param { String } cmd 命令字符串
  16321. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16322. * @example
  16323. * ```javascript
  16324. *
  16325. * var videoAttr1 = {
  16326. * //视频地址
  16327. * url: 'http://www.youku.com/xxx',
  16328. * //视频宽高值, 单位px
  16329. * width: 200,
  16330. * height: 100
  16331. * },
  16332. * videoAttr2 = {
  16333. * //视频地址
  16334. * url: 'http://www.youku.com/xxx',
  16335. * //视频宽高值, 单位px
  16336. * width: 200,
  16337. * height: 100
  16338. * }
  16339. *
  16340. * //editor 是编辑器实例
  16341. * //该方法将会向编辑器内插入两个视频
  16342. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16343. * ```
  16344. */
  16345. /**
  16346. * 查询当前光标所在处是否是一个视频
  16347. * @command insertvideo
  16348. * @method queryCommandState
  16349. * @param { String } cmd 需要查询的命令字符串
  16350. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16351. * @example
  16352. * ```javascript
  16353. *
  16354. * //editor 是编辑器实例
  16355. * editor.queryCommandState( 'insertvideo' );
  16356. * ```
  16357. */
  16358. me.commands["insertvideo"] = {
  16359. execCommand: function (cmd, videoObjs, type){
  16360. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16361. var html = [],id = 'tmpVedio', cl;
  16362. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16363. vi = videoObjs[i];
  16364. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16365. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16366. }
  16367. me.execCommand("inserthtml",html.join(""),true);
  16368. var rng = this.selection.getRange();
  16369. for(var i= 0,len=videoObjs.length;i<len;i++){
  16370. var img = this.document.getElementById('tmpVedio'+i);
  16371. domUtils.removeAttributes(img,'id');
  16372. rng.selectNode(img).select();
  16373. me.execCommand('imagefloat',videoObjs[i].align)
  16374. }
  16375. },
  16376. queryCommandState : function(){
  16377. var img = me.selection.getRange().getClosedNode(),
  16378. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16379. return flag ? 1 : 0;
  16380. }
  16381. };
  16382. };
  16383. // plugins/table.core.js
  16384. /**
  16385. * Created with JetBrains WebStorm.
  16386. * User: taoqili
  16387. * Date: 13-1-18
  16388. * Time: 上午11:09
  16389. * To change this template use File | Settings | File Templates.
  16390. */
  16391. /**
  16392. * UE表格操作类
  16393. * @param table
  16394. * @constructor
  16395. */
  16396. (function () {
  16397. var UETable = UE.UETable = function (table) {
  16398. this.table = table;
  16399. this.indexTable = [];
  16400. this.selectedTds = [];
  16401. this.cellsRange = {};
  16402. this.update(table);
  16403. };
  16404. //===以下为静态工具方法===
  16405. UETable.removeSelectedClass = function (cells) {
  16406. utils.each(cells, function (cell) {
  16407. domUtils.removeClasses(cell, "selectTdClass");
  16408. })
  16409. };
  16410. UETable.addSelectedClass = function (cells) {
  16411. utils.each(cells, function (cell) {
  16412. domUtils.addClass(cell, "selectTdClass");
  16413. })
  16414. };
  16415. UETable.isEmptyBlock = function (node) {
  16416. var reg = new RegExp(domUtils.fillChar, 'g');
  16417. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16418. return 0;
  16419. }
  16420. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16421. if (node.getElementsByTagName(i).length) {
  16422. return 0;
  16423. }
  16424. }
  16425. return 1;
  16426. };
  16427. UETable.getWidth = function (cell) {
  16428. if (!cell)return 0;
  16429. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16430. };
  16431. /**
  16432. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16433. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16434. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16435. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16436. */
  16437. UETable.getTableCellAlignState = function ( cells ) {
  16438. !utils.isArray( cells ) && ( cells = [cells] );
  16439. var result = {},
  16440. status = ['align', 'valign'],
  16441. tempStatus = null,
  16442. isSame = true;//状态是否相同
  16443. utils.each( cells, function( cellNode ){
  16444. utils.each( status, function( currentState ){
  16445. tempStatus = cellNode.getAttribute( currentState );
  16446. if( !result[ currentState ] && tempStatus ) {
  16447. result[ currentState ] = tempStatus;
  16448. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16449. isSame = false;
  16450. return false;
  16451. }
  16452. } );
  16453. return isSame;
  16454. });
  16455. return isSame ? result : null;
  16456. };
  16457. /**
  16458. * 根据当前选区获取相关的table信息
  16459. * @return {Object}
  16460. */
  16461. UETable.getTableItemsByRange = function (editor) {
  16462. var start = editor.selection.getStart();
  16463. //ff下会选中bookmark
  16464. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16465. start = start.nextSibling;
  16466. }
  16467. //在table或者td边缘有可能存在选中tr的情况
  16468. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16469. tr = cell && cell.parentNode,
  16470. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16471. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16472. return {
  16473. cell:cell,
  16474. tr:tr,
  16475. table:table,
  16476. caption:caption
  16477. }
  16478. };
  16479. UETable.getUETableBySelected = function (editor) {
  16480. var table = UETable.getTableItemsByRange(editor).table;
  16481. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16482. return table.ueTable;
  16483. }
  16484. return null;
  16485. };
  16486. UETable.getDefaultValue = function (editor, table) {
  16487. var borderMap = {
  16488. thin:'0px',
  16489. medium:'1px',
  16490. thick:'2px'
  16491. },
  16492. tableBorder, tdPadding, tdBorder, tmpValue;
  16493. if (!table) {
  16494. table = editor.document.createElement('table');
  16495. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16496. editor.body.appendChild(table);
  16497. var td = table.getElementsByTagName('td')[0];
  16498. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16499. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16500. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16501. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16502. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16503. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16504. domUtils.remove(table);
  16505. return {
  16506. tableBorder:tableBorder,
  16507. tdPadding:tdPadding,
  16508. tdBorder:tdBorder
  16509. };
  16510. } else {
  16511. td = table.getElementsByTagName('td')[0];
  16512. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16513. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16514. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16515. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16516. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16517. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16518. return {
  16519. tableBorder:tableBorder,
  16520. tdPadding:tdPadding,
  16521. tdBorder:tdBorder
  16522. };
  16523. }
  16524. };
  16525. /**
  16526. * 根据当前点击的td或者table获取索引对象
  16527. * @param tdOrTable
  16528. */
  16529. UETable.getUETable = function (tdOrTable) {
  16530. var tag = tdOrTable.tagName.toLowerCase();
  16531. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16532. if (!tdOrTable.ueTable) {
  16533. tdOrTable.ueTable = new UETable(tdOrTable);
  16534. }
  16535. return tdOrTable.ueTable;
  16536. };
  16537. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16538. if (!cell || utils.isString(cell)) {
  16539. return this.table.ownerDocument.createElement(cell || 'td');
  16540. }
  16541. var flag = domUtils.hasClass(cell, "selectTdClass");
  16542. flag && domUtils.removeClasses(cell, "selectTdClass");
  16543. var tmpCell = cell.cloneNode(true);
  16544. if (ignoreMerge) {
  16545. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16546. }
  16547. //去掉宽高
  16548. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16549. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16550. tmpCell.style.borderLeftStyle = "";
  16551. tmpCell.style.borderTopStyle = "";
  16552. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16553. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16554. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16555. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16556. flag && domUtils.addClass(cell, "selectTdClass");
  16557. return tmpCell;
  16558. }
  16559. UETable.prototype = {
  16560. getMaxRows:function () {
  16561. var rows = this.table.rows, maxLen = 1;
  16562. for (var i = 0, row; row = rows[i]; i++) {
  16563. var currentMax = 1;
  16564. for (var j = 0, cj; cj = row.cells[j++];) {
  16565. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16566. }
  16567. maxLen = Math.max(currentMax + i, maxLen);
  16568. }
  16569. return maxLen;
  16570. },
  16571. /**
  16572. * 获取当前表格的最大列数
  16573. */
  16574. getMaxCols:function () {
  16575. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16576. for (var i = 0, row; row = rows[i]; i++) {
  16577. var cellsNum = 0;
  16578. for (var j = 0, cj; cj = row.cells[j++];) {
  16579. cellsNum += (cj.colSpan || 1);
  16580. if (cj.rowSpan && cj.rowSpan > 1) {
  16581. for (var k = 1; k < cj.rowSpan; k++) {
  16582. if (!cellRows['row_' + (i + k)]) {
  16583. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16584. } else {
  16585. cellRows['row_' + (i + k)]++
  16586. }
  16587. }
  16588. }
  16589. }
  16590. cellsNum += cellRows['row_' + i] || 0;
  16591. maxLen = Math.max(cellsNum, maxLen);
  16592. }
  16593. return maxLen;
  16594. },
  16595. getCellColIndex:function (cell) {
  16596. },
  16597. /**
  16598. * 获取当前cell旁边的单元格,
  16599. * @param cell
  16600. * @param right
  16601. */
  16602. getHSideCell:function (cell, right) {
  16603. try {
  16604. var cellInfo = this.getCellInfo(cell),
  16605. previewRowIndex, previewColIndex;
  16606. var len = this.selectedTds.length,
  16607. range = this.cellsRange;
  16608. //首行或者首列没有前置单元格
  16609. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16610. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16611. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16612. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16613. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16614. } catch (e) {
  16615. showError(e);
  16616. }
  16617. },
  16618. getTabNextCell:function (cell, preRowIndex) {
  16619. var cellInfo = this.getCellInfo(cell),
  16620. rowIndex = preRowIndex || cellInfo.rowIndex,
  16621. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16622. nextCell;
  16623. try {
  16624. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16625. } catch (e) {
  16626. try {
  16627. rowIndex = rowIndex * 1 + 1;
  16628. colIndex = 0;
  16629. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16630. } catch (e) {
  16631. }
  16632. }
  16633. return nextCell;
  16634. },
  16635. /**
  16636. * 获取视觉上的后置单元格
  16637. * @param cell
  16638. * @param bottom
  16639. */
  16640. getVSideCell:function (cell, bottom, ignoreRange) {
  16641. try {
  16642. var cellInfo = this.getCellInfo(cell),
  16643. nextRowIndex, nextColIndex;
  16644. var len = this.selectedTds.length && !ignoreRange,
  16645. range = this.cellsRange;
  16646. //末行或者末列没有后置单元格
  16647. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16648. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16649. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16650. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16651. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16652. } catch (e) {
  16653. showError(e);
  16654. }
  16655. },
  16656. /**
  16657. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16658. */
  16659. getSameEndPosCells:function (cell, xOrY) {
  16660. try {
  16661. var flag = (xOrY.toLowerCase() === "x"),
  16662. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16663. rows = this.table.rows,
  16664. cells = null, returns = [];
  16665. for (var i = 0; i < this.rowsNum; i++) {
  16666. cells = rows[i].cells;
  16667. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16668. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16669. //对应行的td已经被上面行rowSpan了
  16670. if (tmpEnd > end && flag) break;
  16671. if (cell == tmpCell || end == tmpEnd) {
  16672. //只获取单一的单元格
  16673. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16674. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16675. returns.push(tmpCell);
  16676. }
  16677. if (flag) break;
  16678. }
  16679. }
  16680. }
  16681. return returns;
  16682. } catch (e) {
  16683. showError(e);
  16684. }
  16685. },
  16686. setCellContent:function (cell, content) {
  16687. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16688. },
  16689. cloneCell:UETable.cloneCell,
  16690. /**
  16691. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16692. */
  16693. getSameStartPosXCells:function (cell) {
  16694. try {
  16695. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16696. rows = this.table.rows, cells , returns = [];
  16697. for (var i = 0; i < this.rowsNum; i++) {
  16698. cells = rows[i].cells;
  16699. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16700. var tmpStart = domUtils.getXY(tmpCell).x;
  16701. if (tmpStart > start) break;
  16702. if (tmpStart == start && tmpCell.colSpan == 1) {
  16703. returns.push(tmpCell);
  16704. break;
  16705. }
  16706. }
  16707. }
  16708. return returns;
  16709. } catch (e) {
  16710. showError(e);
  16711. }
  16712. },
  16713. /**
  16714. * 更新table对应的索引表
  16715. */
  16716. update:function (table) {
  16717. this.table = table || this.table;
  16718. this.selectedTds = [];
  16719. this.cellsRange = {};
  16720. this.indexTable = [];
  16721. var rows = this.table.rows,
  16722. rowsNum = this.getMaxRows(),
  16723. dNum = rowsNum - rows.length,
  16724. colsNum = this.getMaxCols();
  16725. while (dNum--) {
  16726. this.table.insertRow(rows.length);
  16727. }
  16728. this.rowsNum = rowsNum;
  16729. this.colsNum = colsNum;
  16730. for (var i = 0, len = rows.length; i < len; i++) {
  16731. this.indexTable[i] = new Array(colsNum);
  16732. }
  16733. //填充索引表
  16734. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16735. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16736. //修正整行被rowSpan时导致的行数计算错误
  16737. if (cell.rowSpan > rowsNum) {
  16738. cell.rowSpan = rowsNum;
  16739. }
  16740. var colIndex = cellIndex,
  16741. rowSpan = cell.rowSpan || 1,
  16742. colSpan = cell.colSpan || 1;
  16743. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16744. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16745. for (var j = 0; j < rowSpan; j++) {
  16746. for (var k = 0; k < colSpan; k++) {
  16747. this.indexTable[rowIndex + j][colIndex + k] = {
  16748. rowIndex:rowIndex,
  16749. cellIndex:cellIndex,
  16750. colIndex:colIndex,
  16751. rowSpan:rowSpan,
  16752. colSpan:colSpan
  16753. }
  16754. }
  16755. }
  16756. }
  16757. }
  16758. //修复残缺td
  16759. for (j = 0; j < rowsNum; j++) {
  16760. for (k = 0; k < colsNum; k++) {
  16761. if (this.indexTable[j][k] === undefined) {
  16762. row = rows[j];
  16763. cell = row.cells[row.cells.length - 1];
  16764. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16765. this.setCellContent(cell);
  16766. if (cell.colSpan !== 1)cell.colSpan = 1;
  16767. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16768. row.appendChild(cell);
  16769. this.indexTable[j][k] = {
  16770. rowIndex:j,
  16771. cellIndex:cell.cellIndex,
  16772. colIndex:k,
  16773. rowSpan:1,
  16774. colSpan:1
  16775. }
  16776. }
  16777. }
  16778. }
  16779. //当框选后删除行或者列后撤销,需要重建选区。
  16780. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16781. selectTds = [];
  16782. utils.each(tds, function (td) {
  16783. if (domUtils.hasClass(td, "selectTdClass")) {
  16784. selectTds.push(td);
  16785. }
  16786. });
  16787. if (selectTds.length) {
  16788. var start = selectTds[0],
  16789. end = selectTds[selectTds.length - 1],
  16790. startInfo = this.getCellInfo(start),
  16791. endInfo = this.getCellInfo(end);
  16792. this.selectedTds = selectTds;
  16793. this.cellsRange = {
  16794. beginRowIndex:startInfo.rowIndex,
  16795. beginColIndex:startInfo.colIndex,
  16796. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16797. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16798. };
  16799. }
  16800. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16801. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16802. domUtils.addClass(this.table.rows[0], "firstRow");
  16803. for(var i = 1; i< this.table.rows.length; i++) {
  16804. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16805. }
  16806. }
  16807. },
  16808. /**
  16809. * 获取单元格的索引信息
  16810. */
  16811. getCellInfo:function (cell) {
  16812. if (!cell) return;
  16813. var cellIndex = cell.cellIndex,
  16814. rowIndex = cell.parentNode.rowIndex,
  16815. rowInfo = this.indexTable[rowIndex],
  16816. numCols = this.colsNum;
  16817. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16818. var cellInfo = rowInfo[colIndex];
  16819. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16820. return cellInfo;
  16821. }
  16822. }
  16823. },
  16824. /**
  16825. * 根据行列号获取单元格
  16826. */
  16827. getCell:function (rowIndex, cellIndex) {
  16828. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16829. },
  16830. /**
  16831. * 删除单元格
  16832. */
  16833. deleteCell:function (cell, rowIndex) {
  16834. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16835. var row = this.table.rows[rowIndex];
  16836. row.deleteCell(cell.cellIndex);
  16837. },
  16838. /**
  16839. * 根据始末两个单元格获取被框选的所有单元格范围
  16840. */
  16841. getCellsRange:function (cellA, cellB) {
  16842. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16843. var tmpBeginRowIndex = beginRowIndex,
  16844. tmpBeginColIndex = beginColIndex,
  16845. tmpEndRowIndex = endRowIndex,
  16846. tmpEndColIndex = endColIndex,
  16847. cellInfo, colIndex, rowIndex;
  16848. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16849. if (beginRowIndex > 0) {
  16850. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16851. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16852. rowIndex = cellInfo.rowIndex;
  16853. if (rowIndex < beginRowIndex) {
  16854. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16855. }
  16856. }
  16857. }
  16858. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16859. if (endColIndex < me.colsNum) {
  16860. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16861. cellInfo = me.indexTable[rowIndex][endColIndex];
  16862. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16863. if (colIndex > endColIndex) {
  16864. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16865. }
  16866. }
  16867. }
  16868. // 检查是否有超出TableRange下边界的情况
  16869. if (endRowIndex < me.rowsNum) {
  16870. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16871. cellInfo = me.indexTable[endRowIndex][colIndex];
  16872. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16873. if (rowIndex > endRowIndex) {
  16874. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16875. }
  16876. }
  16877. }
  16878. // 检查是否有超出TableRange左边界的情况
  16879. if (beginColIndex > 0) {
  16880. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16881. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16882. colIndex = cellInfo.colIndex;
  16883. if (colIndex < beginColIndex) {
  16884. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16885. }
  16886. }
  16887. }
  16888. //递归调用直至所有完成所有框选单元格的扩展
  16889. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16890. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16891. } else {
  16892. // 不需要扩展TableRange的情况
  16893. return {
  16894. beginRowIndex:beginRowIndex,
  16895. beginColIndex:beginColIndex,
  16896. endRowIndex:endRowIndex,
  16897. endColIndex:endColIndex
  16898. };
  16899. }
  16900. }
  16901. try {
  16902. var me = this,
  16903. cellAInfo = me.getCellInfo(cellA);
  16904. if (cellA === cellB) {
  16905. return {
  16906. beginRowIndex:cellAInfo.rowIndex,
  16907. beginColIndex:cellAInfo.colIndex,
  16908. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16909. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16910. };
  16911. }
  16912. var cellBInfo = me.getCellInfo(cellB);
  16913. // 计算TableRange的四个边
  16914. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16915. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16916. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16917. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16918. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16919. } catch (e) {
  16920. //throw e;
  16921. }
  16922. },
  16923. /**
  16924. * 依据cellsRange获取对应的单元格集合
  16925. */
  16926. getCells:function (range) {
  16927. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16928. this.clearSelected();
  16929. var beginRowIndex = range.beginRowIndex,
  16930. beginColIndex = range.beginColIndex,
  16931. endRowIndex = range.endRowIndex,
  16932. endColIndex = range.endColIndex,
  16933. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16934. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16935. for (var j = beginColIndex; j <= endColIndex; j++) {
  16936. cellInfo = this.indexTable[i][j];
  16937. rowIndex = cellInfo.rowIndex;
  16938. colIndex = cellInfo.colIndex;
  16939. // 如果Cells里已经包含了此Cell则跳过
  16940. var key = rowIndex + '|' + colIndex;
  16941. if (tdHash[key]) continue;
  16942. tdHash[key] = 1;
  16943. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16944. return null;
  16945. }
  16946. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16947. }
  16948. }
  16949. return returnTds;
  16950. },
  16951. /**
  16952. * 清理已经选中的单元格
  16953. */
  16954. clearSelected:function () {
  16955. UETable.removeSelectedClass(this.selectedTds);
  16956. this.selectedTds = [];
  16957. this.cellsRange = {};
  16958. },
  16959. /**
  16960. * 根据range设置已经选中的单元格
  16961. */
  16962. setSelected:function (range) {
  16963. var cells = this.getCells(range);
  16964. UETable.addSelectedClass(cells);
  16965. this.selectedTds = cells;
  16966. this.cellsRange = range;
  16967. },
  16968. isFullRow:function () {
  16969. var range = this.cellsRange;
  16970. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16971. },
  16972. isFullCol:function () {
  16973. var range = this.cellsRange,
  16974. table = this.table,
  16975. ths = table.getElementsByTagName("th"),
  16976. rows = range.endRowIndex - range.beginRowIndex + 1;
  16977. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16978. },
  16979. /**
  16980. * 获取视觉上的前置单元格,默认是左边,top传入时
  16981. * @param cell
  16982. * @param top
  16983. */
  16984. getNextCell:function (cell, bottom, ignoreRange) {
  16985. try {
  16986. var cellInfo = this.getCellInfo(cell),
  16987. nextRowIndex, nextColIndex;
  16988. var len = this.selectedTds.length && !ignoreRange,
  16989. range = this.cellsRange;
  16990. //末行或者末列没有后置单元格
  16991. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16992. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16993. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16994. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16995. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16996. } catch (e) {
  16997. showError(e);
  16998. }
  16999. },
  17000. getPreviewCell:function (cell, top) {
  17001. try {
  17002. var cellInfo = this.getCellInfo(cell),
  17003. previewRowIndex, previewColIndex;
  17004. var len = this.selectedTds.length,
  17005. range = this.cellsRange;
  17006. //首行或者首列没有前置单元格
  17007. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17008. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  17009. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17010. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17011. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  17012. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17013. } catch (e) {
  17014. showError(e);
  17015. }
  17016. },
  17017. /**
  17018. * 移动单元格中的内容
  17019. */
  17020. moveContent:function (cellTo, cellFrom) {
  17021. if (UETable.isEmptyBlock(cellFrom)) return;
  17022. if (UETable.isEmptyBlock(cellTo)) {
  17023. cellTo.innerHTML = cellFrom.innerHTML;
  17024. return;
  17025. }
  17026. var child = cellTo.lastChild;
  17027. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17028. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17029. }
  17030. while (child = cellFrom.firstChild) {
  17031. cellTo.appendChild(child);
  17032. }
  17033. },
  17034. /**
  17035. * 向右合并单元格
  17036. */
  17037. mergeRight:function (cell) {
  17038. var cellInfo = this.getCellInfo(cell),
  17039. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17040. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17041. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17042. //合并
  17043. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17044. //被合并的单元格不应存在宽度属性
  17045. cell.removeAttribute("width");
  17046. //移动内容
  17047. this.moveContent(cell, rightCell);
  17048. //删掉被合并的Cell
  17049. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17050. this.update();
  17051. },
  17052. /**
  17053. * 向下合并单元格
  17054. */
  17055. mergeDown:function (cell) {
  17056. var cellInfo = this.getCellInfo(cell),
  17057. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17058. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17059. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17060. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17061. cell.removeAttribute("height");
  17062. this.moveContent(cell, downCell);
  17063. this.deleteCell(downCell, downCellInfo.rowIndex);
  17064. this.update();
  17065. },
  17066. /**
  17067. * 合并整个range中的内容
  17068. */
  17069. mergeRange:function () {
  17070. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17071. var range = this.cellsRange,
  17072. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17073. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17074. var index = this.indexTable,
  17075. info = this.getCellInfo(leftTopCell);
  17076. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17077. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17078. }
  17079. // 删除剩余的Cells
  17080. var cells = this.getCells(range);
  17081. for(var i= 0,ci;ci=cells[i++];){
  17082. if (ci !== leftTopCell) {
  17083. this.moveContent(leftTopCell, ci);
  17084. this.deleteCell(ci);
  17085. }
  17086. }
  17087. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17088. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17089. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17090. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17091. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17092. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17093. leftTopCell.colSpan = 1;
  17094. }
  17095. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17096. var rowIndex = leftTopCell.parentNode.rowIndex;
  17097. //解决IE下的表格操作问题
  17098. if( this.table.deleteRow ) {
  17099. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17100. this.table.deleteRow(curIndex);
  17101. }
  17102. } else {
  17103. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17104. var row = this.table.rows[rowIndex + 1];
  17105. row.parentNode.removeChild(row);
  17106. }
  17107. }
  17108. leftTopCell.rowSpan = 1;
  17109. }
  17110. this.update();
  17111. },
  17112. /**
  17113. * 插入一行单元格
  17114. */
  17115. insertRow:function (rowIndex, sourceCell) {
  17116. var numCols = this.colsNum,
  17117. table = this.table,
  17118. row = table.insertRow(rowIndex), cell,
  17119. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17120. function replaceTdToTh(colIndex, cell, tableRow) {
  17121. if (colIndex == 0) {
  17122. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17123. th = tr.cells[colIndex];
  17124. if (th.tagName == 'TH') {
  17125. th = cell.ownerDocument.createElement("th");
  17126. th.appendChild(cell.firstChild);
  17127. tableRow.insertBefore(th, cell);
  17128. domUtils.remove(cell)
  17129. }
  17130. }else{
  17131. if (cell.tagName == 'TH') {
  17132. var td = cell.ownerDocument.createElement("td");
  17133. td.appendChild(cell.firstChild);
  17134. tableRow.insertBefore(td, cell);
  17135. domUtils.remove(cell)
  17136. }
  17137. }
  17138. }
  17139. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17140. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17141. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17142. cell = this.cloneCell(sourceCell, true);
  17143. this.setCellContent(cell);
  17144. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17145. row.appendChild(cell);
  17146. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17147. }
  17148. } else {
  17149. var infoRow = this.indexTable[rowIndex],
  17150. cellIndex = 0;
  17151. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17152. var cellInfo = infoRow[colIndex];
  17153. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17154. if (cellInfo.rowIndex < rowIndex) {
  17155. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17156. cell.rowSpan = cellInfo.rowSpan + 1;
  17157. } else {
  17158. cell = this.cloneCell(sourceCell, true);
  17159. this.setCellContent(cell);
  17160. row.appendChild(cell);
  17161. }
  17162. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17163. }
  17164. }
  17165. //框选时插入不触发contentchange,需要手动更新索引。
  17166. this.update();
  17167. return row;
  17168. },
  17169. /**
  17170. * 删除一行单元格
  17171. * @param rowIndex
  17172. */
  17173. deleteRow:function (rowIndex) {
  17174. var row = this.table.rows[rowIndex],
  17175. infoRow = this.indexTable[rowIndex],
  17176. colsNum = this.colsNum,
  17177. count = 0; //处理计数
  17178. for (var colIndex = 0; colIndex < colsNum;) {
  17179. var cellInfo = infoRow[colIndex],
  17180. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17181. if (cell.rowSpan > 1) {
  17182. if (cellInfo.rowIndex == rowIndex) {
  17183. var clone = cell.cloneNode(true);
  17184. clone.rowSpan = cell.rowSpan - 1;
  17185. clone.innerHTML = "";
  17186. cell.rowSpan = 1;
  17187. var nextRowIndex = rowIndex + 1,
  17188. nextRow = this.table.rows[nextRowIndex],
  17189. insertCellIndex,
  17190. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17191. if (preMerged < colIndex) {
  17192. insertCellIndex = colIndex - preMerged - 1;
  17193. //nextRow.insertCell(insertCellIndex);
  17194. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17195. } else {
  17196. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17197. }
  17198. count += 1;
  17199. //cell.parentNode.removeChild(cell);
  17200. }
  17201. }
  17202. colIndex += cell.colSpan || 1;
  17203. }
  17204. var deleteTds = [], cacheMap = {};
  17205. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17206. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17207. tmpCellIndex = infoRow[colIndex].cellIndex,
  17208. key = tmpRowIndex + "_" + tmpCellIndex;
  17209. if (cacheMap[key])continue;
  17210. cacheMap[key] = 1;
  17211. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17212. deleteTds.push(cell);
  17213. }
  17214. var mergeTds = [];
  17215. utils.each(deleteTds, function (td) {
  17216. if (td.rowSpan == 1) {
  17217. td.parentNode.removeChild(td);
  17218. } else {
  17219. mergeTds.push(td);
  17220. }
  17221. });
  17222. utils.each(mergeTds, function (td) {
  17223. td.rowSpan--;
  17224. });
  17225. row.parentNode.removeChild(row);
  17226. //浏览器方法本身存在bug,采用自定义方法删除
  17227. //this.table.deleteRow(rowIndex);
  17228. this.update();
  17229. },
  17230. insertCol:function (colIndex, sourceCell, defaultValue) {
  17231. var rowsNum = this.rowsNum,
  17232. rowIndex = 0,
  17233. tableRow, cell,
  17234. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17235. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17236. function replaceTdToTh(rowIndex, cell, tableRow) {
  17237. if (rowIndex == 0) {
  17238. var th = cell.nextSibling || cell.previousSibling;
  17239. if (th.tagName == 'TH') {
  17240. th = cell.ownerDocument.createElement("th");
  17241. th.appendChild(cell.firstChild);
  17242. tableRow.insertBefore(th, cell);
  17243. domUtils.remove(cell)
  17244. }
  17245. }else{
  17246. if (cell.tagName == 'TH') {
  17247. var td = cell.ownerDocument.createElement("td");
  17248. td.appendChild(cell.firstChild);
  17249. tableRow.insertBefore(td, cell);
  17250. domUtils.remove(cell)
  17251. }
  17252. }
  17253. }
  17254. var preCell;
  17255. if (colIndex == 0 || colIndex == this.colsNum) {
  17256. for (; rowIndex < rowsNum; rowIndex++) {
  17257. tableRow = this.table.rows[rowIndex];
  17258. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17259. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17260. this.setCellContent(cell);
  17261. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17262. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17263. if (!colIndex) {
  17264. tableRow.insertBefore(cell, tableRow.cells[0]);
  17265. } else {
  17266. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17267. }
  17268. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17269. }
  17270. } else {
  17271. for (; rowIndex < rowsNum; rowIndex++) {
  17272. var cellInfo = this.indexTable[rowIndex][colIndex];
  17273. if (cellInfo.colIndex < colIndex) {
  17274. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17275. cell.colSpan = cellInfo.colSpan + 1;
  17276. } else {
  17277. tableRow = this.table.rows[rowIndex];
  17278. preCell = tableRow.cells[cellInfo.cellIndex];
  17279. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17280. this.setCellContent(cell);
  17281. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17282. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17283. //防止IE下报错
  17284. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17285. }
  17286. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17287. }
  17288. }
  17289. //框选时插入不触发contentchange,需要手动更新索引
  17290. this.update();
  17291. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17292. },
  17293. updateWidth:function (width, defaultValue) {
  17294. var table = this.table,
  17295. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17296. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17297. table.setAttribute("width", tmpWidth);
  17298. return;
  17299. }
  17300. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17301. utils.each(tds, function (td) {
  17302. td.setAttribute("width", width);
  17303. })
  17304. },
  17305. deleteCol:function (colIndex) {
  17306. var indexTable = this.indexTable,
  17307. tableRows = this.table.rows,
  17308. backTableWidth = this.table.getAttribute("width"),
  17309. backTdWidth = 0,
  17310. rowsNum = this.rowsNum,
  17311. cacheMap = {};
  17312. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17313. var infoRow = indexTable[rowIndex],
  17314. cellInfo = infoRow[colIndex],
  17315. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17316. // 跳过已经处理过的Cell
  17317. if (cacheMap[key])continue;
  17318. cacheMap[key] = 1;
  17319. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17320. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17321. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17322. if (cell.colSpan > 1) {
  17323. cell.colSpan--;
  17324. } else {
  17325. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17326. }
  17327. rowIndex += cellInfo.rowSpan || 1;
  17328. }
  17329. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17330. this.update();
  17331. },
  17332. splitToCells:function (cell) {
  17333. var me = this,
  17334. cells = this.splitToRows(cell);
  17335. utils.each(cells, function (cell) {
  17336. me.splitToCols(cell);
  17337. })
  17338. },
  17339. splitToRows:function (cell) {
  17340. var cellInfo = this.getCellInfo(cell),
  17341. rowIndex = cellInfo.rowIndex,
  17342. colIndex = cellInfo.colIndex,
  17343. results = [];
  17344. // 修改Cell的rowSpan
  17345. cell.rowSpan = 1;
  17346. results.push(cell);
  17347. // 补齐单元格
  17348. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17349. if (i == rowIndex)continue;
  17350. var tableRow = this.table.rows[i],
  17351. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17352. tmpCell.colSpan = cellInfo.colSpan;
  17353. this.setCellContent(tmpCell);
  17354. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17355. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17356. if (cell.style.cssText) {
  17357. tmpCell.style.cssText = cell.style.cssText;
  17358. }
  17359. results.push(tmpCell);
  17360. }
  17361. this.update();
  17362. return results;
  17363. },
  17364. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17365. var indexRow = this.indexTable[rowIndex],
  17366. num = 0;
  17367. for (var i = 0; i < colIndex;) {
  17368. var colSpan = indexRow[i].colSpan,
  17369. tmpRowIndex = indexRow[i].rowIndex;
  17370. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17371. i += colSpan;
  17372. }
  17373. return num;
  17374. },
  17375. splitToCols:function (cell) {
  17376. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17377. cellInfo = this.getCellInfo(cell),
  17378. rowIndex = cellInfo.rowIndex,
  17379. colIndex = cellInfo.colIndex,
  17380. results = [];
  17381. // 修改Cell的rowSpan
  17382. cell.colSpan = 1;
  17383. cell.setAttribute("width", backWidth);
  17384. results.push(cell);
  17385. // 补齐单元格
  17386. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17387. if (j == colIndex)continue;
  17388. var tableRow = this.table.rows[rowIndex],
  17389. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17390. tmpCell.rowSpan = cellInfo.rowSpan;
  17391. this.setCellContent(tmpCell);
  17392. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17393. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17394. tmpCell.setAttribute('width', backWidth);
  17395. if (cell.style.cssText) {
  17396. tmpCell.style.cssText = cell.style.cssText;
  17397. }
  17398. //处理th的情况
  17399. if (cell.tagName == 'TH') {
  17400. var th = cell.ownerDocument.createElement('th');
  17401. th.appendChild(tmpCell.firstChild);
  17402. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17403. th.rowSpan = tmpCell.rowSpan;
  17404. tableRow.insertBefore(th, tmpCell);
  17405. domUtils.remove(tmpCell);
  17406. }
  17407. results.push(tmpCell);
  17408. }
  17409. this.update();
  17410. return results;
  17411. },
  17412. isLastCell:function (cell, rowsNum, colsNum) {
  17413. rowsNum = rowsNum || this.rowsNum;
  17414. colsNum = colsNum || this.colsNum;
  17415. var cellInfo = this.getCellInfo(cell);
  17416. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17417. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17418. },
  17419. getLastCell:function (cells) {
  17420. cells = cells || this.table.getElementsByTagName("td");
  17421. var firstInfo = this.getCellInfo(cells[0]);
  17422. var me = this, last = cells[0],
  17423. tr = last.parentNode,
  17424. cellsNum = 0, cols = 0, rows;
  17425. utils.each(cells, function (cell) {
  17426. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17427. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17428. });
  17429. rows = cellsNum / cols;
  17430. utils.each(cells, function (cell) {
  17431. if (me.isLastCell(cell, rows, cols)) {
  17432. last = cell;
  17433. return false;
  17434. }
  17435. });
  17436. return last;
  17437. },
  17438. selectRow:function (rowIndex) {
  17439. var indexRow = this.indexTable[rowIndex],
  17440. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17441. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17442. range = this.getCellsRange(start, end);
  17443. this.setSelected(range);
  17444. },
  17445. selectTable:function () {
  17446. var tds = this.table.getElementsByTagName("td"),
  17447. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17448. this.setSelected(range);
  17449. },
  17450. setBackground:function (cells, value) {
  17451. if (typeof value === "string") {
  17452. utils.each(cells, function (cell) {
  17453. cell.style.backgroundColor = value;
  17454. })
  17455. } else if (typeof value === "object") {
  17456. value = utils.extend({
  17457. repeat:true,
  17458. colorList:["#ddd", "#fff"]
  17459. }, value);
  17460. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17461. count = 0,
  17462. colors = value.colorList,
  17463. getColor = function (list, index, repeat) {
  17464. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17465. };
  17466. for (var i = 0, cell; cell = cells[i++];) {
  17467. var cellInfo = this.getCellInfo(cell);
  17468. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17469. }
  17470. }
  17471. },
  17472. removeBackground:function (cells) {
  17473. utils.each(cells, function (cell) {
  17474. cell.style.backgroundColor = "";
  17475. })
  17476. }
  17477. };
  17478. function showError(e) {
  17479. }
  17480. })();
  17481. // plugins/table.cmds.js
  17482. /**
  17483. * Created with JetBrains PhpStorm.
  17484. * User: taoqili
  17485. * Date: 13-2-20
  17486. * Time: 下午6:25
  17487. * To change this template use File | Settings | File Templates.
  17488. */
  17489. ;
  17490. (function () {
  17491. var UT = UE.UETable,
  17492. getTableItemsByRange = function (editor) {
  17493. return UT.getTableItemsByRange(editor);
  17494. },
  17495. getUETableBySelected = function (editor) {
  17496. return UT.getUETableBySelected(editor)
  17497. },
  17498. getDefaultValue = function (editor, table) {
  17499. return UT.getDefaultValue(editor, table);
  17500. },
  17501. getUETable = function (tdOrTable) {
  17502. return UT.getUETable(tdOrTable);
  17503. };
  17504. UE.commands['inserttable'] = {
  17505. queryCommandState: function () {
  17506. return getTableItemsByRange(this).table ? -1 : 0;
  17507. },
  17508. execCommand: function (cmd, opt) {
  17509. function createTable(opt, tdWidth) {
  17510. var html = [],
  17511. rowsNum = opt.numRows,
  17512. colsNum = opt.numCols;
  17513. for (var r = 0; r < rowsNum; r++) {
  17514. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17515. for (var c = 0; c < colsNum; c++) {
  17516. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17517. }
  17518. html.push('</tr>')
  17519. }
  17520. //禁止指定table-width
  17521. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17522. }
  17523. if (!opt) {
  17524. opt = utils.extend({}, {
  17525. numCols: this.options.defaultCols,
  17526. numRows: this.options.defaultRows,
  17527. tdvalign: this.options.tdvalign
  17528. })
  17529. }
  17530. var me = this;
  17531. var range = this.selection.getRange(),
  17532. start = range.startContainer,
  17533. firstParentBlock = domUtils.findParent(start, function (node) {
  17534. return domUtils.isBlockElm(node);
  17535. }, true) || me.body;
  17536. var defaultValue = getDefaultValue(me),
  17537. tableWidth = firstParentBlock.offsetWidth,
  17538. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17539. //todo其他属性
  17540. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17541. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17542. }
  17543. };
  17544. UE.commands['insertparagraphbeforetable'] = {
  17545. queryCommandState: function () {
  17546. return getTableItemsByRange(this).cell ? 0 : -1;
  17547. },
  17548. execCommand: function () {
  17549. var table = getTableItemsByRange(this).table;
  17550. if (table) {
  17551. var p = this.document.createElement("p");
  17552. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17553. table.parentNode.insertBefore(p, table);
  17554. this.selection.getRange().setStart(p, 0).setCursor();
  17555. }
  17556. }
  17557. };
  17558. UE.commands['deletetable'] = {
  17559. queryCommandState: function () {
  17560. var rng = this.selection.getRange();
  17561. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17562. },
  17563. execCommand: function (cmd, table) {
  17564. var rng = this.selection.getRange();
  17565. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17566. if (table) {
  17567. var next = table.nextSibling;
  17568. if (!next) {
  17569. next = domUtils.createElement(this.document, 'p', {
  17570. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17571. });
  17572. table.parentNode.insertBefore(next, table);
  17573. }
  17574. domUtils.remove(table);
  17575. rng = this.selection.getRange();
  17576. if (next.nodeType == 3) {
  17577. rng.setStartBefore(next)
  17578. } else {
  17579. rng.setStart(next, 0)
  17580. }
  17581. rng.setCursor(false, true)
  17582. this.fireEvent("tablehasdeleted")
  17583. }
  17584. }
  17585. };
  17586. UE.commands['cellalign'] = {
  17587. queryCommandState: function () {
  17588. return getSelectedArr(this).length ? 0 : -1
  17589. },
  17590. execCommand: function (cmd, align) {
  17591. var selectedTds = getSelectedArr(this);
  17592. if (selectedTds.length) {
  17593. for (var i = 0, ci; ci = selectedTds[i++];) {
  17594. ci.setAttribute('align', align);
  17595. }
  17596. }
  17597. }
  17598. };
  17599. UE.commands['cellvalign'] = {
  17600. queryCommandState: function () {
  17601. return getSelectedArr(this).length ? 0 : -1;
  17602. },
  17603. execCommand: function (cmd, valign) {
  17604. var selectedTds = getSelectedArr(this);
  17605. if (selectedTds.length) {
  17606. for (var i = 0, ci; ci = selectedTds[i++];) {
  17607. ci.setAttribute('vAlign', valign);
  17608. }
  17609. }
  17610. }
  17611. };
  17612. UE.commands['insertcaption'] = {
  17613. queryCommandState: function () {
  17614. var table = getTableItemsByRange(this).table;
  17615. if (table) {
  17616. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17617. }
  17618. return -1;
  17619. },
  17620. execCommand: function () {
  17621. var table = getTableItemsByRange(this).table;
  17622. if (table) {
  17623. var caption = this.document.createElement('caption');
  17624. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17625. table.insertBefore(caption, table.firstChild);
  17626. var range = this.selection.getRange();
  17627. range.setStart(caption, 0).setCursor();
  17628. }
  17629. }
  17630. };
  17631. UE.commands['deletecaption'] = {
  17632. queryCommandState: function () {
  17633. var rng = this.selection.getRange(),
  17634. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17635. if (table) {
  17636. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17637. }
  17638. return -1;
  17639. },
  17640. execCommand: function () {
  17641. var rng = this.selection.getRange(),
  17642. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17643. if (table) {
  17644. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17645. var range = this.selection.getRange();
  17646. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17647. }
  17648. }
  17649. };
  17650. UE.commands['inserttitle'] = {
  17651. queryCommandState: function () {
  17652. var table = getTableItemsByRange(this).table;
  17653. if (table) {
  17654. var firstRow = table.rows[0];
  17655. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17656. }
  17657. return -1;
  17658. },
  17659. execCommand: function () {
  17660. var table = getTableItemsByRange(this).table;
  17661. if (table) {
  17662. getUETable(table).insertRow(0, 'th');
  17663. }
  17664. var th = table.getElementsByTagName('th')[0];
  17665. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17666. }
  17667. };
  17668. UE.commands['deletetitle'] = {
  17669. queryCommandState: function () {
  17670. var table = getTableItemsByRange(this).table;
  17671. if (table) {
  17672. var firstRow = table.rows[0];
  17673. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17674. }
  17675. return -1;
  17676. },
  17677. execCommand: function () {
  17678. var table = getTableItemsByRange(this).table;
  17679. if (table) {
  17680. domUtils.remove(table.rows[0])
  17681. }
  17682. var td = table.getElementsByTagName('td')[0];
  17683. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17684. }
  17685. };
  17686. UE.commands['inserttitlecol'] = {
  17687. queryCommandState: function () {
  17688. var table = getTableItemsByRange(this).table;
  17689. if (table) {
  17690. var lastRow = table.rows[table.rows.length-1];
  17691. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17692. }
  17693. return -1;
  17694. },
  17695. execCommand: function (cmd) {
  17696. var table = getTableItemsByRange(this).table;
  17697. if (table) {
  17698. getUETable(table).insertCol(0, 'th');
  17699. }
  17700. resetTdWidth(table, this);
  17701. var th = table.getElementsByTagName('th')[0];
  17702. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17703. }
  17704. };
  17705. UE.commands['deletetitlecol'] = {
  17706. queryCommandState: function () {
  17707. var table = getTableItemsByRange(this).table;
  17708. if (table) {
  17709. var lastRow = table.rows[table.rows.length-1];
  17710. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17711. }
  17712. return -1;
  17713. },
  17714. execCommand: function () {
  17715. var table = getTableItemsByRange(this).table;
  17716. if (table) {
  17717. for(var i = 0; i< table.rows.length; i++ ){
  17718. domUtils.remove(table.rows[i].children[0])
  17719. }
  17720. }
  17721. resetTdWidth(table, this);
  17722. var td = table.getElementsByTagName('td')[0];
  17723. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17724. }
  17725. };
  17726. UE.commands["mergeright"] = {
  17727. queryCommandState: function (cmd) {
  17728. var tableItems = getTableItemsByRange(this),
  17729. table = tableItems.table,
  17730. cell = tableItems.cell;
  17731. if (!table || !cell) return -1;
  17732. var ut = getUETable(table);
  17733. if (ut.selectedTds.length) return -1;
  17734. var cellInfo = ut.getCellInfo(cell),
  17735. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17736. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17737. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17738. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17739. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17740. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17741. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17742. },
  17743. execCommand: function (cmd) {
  17744. var rng = this.selection.getRange(),
  17745. bk = rng.createBookmark(true);
  17746. var cell = getTableItemsByRange(this).cell,
  17747. ut = getUETable(cell);
  17748. ut.mergeRight(cell);
  17749. rng.moveToBookmark(bk).select();
  17750. }
  17751. };
  17752. UE.commands["mergedown"] = {
  17753. queryCommandState: function (cmd) {
  17754. var tableItems = getTableItemsByRange(this),
  17755. table = tableItems.table,
  17756. cell = tableItems.cell;
  17757. if (!table || !cell) return -1;
  17758. var ut = getUETable(table);
  17759. if (ut.selectedTds.length)return -1;
  17760. var cellInfo = ut.getCellInfo(cell),
  17761. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17762. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17763. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17764. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17765. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17766. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17767. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17768. },
  17769. execCommand: function () {
  17770. var rng = this.selection.getRange(),
  17771. bk = rng.createBookmark(true);
  17772. var cell = getTableItemsByRange(this).cell,
  17773. ut = getUETable(cell);
  17774. ut.mergeDown(cell);
  17775. rng.moveToBookmark(bk).select();
  17776. }
  17777. };
  17778. UE.commands["mergecells"] = {
  17779. queryCommandState: function () {
  17780. return getUETableBySelected(this) ? 0 : -1;
  17781. },
  17782. execCommand: function () {
  17783. var ut = getUETableBySelected(this);
  17784. if (ut && ut.selectedTds.length) {
  17785. var cell = ut.selectedTds[0];
  17786. ut.mergeRange();
  17787. var rng = this.selection.getRange();
  17788. if (domUtils.isEmptyBlock(cell)) {
  17789. rng.setStart(cell, 0).collapse(true)
  17790. } else {
  17791. rng.selectNodeContents(cell)
  17792. }
  17793. rng.select();
  17794. }
  17795. }
  17796. };
  17797. UE.commands["insertrow"] = {
  17798. queryCommandState: function () {
  17799. var tableItems = getTableItemsByRange(this),
  17800. cell = tableItems.cell;
  17801. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17802. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17803. },
  17804. execCommand: function () {
  17805. var rng = this.selection.getRange(),
  17806. bk = rng.createBookmark(true);
  17807. var tableItems = getTableItemsByRange(this),
  17808. cell = tableItems.cell,
  17809. table = tableItems.table,
  17810. ut = getUETable(table),
  17811. cellInfo = ut.getCellInfo(cell);
  17812. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17813. if (!ut.selectedTds.length) {
  17814. ut.insertRow(cellInfo.rowIndex, cell);
  17815. } else {
  17816. var range = ut.cellsRange;
  17817. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17818. ut.insertRow(range.beginRowIndex, cell);
  17819. }
  17820. }
  17821. rng.moveToBookmark(bk).select();
  17822. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17823. }
  17824. };
  17825. //后插入行
  17826. UE.commands["insertrownext"] = {
  17827. queryCommandState: function () {
  17828. var tableItems = getTableItemsByRange(this),
  17829. cell = tableItems.cell;
  17830. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17831. },
  17832. execCommand: function () {
  17833. var rng = this.selection.getRange(),
  17834. bk = rng.createBookmark(true);
  17835. var tableItems = getTableItemsByRange(this),
  17836. cell = tableItems.cell,
  17837. table = tableItems.table,
  17838. ut = getUETable(table),
  17839. cellInfo = ut.getCellInfo(cell);
  17840. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17841. if (!ut.selectedTds.length) {
  17842. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17843. } else {
  17844. var range = ut.cellsRange;
  17845. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17846. ut.insertRow(range.endRowIndex + 1, cell);
  17847. }
  17848. }
  17849. rng.moveToBookmark(bk).select();
  17850. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17851. }
  17852. };
  17853. UE.commands["deleterow"] = {
  17854. queryCommandState: function () {
  17855. var tableItems = getTableItemsByRange(this);
  17856. return tableItems.cell ? 0 : -1;
  17857. },
  17858. execCommand: function () {
  17859. var cell = getTableItemsByRange(this).cell,
  17860. ut = getUETable(cell),
  17861. cellsRange = ut.cellsRange,
  17862. cellInfo = ut.getCellInfo(cell),
  17863. preCell = ut.getVSideCell(cell),
  17864. nextCell = ut.getVSideCell(cell, true),
  17865. rng = this.selection.getRange();
  17866. if (utils.isEmptyObject(cellsRange)) {
  17867. ut.deleteRow(cellInfo.rowIndex);
  17868. } else {
  17869. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17870. ut.deleteRow(cellsRange.beginRowIndex);
  17871. }
  17872. }
  17873. var table = ut.table;
  17874. if (!table.getElementsByTagName('td').length) {
  17875. var nextSibling = table.nextSibling;
  17876. domUtils.remove(table);
  17877. if (nextSibling) {
  17878. rng.setStart(nextSibling, 0).setCursor(false, true);
  17879. }
  17880. } else {
  17881. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17882. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17883. } else {
  17884. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17885. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17886. }
  17887. }
  17888. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17889. }
  17890. };
  17891. UE.commands["insertcol"] = {
  17892. queryCommandState: function (cmd) {
  17893. var tableItems = getTableItemsByRange(this),
  17894. cell = tableItems.cell;
  17895. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17896. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17897. },
  17898. execCommand: function (cmd) {
  17899. var rng = this.selection.getRange(),
  17900. bk = rng.createBookmark(true);
  17901. if (this.queryCommandState(cmd) == -1)return;
  17902. var cell = getTableItemsByRange(this).cell,
  17903. ut = getUETable(cell),
  17904. cellInfo = ut.getCellInfo(cell);
  17905. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17906. if (!ut.selectedTds.length) {
  17907. ut.insertCol(cellInfo.colIndex, cell);
  17908. } else {
  17909. var range = ut.cellsRange;
  17910. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17911. ut.insertCol(range.beginColIndex, cell);
  17912. }
  17913. }
  17914. rng.moveToBookmark(bk).select(true);
  17915. }
  17916. };
  17917. UE.commands["insertcolnext"] = {
  17918. queryCommandState: function () {
  17919. var tableItems = getTableItemsByRange(this),
  17920. cell = tableItems.cell;
  17921. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17922. },
  17923. execCommand: function () {
  17924. var rng = this.selection.getRange(),
  17925. bk = rng.createBookmark(true);
  17926. var cell = getTableItemsByRange(this).cell,
  17927. ut = getUETable(cell),
  17928. cellInfo = ut.getCellInfo(cell);
  17929. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17930. if (!ut.selectedTds.length) {
  17931. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17932. } else {
  17933. var range = ut.cellsRange;
  17934. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17935. ut.insertCol(range.endColIndex + 1, cell);
  17936. }
  17937. }
  17938. rng.moveToBookmark(bk).select();
  17939. }
  17940. };
  17941. UE.commands["deletecol"] = {
  17942. queryCommandState: function () {
  17943. var tableItems = getTableItemsByRange(this);
  17944. return tableItems.cell ? 0 : -1;
  17945. },
  17946. execCommand: function () {
  17947. var cell = getTableItemsByRange(this).cell,
  17948. ut = getUETable(cell),
  17949. range = ut.cellsRange,
  17950. cellInfo = ut.getCellInfo(cell),
  17951. preCell = ut.getHSideCell(cell),
  17952. nextCell = ut.getHSideCell(cell, true);
  17953. if (utils.isEmptyObject(range)) {
  17954. ut.deleteCol(cellInfo.colIndex);
  17955. } else {
  17956. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17957. ut.deleteCol(range.beginColIndex);
  17958. }
  17959. }
  17960. var table = ut.table,
  17961. rng = this.selection.getRange();
  17962. if (!table.getElementsByTagName('td').length) {
  17963. var nextSibling = table.nextSibling;
  17964. domUtils.remove(table);
  17965. if (nextSibling) {
  17966. rng.setStart(nextSibling, 0).setCursor(false, true);
  17967. }
  17968. } else {
  17969. if (domUtils.inDoc(cell, this.document)) {
  17970. rng.setStart(cell, 0).setCursor(false, true);
  17971. } else {
  17972. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17973. rng.selectNodeContents(nextCell).setCursor(false, true);
  17974. } else {
  17975. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17976. rng.selectNodeContents(preCell).setCursor(true, true);
  17977. }
  17978. }
  17979. }
  17980. }
  17981. }
  17982. };
  17983. UE.commands["splittocells"] = {
  17984. queryCommandState: function () {
  17985. var tableItems = getTableItemsByRange(this),
  17986. cell = tableItems.cell;
  17987. if (!cell) return -1;
  17988. var ut = getUETable(tableItems.table);
  17989. if (ut.selectedTds.length > 0) return -1;
  17990. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17991. },
  17992. execCommand: function () {
  17993. var rng = this.selection.getRange(),
  17994. bk = rng.createBookmark(true);
  17995. var cell = getTableItemsByRange(this).cell,
  17996. ut = getUETable(cell);
  17997. ut.splitToCells(cell);
  17998. rng.moveToBookmark(bk).select();
  17999. }
  18000. };
  18001. UE.commands["splittorows"] = {
  18002. queryCommandState: function () {
  18003. var tableItems = getTableItemsByRange(this),
  18004. cell = tableItems.cell;
  18005. if (!cell) return -1;
  18006. var ut = getUETable(tableItems.table);
  18007. if (ut.selectedTds.length > 0) return -1;
  18008. return cell && cell.rowSpan > 1 ? 0 : -1;
  18009. },
  18010. execCommand: function () {
  18011. var rng = this.selection.getRange(),
  18012. bk = rng.createBookmark(true);
  18013. var cell = getTableItemsByRange(this).cell,
  18014. ut = getUETable(cell);
  18015. ut.splitToRows(cell);
  18016. rng.moveToBookmark(bk).select();
  18017. }
  18018. };
  18019. UE.commands["splittocols"] = {
  18020. queryCommandState: function () {
  18021. var tableItems = getTableItemsByRange(this),
  18022. cell = tableItems.cell;
  18023. if (!cell) return -1;
  18024. var ut = getUETable(tableItems.table);
  18025. if (ut.selectedTds.length > 0) return -1;
  18026. return cell && cell.colSpan > 1 ? 0 : -1;
  18027. },
  18028. execCommand: function () {
  18029. var rng = this.selection.getRange(),
  18030. bk = rng.createBookmark(true);
  18031. var cell = getTableItemsByRange(this).cell,
  18032. ut = getUETable(cell);
  18033. ut.splitToCols(cell);
  18034. rng.moveToBookmark(bk).select();
  18035. }
  18036. };
  18037. UE.commands["adaptbytext"] =
  18038. UE.commands["adaptbywindow"] = {
  18039. queryCommandState: function () {
  18040. return getTableItemsByRange(this).table ? 0 : -1
  18041. },
  18042. execCommand: function (cmd) {
  18043. var tableItems = getTableItemsByRange(this),
  18044. table = tableItems.table;
  18045. if (table) {
  18046. if (cmd == 'adaptbywindow') {
  18047. resetTdWidth(table, this);
  18048. } else {
  18049. var cells = domUtils.getElementsByTagName(table, "td th");
  18050. utils.each(cells, function (cell) {
  18051. cell.removeAttribute("width");
  18052. });
  18053. table.removeAttribute("width");
  18054. }
  18055. }
  18056. }
  18057. };
  18058. //平均分配各列
  18059. UE.commands['averagedistributecol'] = {
  18060. queryCommandState: function () {
  18061. var ut = getUETableBySelected(this);
  18062. if (!ut) return -1;
  18063. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18064. },
  18065. execCommand: function (cmd) {
  18066. var me = this,
  18067. ut = getUETableBySelected(me);
  18068. function getAverageWidth() {
  18069. var tb = ut.table,
  18070. averageWidth, sumWidth = 0, colsNum = 0,
  18071. tbAttr = getDefaultValue(me, tb);
  18072. if (ut.isFullRow()) {
  18073. sumWidth = tb.offsetWidth;
  18074. colsNum = ut.colsNum;
  18075. } else {
  18076. var begin = ut.cellsRange.beginColIndex,
  18077. end = ut.cellsRange.endColIndex,
  18078. node;
  18079. for (var i = begin; i <= end;) {
  18080. node = ut.selectedTds[i];
  18081. sumWidth += node.offsetWidth;
  18082. i += node.colSpan;
  18083. colsNum += 1;
  18084. }
  18085. }
  18086. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18087. return averageWidth;
  18088. }
  18089. function setAverageWidth(averageWidth) {
  18090. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18091. node.setAttribute("width", "");
  18092. });
  18093. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18094. utils.each(cells, function (node) {
  18095. if (node.colSpan == 1) {
  18096. node.setAttribute("width", averageWidth);
  18097. }
  18098. });
  18099. }
  18100. if (ut && ut.selectedTds.length) {
  18101. setAverageWidth(getAverageWidth());
  18102. }
  18103. }
  18104. };
  18105. //平均分配各行
  18106. UE.commands['averagedistributerow'] = {
  18107. queryCommandState: function () {
  18108. var ut = getUETableBySelected(this);
  18109. if (!ut) return -1;
  18110. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18111. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18112. },
  18113. execCommand: function (cmd) {
  18114. var me = this,
  18115. ut = getUETableBySelected(me);
  18116. function getAverageHeight() {
  18117. var averageHeight, rowNum, sumHeight = 0,
  18118. tb = ut.table,
  18119. tbAttr = getDefaultValue(me, tb),
  18120. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18121. if (ut.isFullCol()) {
  18122. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18123. thArr = domUtils.getElementsByTagName(tb, "th"),
  18124. captionHeight, thHeight;
  18125. if (captionArr.length > 0) {
  18126. captionHeight = captionArr[0].offsetHeight;
  18127. }
  18128. if (thArr.length > 0) {
  18129. thHeight = thArr[0].offsetHeight;
  18130. }
  18131. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18132. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18133. } else {
  18134. var begin = ut.cellsRange.beginRowIndex,
  18135. end = ut.cellsRange.endRowIndex,
  18136. count = 0,
  18137. trs = domUtils.getElementsByTagName(tb, "tr");
  18138. for (var i = begin; i <= end; i++) {
  18139. sumHeight += trs[i].offsetHeight;
  18140. count += 1;
  18141. }
  18142. rowNum = count;
  18143. }
  18144. //ie8下是混杂模式
  18145. if (browser.ie && browser.version < 9) {
  18146. averageHeight = Math.ceil(sumHeight / rowNum);
  18147. } else {
  18148. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18149. }
  18150. return averageHeight;
  18151. }
  18152. function setAverageHeight(averageHeight) {
  18153. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18154. utils.each(cells, function (node) {
  18155. if (node.rowSpan == 1) {
  18156. node.setAttribute("height", averageHeight);
  18157. }
  18158. });
  18159. }
  18160. if (ut && ut.selectedTds.length) {
  18161. setAverageHeight(getAverageHeight());
  18162. }
  18163. }
  18164. };
  18165. //单元格对齐方式
  18166. UE.commands['cellalignment'] = {
  18167. queryCommandState: function () {
  18168. return getTableItemsByRange(this).table ? 0 : -1
  18169. },
  18170. execCommand: function (cmd, data) {
  18171. var me = this,
  18172. ut = getUETableBySelected(me);
  18173. if (!ut) {
  18174. var start = me.selection.getStart(),
  18175. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18176. if (!/caption/ig.test(cell.tagName)) {
  18177. domUtils.setAttributes(cell, data);
  18178. } else {
  18179. cell.style.textAlign = data.align;
  18180. cell.style.verticalAlign = data.vAlign;
  18181. }
  18182. me.selection.getRange().setCursor(true);
  18183. } else {
  18184. utils.each(ut.selectedTds, function (cell) {
  18185. domUtils.setAttributes(cell, data);
  18186. });
  18187. }
  18188. },
  18189. /**
  18190. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18191. * @see UE.UETable.getTableCellAlignState
  18192. */
  18193. queryCommandValue: function (cmd) {
  18194. var activeMenuCell = getTableItemsByRange( this).cell;
  18195. if( !activeMenuCell ) {
  18196. activeMenuCell = getSelectedArr(this)[0];
  18197. }
  18198. if (!activeMenuCell) {
  18199. return null;
  18200. } else {
  18201. //获取同时选中的其他单元格
  18202. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18203. !cells.length && ( cells = activeMenuCell );
  18204. return UE.UETable.getTableCellAlignState(cells);
  18205. }
  18206. }
  18207. };
  18208. //表格对齐方式
  18209. UE.commands['tablealignment'] = {
  18210. queryCommandState: function () {
  18211. if (browser.ie && browser.version < 8) {
  18212. return -1;
  18213. }
  18214. return getTableItemsByRange(this).table ? 0 : -1
  18215. },
  18216. execCommand: function (cmd, value) {
  18217. var me = this,
  18218. start = me.selection.getStart(),
  18219. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18220. if (table) {
  18221. table.setAttribute("align",value);
  18222. }
  18223. }
  18224. };
  18225. //表格属性
  18226. UE.commands['edittable'] = {
  18227. queryCommandState: function () {
  18228. return getTableItemsByRange(this).table ? 0 : -1
  18229. },
  18230. execCommand: function (cmd, color) {
  18231. var rng = this.selection.getRange(),
  18232. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18233. if (table) {
  18234. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18235. domUtils.getElementsByTagName(table, "th"),
  18236. domUtils.getElementsByTagName(table, "caption")
  18237. );
  18238. utils.each(arr, function (node) {
  18239. node.style.borderColor = color;
  18240. });
  18241. }
  18242. }
  18243. };
  18244. //单元格属性
  18245. UE.commands['edittd'] = {
  18246. queryCommandState: function () {
  18247. return getTableItemsByRange(this).table ? 0 : -1
  18248. },
  18249. execCommand: function (cmd, bkColor) {
  18250. var me = this,
  18251. ut = getUETableBySelected(me);
  18252. if (!ut) {
  18253. var start = me.selection.getStart(),
  18254. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18255. if (cell) {
  18256. cell.style.backgroundColor = bkColor;
  18257. }
  18258. } else {
  18259. utils.each(ut.selectedTds, function (cell) {
  18260. cell.style.backgroundColor = bkColor;
  18261. });
  18262. }
  18263. }
  18264. };
  18265. UE.commands["settablebackground"] = {
  18266. queryCommandState: function () {
  18267. return getSelectedArr(this).length > 1 ? 0 : -1;
  18268. },
  18269. execCommand: function (cmd, value) {
  18270. var cells, ut;
  18271. cells = getSelectedArr(this);
  18272. ut = getUETable(cells[0]);
  18273. ut.setBackground(cells, value);
  18274. }
  18275. };
  18276. UE.commands["cleartablebackground"] = {
  18277. queryCommandState: function () {
  18278. var cells = getSelectedArr(this);
  18279. if (!cells.length)return -1;
  18280. for (var i = 0, cell; cell = cells[i++];) {
  18281. if (cell.style.backgroundColor !== "") return 0;
  18282. }
  18283. return -1;
  18284. },
  18285. execCommand: function () {
  18286. var cells = getSelectedArr(this),
  18287. ut = getUETable(cells[0]);
  18288. ut.removeBackground(cells);
  18289. }
  18290. };
  18291. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18292. queryCommandState: function (cmd) {
  18293. var table = getTableItemsByRange(this).table;
  18294. if (!table) return -1;
  18295. var interlaced = table.getAttribute("interlaced");
  18296. if (cmd == "interlacetable") {
  18297. //TODO 待定
  18298. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18299. return (interlaced === "enabled") ? -1 : 0;
  18300. } else {
  18301. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18302. }
  18303. },
  18304. execCommand: function (cmd, classList) {
  18305. var table = getTableItemsByRange(this).table;
  18306. if (cmd == "interlacetable") {
  18307. table.setAttribute("interlaced", "enabled");
  18308. this.fireEvent("interlacetable", table, classList);
  18309. } else {
  18310. table.setAttribute("interlaced", "disabled");
  18311. this.fireEvent("uninterlacetable", table);
  18312. }
  18313. }
  18314. };
  18315. UE.commands["setbordervisible"] = {
  18316. queryCommandState: function (cmd) {
  18317. var table = getTableItemsByRange(this).table;
  18318. if (!table) return -1;
  18319. return 0;
  18320. },
  18321. execCommand: function () {
  18322. var table = getTableItemsByRange(this).table;
  18323. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18324. td.style.borderWidth = '1px';
  18325. td.style.borderStyle = 'solid';
  18326. })
  18327. }
  18328. };
  18329. function resetTdWidth(table, editor) {
  18330. var tds = domUtils.getElementsByTagName(table,'td th');
  18331. utils.each(tds, function (td) {
  18332. td.removeAttribute("width");
  18333. });
  18334. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18335. var tdsWidths = [];
  18336. setTimeout(function () {
  18337. utils.each(tds, function (td) {
  18338. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18339. })
  18340. utils.each(tds, function (td,i) {
  18341. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18342. })
  18343. }, 0);
  18344. }
  18345. function getTableWidth(editor, needIEHack, defaultValue) {
  18346. var body = editor.body;
  18347. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18348. }
  18349. function getSelectedArr(editor) {
  18350. var cell = getTableItemsByRange(editor).cell;
  18351. if (cell) {
  18352. var ut = getUETable(cell);
  18353. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18354. } else {
  18355. return [];
  18356. }
  18357. }
  18358. })();
  18359. // plugins/table.action.js
  18360. /**
  18361. * Created with JetBrains PhpStorm.
  18362. * User: taoqili
  18363. * Date: 12-10-12
  18364. * Time: 上午10:05
  18365. * To change this template use File | Settings | File Templates.
  18366. */
  18367. UE.plugins['table'] = function () {
  18368. var me = this,
  18369. tabTimer = null,
  18370. //拖动计时器
  18371. tableDragTimer = null,
  18372. //双击计时器
  18373. tableResizeTimer = null,
  18374. //单元格最小宽度
  18375. cellMinWidth = 5,
  18376. isInResizeBuffer = false,
  18377. //单元格边框大小
  18378. cellBorderWidth = 5,
  18379. //鼠标偏移距离
  18380. offsetOfTableCell = 10,
  18381. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18382. singleClickState = 0,
  18383. userActionStatus = null,
  18384. //双击允许的时间范围
  18385. dblclickTime = 360,
  18386. UT = UE.UETable,
  18387. getUETable = function (tdOrTable) {
  18388. return UT.getUETable(tdOrTable);
  18389. },
  18390. getUETableBySelected = function (editor) {
  18391. return UT.getUETableBySelected(editor);
  18392. },
  18393. getDefaultValue = function (editor, table) {
  18394. return UT.getDefaultValue(editor, table);
  18395. },
  18396. removeSelectedClass = function (cells) {
  18397. return UT.removeSelectedClass(cells);
  18398. };
  18399. function showError(e) {
  18400. // throw e;
  18401. }
  18402. me.ready(function(){
  18403. var me = this;
  18404. var orgGetText = me.selection.getText;
  18405. me.selection.getText = function(){
  18406. var table = getUETableBySelected(me);
  18407. if(table){
  18408. var str = '';
  18409. utils.each(table.selectedTds,function(td){
  18410. str += td[browser.ie?'innerText':'textContent'];
  18411. })
  18412. return str;
  18413. }else{
  18414. return orgGetText.call(me.selection)
  18415. }
  18416. }
  18417. })
  18418. //处理拖动及框选相关方法
  18419. var startTd = null, //鼠标按下时的锚点td
  18420. currentTd = null, //当前鼠标经过时的td
  18421. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18422. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18423. dragButton = null,
  18424. dragOver = false,
  18425. dragLine = null, //模拟的拖动线
  18426. dragTd = null; //发生拖动的目标td
  18427. var mousedown = false,
  18428. //todo 判断混乱模式
  18429. needIEHack = true;
  18430. me.setOpt({
  18431. 'maxColNum':20,
  18432. 'maxRowNum':100,
  18433. 'defaultCols':5,
  18434. 'defaultRows':5,
  18435. 'tdvalign':'top',
  18436. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18437. 'tableDragable':false,
  18438. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18439. });
  18440. me.getUETable = getUETable;
  18441. var commands = {
  18442. 'deletetable':1,
  18443. 'inserttable':1,
  18444. 'cellvalign':1,
  18445. 'insertcaption':1,
  18446. 'deletecaption':1,
  18447. 'inserttitle':1,
  18448. 'deletetitle':1,
  18449. "mergeright":1,
  18450. "mergedown":1,
  18451. "mergecells":1,
  18452. "insertrow":1,
  18453. "insertrownext":1,
  18454. "deleterow":1,
  18455. "insertcol":1,
  18456. "insertcolnext":1,
  18457. "deletecol":1,
  18458. "splittocells":1,
  18459. "splittorows":1,
  18460. "splittocols":1,
  18461. "adaptbytext":1,
  18462. "adaptbywindow":1,
  18463. "adaptbycustomer":1,
  18464. "insertparagraph":1,
  18465. "insertparagraphbeforetable":1,
  18466. "averagedistributecol":1,
  18467. "averagedistributerow":1
  18468. };
  18469. me.ready(function () {
  18470. utils.cssRule('table',
  18471. //选中的td上的样式
  18472. '.selectTdClass{background-color:#edf5fa !important}' +
  18473. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18474. //插入的表格的默认样式
  18475. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18476. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18477. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18478. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18479. 'table tr.firstRow th{border-top-width:2px;}' +
  18480. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18481. 'td p{margin:0;padding:0;}', me.document);
  18482. var tableCopyList, isFullCol, isFullRow;
  18483. //注册del/backspace事件
  18484. me.addListener('keydown', function (cmd, evt) {
  18485. var me = this;
  18486. var keyCode = evt.keyCode || evt.which;
  18487. if (keyCode == 8) {
  18488. var ut = getUETableBySelected(me);
  18489. if (ut && ut.selectedTds.length) {
  18490. if (ut.isFullCol()) {
  18491. me.execCommand('deletecol')
  18492. } else if (ut.isFullRow()) {
  18493. me.execCommand('deleterow')
  18494. } else {
  18495. me.fireEvent('delcells');
  18496. }
  18497. domUtils.preventDefault(evt);
  18498. }
  18499. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18500. range = me.selection.getRange();
  18501. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18502. me.fireEvent('saveScene');
  18503. var table = caption.parentNode;
  18504. domUtils.remove(caption);
  18505. if (table) {
  18506. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18507. }
  18508. me.fireEvent('saveScene');
  18509. }
  18510. }
  18511. if (keyCode == 46) {
  18512. ut = getUETableBySelected(me);
  18513. if (ut) {
  18514. me.fireEvent('saveScene');
  18515. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18516. domUtils.fillNode(me.document, ci)
  18517. }
  18518. me.fireEvent('saveScene');
  18519. domUtils.preventDefault(evt);
  18520. }
  18521. }
  18522. if (keyCode == 13) {
  18523. var rng = me.selection.getRange(),
  18524. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18525. if (caption) {
  18526. var table = domUtils.findParentByTagName(caption, 'table');
  18527. if (!rng.collapsed) {
  18528. rng.deleteContents();
  18529. me.fireEvent('saveScene');
  18530. } else {
  18531. if (caption) {
  18532. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18533. }
  18534. }
  18535. domUtils.preventDefault(evt);
  18536. return;
  18537. }
  18538. if (rng.collapsed) {
  18539. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18540. if (table) {
  18541. var cell = table.rows[0].cells[0],
  18542. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18543. preNode = table.previousSibling;
  18544. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18545. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18546. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18547. me.execCommand('insertparagraphbeforetable');
  18548. domUtils.preventDefault(evt);
  18549. }
  18550. }
  18551. }
  18552. }
  18553. }
  18554. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18555. tableCopyList = null;
  18556. var ut = getUETableBySelected(me);
  18557. if (ut) {
  18558. var tds = ut.selectedTds;
  18559. isFullCol = ut.isFullCol();
  18560. isFullRow = ut.isFullRow();
  18561. tableCopyList = [
  18562. [ut.cloneCell(tds[0],null,true)]
  18563. ];
  18564. for (var i = 1, ci; ci = tds[i]; i++) {
  18565. if (ci.parentNode !== tds[i - 1].parentNode) {
  18566. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18567. } else {
  18568. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18569. }
  18570. }
  18571. }
  18572. }
  18573. });
  18574. me.addListener("tablehasdeleted",function(){
  18575. toggleDraggableState(this, false, "", null);
  18576. if (dragButton)domUtils.remove(dragButton);
  18577. });
  18578. me.addListener('beforepaste', function (cmd, html) {
  18579. var me = this;
  18580. var rng = me.selection.getRange();
  18581. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18582. var div = me.document.createElement("div");
  18583. div.innerHTML = html.html;
  18584. //trace:3729
  18585. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18586. return;
  18587. }
  18588. var table = getUETableBySelected(me);
  18589. if (tableCopyList) {
  18590. me.fireEvent('saveScene');
  18591. var rng = me.selection.getRange();
  18592. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18593. if (td) {
  18594. var ut = getUETable(td);
  18595. if (isFullRow) {
  18596. var rowIndex = ut.getCellInfo(td).rowIndex;
  18597. if (td.tagName == 'TH') {
  18598. rowIndex++;
  18599. }
  18600. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18601. var tr = ut.insertRow(rowIndex++, "td");
  18602. for (var j = 0, cj; cj = ci[j]; j++) {
  18603. var cell = tr.cells[j];
  18604. if (!cell) {
  18605. cell = tr.insertCell(j)
  18606. }
  18607. cell.innerHTML = cj.innerHTML;
  18608. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18609. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18610. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18611. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18612. }
  18613. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18614. if (!ci[j])
  18615. break;
  18616. cj.innerHTML = ci[j].innerHTML;
  18617. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18618. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18619. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18620. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18621. }
  18622. }
  18623. } else {
  18624. if (isFullCol) {
  18625. cellInfo = ut.getCellInfo(td);
  18626. var maxColNum = 0;
  18627. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18628. maxColNum += cj.colSpan || 1;
  18629. }
  18630. me.__hasEnterExecCommand = true;
  18631. for (i = 0; i < maxColNum; i++) {
  18632. me.execCommand('insertcol');
  18633. }
  18634. me.__hasEnterExecCommand = false;
  18635. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18636. if (td.tagName == 'TH') {
  18637. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18638. }
  18639. }
  18640. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18641. tmpNode = td;
  18642. for (var j = 0, cj; cj = ci[j++];) {
  18643. if (td) {
  18644. td.innerHTML = cj.innerHTML;
  18645. //todo 定制处理
  18646. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18647. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18648. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18649. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18650. preNode = td;
  18651. td = td.nextSibling;
  18652. } else {
  18653. var cloneTd = cj.cloneNode(true);
  18654. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18655. preNode.parentNode.appendChild(cloneTd)
  18656. }
  18657. }
  18658. td = ut.getNextCell(tmpNode, true, true);
  18659. if (!tableCopyList[i])
  18660. break;
  18661. if (!td) {
  18662. var cellInfo = ut.getCellInfo(tmpNode);
  18663. ut.table.insertRow(ut.table.rows.length);
  18664. ut.update();
  18665. td = ut.getVSideCell(tmpNode, true);
  18666. }
  18667. }
  18668. }
  18669. ut.update();
  18670. } else {
  18671. table = me.document.createElement('table');
  18672. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18673. var tr = table.insertRow(table.rows.length);
  18674. for (var j = 0, cj; cj = ci[j++];) {
  18675. cloneTd = UT.cloneCell(cj,null,true);
  18676. domUtils.removeAttributes(cloneTd, ['class']);
  18677. tr.appendChild(cloneTd)
  18678. }
  18679. if (j == 2 && cloneTd.rowSpan > 1) {
  18680. cloneTd.rowSpan = 1;
  18681. }
  18682. }
  18683. var defaultValue = getDefaultValue(me),
  18684. width = me.body.offsetWidth -
  18685. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18686. me.execCommand('insertHTML', '<table ' +
  18687. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18688. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18689. }
  18690. me.fireEvent('contentchange');
  18691. me.fireEvent('saveScene');
  18692. html.html = '';
  18693. return true;
  18694. } else {
  18695. var div = me.document.createElement("div"), tables;
  18696. div.innerHTML = html.html;
  18697. tables = div.getElementsByTagName("table");
  18698. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18699. utils.each(tables, function (t) {
  18700. domUtils.remove(t)
  18701. });
  18702. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18703. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18704. }
  18705. } else {
  18706. utils.each(tables, function (table) {
  18707. removeStyleSize(table, true);
  18708. domUtils.removeAttributes(table, ['style', 'border']);
  18709. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18710. if (isEmptyBlock(td)) {
  18711. domUtils.fillNode(me.document, td);
  18712. }
  18713. removeStyleSize(td, true);
  18714. // domUtils.removeAttributes(td, ['style'])
  18715. });
  18716. });
  18717. }
  18718. html.html = div.innerHTML;
  18719. }
  18720. });
  18721. me.addListener('afterpaste', function () {
  18722. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18723. if (table.offsetWidth > me.body.offsetWidth) {
  18724. var defaultValue = getDefaultValue(me, table);
  18725. 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'
  18726. }
  18727. })
  18728. });
  18729. me.addListener('blur', function () {
  18730. tableCopyList = null;
  18731. });
  18732. var timer;
  18733. me.addListener('keydown', function () {
  18734. clearTimeout(timer);
  18735. timer = setTimeout(function () {
  18736. var rng = me.selection.getRange(),
  18737. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18738. if (cell) {
  18739. var table = cell.parentNode.parentNode.parentNode;
  18740. if (table.offsetWidth > table.getAttribute("width")) {
  18741. cell.style.wordBreak = "break-all";
  18742. }
  18743. }
  18744. }, 100);
  18745. });
  18746. me.addListener("selectionchange", function () {
  18747. toggleDraggableState(me, false, "", null);
  18748. });
  18749. //内容变化时触发索引更新
  18750. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18751. me.addListener("contentchange", function () {
  18752. var me = this;
  18753. //尽可能排除一些不需要更新的状况
  18754. hideDragLine(me);
  18755. if (getUETableBySelected(me))return;
  18756. var rng = me.selection.getRange();
  18757. var start = rng.startContainer;
  18758. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18759. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18760. if (me.fireEvent("excludetable", table) === true) return;
  18761. table.ueTable = new UT(table);
  18762. //trace:3742
  18763. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18764. //
  18765. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18766. // domUtils.fillNode(me.document, td);
  18767. // if (browser.ie && browser.version == 6) {
  18768. // td.innerHTML = '&nbsp;'
  18769. // }
  18770. // }
  18771. // });
  18772. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18773. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18774. // domUtils.fillNode(me.document, th);
  18775. // if (browser.ie && browser.version == 6) {
  18776. // th.innerHTML = '&nbsp;'
  18777. // }
  18778. // }
  18779. // });
  18780. table.onmouseover = function () {
  18781. me.fireEvent('tablemouseover', table);
  18782. };
  18783. table.onmousemove = function () {
  18784. me.fireEvent('tablemousemove', table);
  18785. me.options.tableDragable && toggleDragButton(true, this, me);
  18786. utils.defer(function(){
  18787. me.fireEvent('contentchange',50)
  18788. },true)
  18789. };
  18790. table.onmouseout = function () {
  18791. me.fireEvent('tablemouseout', table);
  18792. toggleDraggableState(me, false, "", null);
  18793. hideDragLine(me);
  18794. };
  18795. table.onclick = function (evt) {
  18796. evt = me.window.event || evt;
  18797. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18798. if (!target)return;
  18799. var ut = getUETable(target),
  18800. table = ut.table,
  18801. cellInfo = ut.getCellInfo(target),
  18802. cellsRange,
  18803. rng = me.selection.getRange();
  18804. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18805. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18806. // ut.setSelected(cellsRange);
  18807. // return;
  18808. // }
  18809. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18810. //
  18811. // return;
  18812. // }
  18813. if (inTableSide(table, target, evt, true)) {
  18814. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18815. if (evt.shiftKey && ut.selectedTds.length) {
  18816. if (ut.selectedTds[0] !== endTdCol) {
  18817. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18818. ut.setSelected(cellsRange);
  18819. } else {
  18820. rng && rng.selectNodeContents(endTdCol).select();
  18821. }
  18822. } else {
  18823. if (target !== endTdCol) {
  18824. cellsRange = ut.getCellsRange(target, endTdCol);
  18825. ut.setSelected(cellsRange);
  18826. } else {
  18827. rng && rng.selectNodeContents(endTdCol).select();
  18828. }
  18829. }
  18830. return;
  18831. }
  18832. if (inTableSide(table, target, evt)) {
  18833. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18834. if (evt.shiftKey && ut.selectedTds.length) {
  18835. if (ut.selectedTds[0] !== endTdRow) {
  18836. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18837. ut.setSelected(cellsRange);
  18838. } else {
  18839. rng && rng.selectNodeContents(endTdRow).select();
  18840. }
  18841. } else {
  18842. if (target !== endTdRow) {
  18843. cellsRange = ut.getCellsRange(target, endTdRow);
  18844. ut.setSelected(cellsRange);
  18845. } else {
  18846. rng && rng.selectNodeContents(endTdRow).select();
  18847. }
  18848. }
  18849. }
  18850. };
  18851. });
  18852. switchBorderColor(me, true);
  18853. });
  18854. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18855. domUtils.on(me.document, "mouseout", function (evt) {
  18856. var target = evt.target || evt.srcElement;
  18857. if (target.tagName == "TABLE") {
  18858. toggleDraggableState(me, false, "", null);
  18859. }
  18860. });
  18861. /**
  18862. * 表格隔行变色
  18863. */
  18864. me.addListener("interlacetable",function(type,table,classList){
  18865. if(!table) return;
  18866. var me = this,
  18867. rows = table.rows,
  18868. len = rows.length,
  18869. getClass = function(list,index,repeat){
  18870. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18871. };
  18872. for(var i = 0;i<len;i++){
  18873. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18874. }
  18875. });
  18876. me.addListener("uninterlacetable",function(type,table){
  18877. if(!table) return;
  18878. var me = this,
  18879. rows = table.rows,
  18880. classList = me.options.classList,
  18881. len = rows.length;
  18882. for(var i = 0;i<len;i++){
  18883. domUtils.removeClasses( rows[i], classList );
  18884. }
  18885. });
  18886. me.addListener("mousedown", mouseDownEvent);
  18887. me.addListener("mouseup", mouseUpEvent);
  18888. //拖动的时候触发mouseup
  18889. domUtils.on( me.body, 'dragstart', function( evt ){
  18890. mouseUpEvent.call( me, 'dragstart', evt );
  18891. });
  18892. me.addOutputRule(function(root){
  18893. utils.each(root.getNodesByTagName('div'),function(n){
  18894. if (n.getAttr('id') == 'ue_tableDragLine') {
  18895. n.parentNode.removeChild(n);
  18896. }
  18897. });
  18898. });
  18899. var currentRowIndex = 0;
  18900. me.addListener("mousedown", function () {
  18901. currentRowIndex = 0;
  18902. });
  18903. me.addListener('tabkeydown', function () {
  18904. var range = this.selection.getRange(),
  18905. common = range.getCommonAncestor(true, true),
  18906. table = domUtils.findParentByTagName(common, 'table');
  18907. if (table) {
  18908. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18909. var cell = domUtils.getElementsByTagName(table, 'th td');
  18910. if (cell && cell.length) {
  18911. range.setStart(cell[0], 0).setCursor(false, true)
  18912. }
  18913. } else {
  18914. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18915. ua = getUETable(cell);
  18916. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18917. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18918. if (nextCell) {
  18919. if (isEmptyBlock(nextCell)) {
  18920. range.setStart(nextCell, 0).setCursor(false, true)
  18921. } else {
  18922. range.selectNodeContents(nextCell).select()
  18923. }
  18924. } else {
  18925. me.fireEvent('saveScene');
  18926. me.__hasEnterExecCommand = true;
  18927. this.execCommand('insertrownext');
  18928. me.__hasEnterExecCommand = false;
  18929. range = this.selection.getRange();
  18930. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18931. me.fireEvent('saveScene');
  18932. }
  18933. }
  18934. return true;
  18935. }
  18936. });
  18937. browser.ie && me.addListener('selectionchange', function () {
  18938. toggleDraggableState(this, false, "", null);
  18939. });
  18940. me.addListener("keydown", function (type, evt) {
  18941. var me = this;
  18942. //处理在表格的最后一个输入tab产生新的表格
  18943. var keyCode = evt.keyCode || evt.which;
  18944. if (keyCode == 8 || keyCode == 46) {
  18945. return;
  18946. }
  18947. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18948. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18949. var ut = getUETableBySelected(me);
  18950. if (!ut) return;
  18951. notCtrlKey && ut.clearSelected();
  18952. });
  18953. me.addListener("beforegetcontent", function () {
  18954. switchBorderColor(this, false);
  18955. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18956. if (domUtils.isEmptyNode(ci)) {
  18957. ci.innerHTML = '&nbsp;'
  18958. }
  18959. });
  18960. });
  18961. me.addListener("aftergetcontent", function () {
  18962. switchBorderColor(this, true);
  18963. });
  18964. me.addListener("getAllHtml", function () {
  18965. removeSelectedClass(me.document.getElementsByTagName("td"));
  18966. });
  18967. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18968. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18969. if (!fullscreen) {
  18970. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18971. tables = domUtils.getElementsByTagName(this.body, "table");
  18972. utils.each(tables, function (table) {
  18973. if (table.offsetWidth < me.body.offsetWidth) return false;
  18974. var tds = domUtils.getElementsByTagName(table, "td"),
  18975. backWidths = [];
  18976. utils.each(tds, function (td) {
  18977. backWidths.push(td.offsetWidth);
  18978. });
  18979. for (var i = 0, td; td = tds[i]; i++) {
  18980. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18981. }
  18982. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18983. });
  18984. }
  18985. });
  18986. //重写execCommand命令,用于处理框选时的处理
  18987. var oldExecCommand = me.execCommand;
  18988. me.execCommand = function (cmd, datatat) {
  18989. var me = this,
  18990. args = arguments;
  18991. cmd = cmd.toLowerCase();
  18992. var ut = getUETableBySelected(me), tds,
  18993. range = new dom.Range(me.document),
  18994. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18995. result;
  18996. if (!cmdFun) return;
  18997. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18998. me.__hasEnterExecCommand = true;
  18999. me.fireEvent("beforeexeccommand", cmd);
  19000. tds = ut.selectedTds;
  19001. var lastState = -2, lastValue = -2, value, state;
  19002. for (var i = 0, td; td = tds[i]; i++) {
  19003. if (isEmptyBlock(td)) {
  19004. range.setStart(td, 0).setCursor(false, true)
  19005. } else {
  19006. range.selectNode(td).select(true);
  19007. }
  19008. state = me.queryCommandState(cmd);
  19009. value = me.queryCommandValue(cmd);
  19010. if (state != -1) {
  19011. if (lastState !== state || lastValue !== value) {
  19012. me._ignoreContentChange = true;
  19013. result = oldExecCommand.apply(me, arguments);
  19014. me._ignoreContentChange = false;
  19015. }
  19016. lastState = me.queryCommandState(cmd);
  19017. lastValue = me.queryCommandValue(cmd);
  19018. if (domUtils.isEmptyBlock(td)) {
  19019. domUtils.fillNode(me.document, td)
  19020. }
  19021. }
  19022. }
  19023. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19024. me.fireEvent('contentchange');
  19025. me.fireEvent("afterexeccommand", cmd);
  19026. me.__hasEnterExecCommand = false;
  19027. me._selectionChange();
  19028. } else {
  19029. result = oldExecCommand.apply(me, arguments);
  19030. }
  19031. return result;
  19032. };
  19033. });
  19034. /**
  19035. * 删除obj的宽高style,改成属性宽高
  19036. * @param obj
  19037. * @param replaceToProperty
  19038. */
  19039. function removeStyleSize(obj, replaceToProperty) {
  19040. removeStyle(obj, "width", true);
  19041. removeStyle(obj, "height", true);
  19042. }
  19043. function removeStyle(obj, styleName, replaceToProperty) {
  19044. if (obj.style[styleName]) {
  19045. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19046. obj.style[styleName] = "";
  19047. }
  19048. }
  19049. function getParentTdOrTh(ele) {
  19050. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19051. var td;
  19052. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19053. return null;
  19054. }
  19055. function isEmptyBlock(node) {
  19056. var reg = new RegExp(domUtils.fillChar, 'g');
  19057. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19058. return 0;
  19059. }
  19060. for (var n in dtd.$isNotEmpty) {
  19061. if (node.getElementsByTagName(n).length) {
  19062. return 0;
  19063. }
  19064. }
  19065. return 1;
  19066. }
  19067. function mouseCoords(evt) {
  19068. if (evt.pageX || evt.pageY) {
  19069. return { x:evt.pageX, y:evt.pageY };
  19070. }
  19071. return {
  19072. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19073. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19074. };
  19075. }
  19076. function mouseMoveEvent(evt) {
  19077. if( isEditorDisabled() ) {
  19078. return;
  19079. }
  19080. try {
  19081. //普通状态下鼠标移动
  19082. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19083. pos;
  19084. //区分用户的行为是拖动还是双击
  19085. if( isInResizeBuffer ) {
  19086. me.body.style.webkitUserSelect = 'none';
  19087. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19088. clearTableDragTimer();
  19089. isInResizeBuffer = false;
  19090. singleClickState = 0;
  19091. //drag action
  19092. tableBorderDrag(evt);
  19093. }
  19094. }
  19095. //修改单元格大小时的鼠标移动
  19096. if (onDrag && dragTd) {
  19097. singleClickState = 0;
  19098. me.body.style.webkitUserSelect = 'none';
  19099. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19100. pos = mouseCoords(evt);
  19101. toggleDraggableState(me, true, onDrag, pos, target);
  19102. if (onDrag == "h") {
  19103. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19104. } else if (onDrag == "v") {
  19105. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19106. }
  19107. return;
  19108. }
  19109. //当鼠标处于table上时,修改移动过程中的光标状态
  19110. if (target) {
  19111. //针对使用table作为容器的组件不触发拖拽效果
  19112. if (me.fireEvent('excludetable', target) === true)
  19113. return;
  19114. pos = mouseCoords(evt);
  19115. var state = getRelation(target, pos),
  19116. table = domUtils.findParentByTagName(target, "table", true);
  19117. if (inTableSide(table, target, evt, true)) {
  19118. if (me.fireEvent("excludetable", table) === true) return;
  19119. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19120. } else if (inTableSide(table, target, evt)) {
  19121. if (me.fireEvent("excludetable", table) === true) return;
  19122. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19123. } else {
  19124. me.body.style.cursor = "text";
  19125. var curCell = target;
  19126. if (/\d/.test(state)) {
  19127. state = state.replace(/\d/, '');
  19128. target = getUETable(target).getPreviewCell(target, state == "v");
  19129. }
  19130. //位于第一行的顶部或者第一列的左边时不可拖动
  19131. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19132. }
  19133. } else {
  19134. toggleDragButton(false, table, me);
  19135. }
  19136. } catch (e) {
  19137. showError(e);
  19138. }
  19139. }
  19140. var dragButtonTimer;
  19141. function toggleDragButton(show, table, editor) {
  19142. if (!show) {
  19143. if (dragOver)return;
  19144. dragButtonTimer = setTimeout(function () {
  19145. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19146. }, 2000);
  19147. } else {
  19148. createDragButton(table, editor);
  19149. }
  19150. }
  19151. function createDragButton(table, editor) {
  19152. var pos = domUtils.getXY(table),
  19153. doc = table.ownerDocument;
  19154. if (dragButton && dragButton.parentNode)return dragButton;
  19155. dragButton = doc.createElement("div");
  19156. dragButton.contentEditable = false;
  19157. dragButton.innerHTML = "";
  19158. 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;";
  19159. domUtils.unSelectable(dragButton);
  19160. dragButton.onmouseover = function (evt) {
  19161. dragOver = true;
  19162. };
  19163. dragButton.onmouseout = function (evt) {
  19164. dragOver = false;
  19165. };
  19166. domUtils.on(dragButton, 'click', function (type, evt) {
  19167. doClick(evt, this);
  19168. });
  19169. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19170. doDblClick(evt);
  19171. });
  19172. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19173. domUtils.preventDefault(evt);
  19174. });
  19175. var timer;
  19176. function doClick(evt, button) {
  19177. // 部分浏览器下需要清理
  19178. clearTimeout(timer);
  19179. timer = setTimeout(function () {
  19180. editor.fireEvent("tableClicked", table, button);
  19181. }, 300);
  19182. }
  19183. function doDblClick(evt) {
  19184. clearTimeout(timer);
  19185. var ut = getUETable(table),
  19186. start = table.rows[0].cells[0],
  19187. end = ut.getLastCell(),
  19188. range = ut.getCellsRange(start, end);
  19189. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19190. ut.setSelected(range);
  19191. }
  19192. doc.body.appendChild(dragButton);
  19193. }
  19194. // function inPosition(table, pos) {
  19195. // var tablePos = domUtils.getXY(table),
  19196. // width = table.offsetWidth,
  19197. // height = table.offsetHeight;
  19198. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19199. // return "topLeft";
  19200. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19201. // return "bottomRight";
  19202. // }
  19203. // }
  19204. function inTableSide(table, cell, evt, top) {
  19205. var pos = mouseCoords(evt),
  19206. state = getRelation(cell, pos);
  19207. if (top) {
  19208. var caption = table.getElementsByTagName("caption")[0],
  19209. capHeight = caption ? caption.offsetHeight : 0;
  19210. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19211. } else {
  19212. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19213. }
  19214. }
  19215. /**
  19216. * 获取拖动时允许的X轴坐标
  19217. * @param dragTd
  19218. * @param evt
  19219. */
  19220. function getPermissionX(dragTd, evt) {
  19221. var ut = getUETable(dragTd);
  19222. if (ut) {
  19223. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19224. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19225. mouseX = mouseCoords(evt).x,
  19226. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19227. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19228. left += cellMinWidth;
  19229. right -= cellMinWidth;
  19230. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19231. }
  19232. }
  19233. /**
  19234. * 获取拖动时允许的Y轴坐标
  19235. */
  19236. function getPermissionY(dragTd, evt) {
  19237. try {
  19238. var top = domUtils.getXY(dragTd).y,
  19239. mousePosY = mouseCoords(evt).y;
  19240. return mousePosY < top ? top : mousePosY;
  19241. } catch (e) {
  19242. showError(e);
  19243. }
  19244. }
  19245. /**
  19246. * 移动状态切换
  19247. */
  19248. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19249. try {
  19250. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19251. if (browser.ie) {
  19252. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19253. getDragLine(editor, editor.document);
  19254. showDragLineAt(dir, cell);
  19255. } else {
  19256. hideDragLine(editor)
  19257. }
  19258. }
  19259. onBorder = draggable;
  19260. } catch (e) {
  19261. showError(e);
  19262. }
  19263. }
  19264. /**
  19265. * 获取与UETable相关的resize line
  19266. * @param uetable UETable对象
  19267. */
  19268. function getResizeLineByUETable() {
  19269. var lineId = '_UETableResizeLine',
  19270. line = this.document.getElementById( lineId );
  19271. if( !line ) {
  19272. line = this.document.createElement("div");
  19273. line.id = lineId;
  19274. line.contnetEditable = false;
  19275. line.setAttribute("unselectable", "on");
  19276. var styles = {
  19277. width: 2*cellBorderWidth + 1 + 'px',
  19278. position: 'absolute',
  19279. 'z-index': 100000,
  19280. cursor: 'col-resize',
  19281. background: 'red',
  19282. display: 'none'
  19283. };
  19284. //切换状态
  19285. line.onmouseout = function(){
  19286. this.style.display = 'none';
  19287. };
  19288. utils.extend( line.style, styles );
  19289. this.document.body.appendChild( line );
  19290. }
  19291. return line;
  19292. }
  19293. /**
  19294. * 更新resize-line
  19295. */
  19296. function updateResizeLine( cell, uetable ) {
  19297. var line = getResizeLineByUETable.call( this ),
  19298. table = uetable.table,
  19299. styles = {
  19300. top: domUtils.getXY( table ).y + 'px',
  19301. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19302. display: 'block',
  19303. height: table.offsetHeight + 'px'
  19304. };
  19305. utils.extend( line.style, styles );
  19306. }
  19307. /**
  19308. * 显示resize-line
  19309. */
  19310. function showResizeLine( cell ) {
  19311. var uetable = getUETable( cell );
  19312. updateResizeLine.call( this, cell, uetable );
  19313. }
  19314. /**
  19315. * 获取鼠标与当前单元格的相对位置
  19316. * @param ele
  19317. * @param mousePos
  19318. */
  19319. function getRelation(ele, mousePos) {
  19320. var elePos = domUtils.getXY(ele);
  19321. if( !elePos ) {
  19322. return '';
  19323. }
  19324. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19325. return "h";
  19326. }
  19327. if (mousePos.x - elePos.x < cellBorderWidth) {
  19328. return 'h1'
  19329. }
  19330. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19331. return "v";
  19332. }
  19333. if (mousePos.y - elePos.y < cellBorderWidth) {
  19334. return 'v1'
  19335. }
  19336. return '';
  19337. }
  19338. function mouseDownEvent(type, evt) {
  19339. if( isEditorDisabled() ) {
  19340. return ;
  19341. }
  19342. userActionStatus = {
  19343. x: evt.clientX,
  19344. y: evt.clientY
  19345. };
  19346. //右键菜单单独处理
  19347. if (evt.button == 2) {
  19348. var ut = getUETableBySelected(me),
  19349. flag = false;
  19350. if (ut) {
  19351. var td = getTargetTd(me, evt);
  19352. utils.each(ut.selectedTds, function (ti) {
  19353. if (ti === td) {
  19354. flag = true;
  19355. }
  19356. });
  19357. if (!flag) {
  19358. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19359. ut.clearSelected()
  19360. } else {
  19361. td = ut.selectedTds[0];
  19362. setTimeout(function () {
  19363. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19364. }, 0);
  19365. }
  19366. }
  19367. } else {
  19368. tableClickHander( evt );
  19369. }
  19370. }
  19371. //清除表格的计时器
  19372. function clearTableTimer() {
  19373. tabTimer && clearTimeout( tabTimer );
  19374. tabTimer = null;
  19375. }
  19376. //双击收缩
  19377. function tableDbclickHandler(evt) {
  19378. singleClickState = 0;
  19379. evt = evt || me.window.event;
  19380. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19381. if (target) {
  19382. var h;
  19383. if (h = getRelation(target, mouseCoords(evt))) {
  19384. hideDragLine( me );
  19385. if (h == 'h1') {
  19386. h = 'h';
  19387. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19388. me.execCommand('adaptbywindow');
  19389. } else {
  19390. target = getUETable(target).getPreviewCell(target);
  19391. if (target) {
  19392. var rng = me.selection.getRange();
  19393. rng.selectNodeContents(target).setCursor(true, true)
  19394. }
  19395. }
  19396. }
  19397. if (h == 'h') {
  19398. var ut = getUETable(target),
  19399. table = ut.table,
  19400. cells = getCellsByMoveBorder( target, table, true );
  19401. cells = extractArray( cells, 'left' );
  19402. ut.width = ut.offsetWidth;
  19403. var oldWidth = [],
  19404. newWidth = [];
  19405. utils.each( cells, function( cell ){
  19406. oldWidth.push( cell.offsetWidth );
  19407. } );
  19408. utils.each( cells, function( cell ){
  19409. cell.removeAttribute("width");
  19410. } );
  19411. window.setTimeout( function(){
  19412. //是否允许改变
  19413. var changeable = true;
  19414. utils.each( cells, function( cell, index ){
  19415. var width = cell.offsetWidth;
  19416. if( width > oldWidth[index] ) {
  19417. changeable = false;
  19418. return false;
  19419. }
  19420. newWidth.push( width );
  19421. } );
  19422. var change = changeable ? newWidth : oldWidth;
  19423. utils.each( cells, function( cell, index ){
  19424. cell.width = change[index] - getTabcellSpace();
  19425. } );
  19426. }, 0 );
  19427. // minWidth -= cellMinWidth;
  19428. //
  19429. // table.removeAttribute("width");
  19430. // utils.each(cells, function (cell) {
  19431. // cell.style.width = "";
  19432. // cell.width -= minWidth;
  19433. // });
  19434. }
  19435. }
  19436. }
  19437. }
  19438. function tableClickHander( evt ) {
  19439. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19440. //trace:3113
  19441. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19442. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19443. t.ueTable = null;
  19444. });
  19445. startTd = getTargetTd(me, evt);
  19446. if( !startTd ) return;
  19447. var table = domUtils.findParentByTagName(startTd, "table", true);
  19448. ut = getUETable(table);
  19449. ut && ut.clearSelected();
  19450. //判断当前鼠标状态
  19451. if (!onBorder) {
  19452. me.document.body.style.webkitUserSelect = '';
  19453. mousedown = true;
  19454. me.addListener('mouseover', mouseOverEvent);
  19455. } else {
  19456. //边框上的动作处理
  19457. borderActionHandler( evt );
  19458. }
  19459. }
  19460. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19461. function borderActionHandler( evt ) {
  19462. if ( browser.ie ) {
  19463. evt = reconstruct(evt );
  19464. }
  19465. clearTableDragTimer();
  19466. //是否正在等待resize的缓冲中
  19467. isInResizeBuffer = true;
  19468. tableDragTimer = setTimeout(function(){
  19469. tableBorderDrag( evt );
  19470. }, dblclickTime);
  19471. }
  19472. function extractArray( originArr, key ) {
  19473. var result = [],
  19474. tmp = null;
  19475. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19476. tmp = originArr[ i ][ key ];
  19477. if( tmp ) {
  19478. result.push( tmp );
  19479. }
  19480. }
  19481. return result;
  19482. }
  19483. function clearTableDragTimer() {
  19484. tableDragTimer && clearTimeout(tableDragTimer);
  19485. tableDragTimer = null;
  19486. }
  19487. function reconstruct( obj ) {
  19488. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19489. newObj = {};
  19490. if( obj ) {
  19491. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19492. val=obj[ key ];
  19493. val && (newObj[ key ] = val);
  19494. }
  19495. }
  19496. return newObj;
  19497. }
  19498. //边框拖动
  19499. function tableBorderDrag( evt ) {
  19500. isInResizeBuffer = false;
  19501. startTd = evt.target || evt.srcElement;
  19502. if( !startTd ) return;
  19503. var state = getRelation(startTd, mouseCoords(evt));
  19504. if (/\d/.test(state)) {
  19505. state = state.replace(/\d/, '');
  19506. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19507. }
  19508. hideDragLine(me);
  19509. getDragLine(me, me.document);
  19510. me.fireEvent('saveScene');
  19511. showDragLineAt(state, startTd);
  19512. mousedown = true;
  19513. //拖动开始
  19514. onDrag = state;
  19515. dragTd = startTd;
  19516. }
  19517. function mouseUpEvent(type, evt) {
  19518. if( isEditorDisabled() ) {
  19519. return ;
  19520. }
  19521. clearTableDragTimer();
  19522. isInResizeBuffer = false;
  19523. if( onBorder ) {
  19524. singleClickState = ++singleClickState % 3;
  19525. userActionStatus = {
  19526. x: evt.clientX,
  19527. y: evt.clientY
  19528. };
  19529. tableResizeTimer = setTimeout(function(){
  19530. singleClickState > 0 && singleClickState--;
  19531. }, dblclickTime );
  19532. if( singleClickState === 2 ) {
  19533. singleClickState = 0;
  19534. tableDbclickHandler(evt);
  19535. return;
  19536. }
  19537. }
  19538. if (evt.button == 2)return;
  19539. var me = this;
  19540. //清除表格上原生跨选问题
  19541. var range = me.selection.getRange(),
  19542. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19543. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19544. if (start || end) {
  19545. if (start === end) {
  19546. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19547. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19548. if (start !== end) {
  19549. me.selection.clearRange()
  19550. }
  19551. } else {
  19552. me.selection.clearRange()
  19553. }
  19554. }
  19555. mousedown = false;
  19556. me.document.body.style.webkitUserSelect = '';
  19557. //拖拽状态下的mouseUP
  19558. if ( onDrag && dragTd ) {
  19559. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19560. singleClickState = 0;
  19561. dragLine = me.document.getElementById('ue_tableDragLine');
  19562. // trace 3973
  19563. if (dragLine) {
  19564. var dragTdPos = domUtils.getXY(dragTd),
  19565. dragLinePos = domUtils.getXY(dragLine);
  19566. switch (onDrag) {
  19567. case "h":
  19568. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19569. break;
  19570. case "v":
  19571. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19572. break;
  19573. default:
  19574. }
  19575. onDrag = "";
  19576. dragTd = null;
  19577. hideDragLine(me);
  19578. me.fireEvent('saveScene');
  19579. return;
  19580. }
  19581. }
  19582. //正常状态下的mouseup
  19583. if (!startTd) {
  19584. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19585. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19586. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19587. if (me.fireEvent("excludetable", target) === true) return;
  19588. range = new dom.Range(me.document);
  19589. range.setStart(target, 0).setCursor(false, true);
  19590. }
  19591. } else {
  19592. var ut = getUETable(startTd),
  19593. cell = ut ? ut.selectedTds[0] : null;
  19594. if (cell) {
  19595. range = new dom.Range(me.document);
  19596. if (domUtils.isEmptyBlock(cell)) {
  19597. range.setStart(cell, 0).setCursor(false, true);
  19598. } else {
  19599. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19600. }
  19601. } else {
  19602. range = me.selection.getRange().shrinkBoundary();
  19603. if (!range.collapsed) {
  19604. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19605. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19606. //在table里边的不能清除
  19607. if (start && !end || !start && end || start && end && start !== end) {
  19608. range.setCursor(false, true);
  19609. }
  19610. }
  19611. }
  19612. startTd = null;
  19613. me.removeListener('mouseover', mouseOverEvent);
  19614. }
  19615. me._selectionChange(250, evt);
  19616. }
  19617. function mouseOverEvent(type, evt) {
  19618. if( isEditorDisabled() ) {
  19619. return;
  19620. }
  19621. var me = this,
  19622. tar = evt.target || evt.srcElement;
  19623. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19624. //需要判断两个TD是否位于同一个表格内
  19625. if (startTd && currentTd &&
  19626. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19627. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19628. var ut = getUETable(currentTd);
  19629. if (startTd != currentTd) {
  19630. me.document.body.style.webkitUserSelect = 'none';
  19631. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19632. var range = ut.getCellsRange(startTd, currentTd);
  19633. ut.setSelected(range);
  19634. } else {
  19635. me.document.body.style.webkitUserSelect = '';
  19636. ut.clearSelected();
  19637. }
  19638. }
  19639. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19640. }
  19641. function setCellHeight(cell, height, backHeight) {
  19642. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19643. tmpHeight = backHeight + height;
  19644. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19645. if (cell.style.height) cell.style.height = "";
  19646. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19647. }
  19648. function getWidth(cell) {
  19649. if (!cell)return 0;
  19650. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19651. }
  19652. function changeColWidth(cell, changeValue) {
  19653. var ut = getUETable(cell);
  19654. if (ut) {
  19655. //根据当前移动的边框获取相关的单元格
  19656. var table = ut.table,
  19657. cells = getCellsByMoveBorder( cell, table );
  19658. table.style.width = "";
  19659. table.removeAttribute("width");
  19660. //修正改变量
  19661. changeValue = correctChangeValue( changeValue, cell, cells );
  19662. if (cell.nextSibling) {
  19663. var i=0;
  19664. utils.each( cells, function( cellGroup ){
  19665. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19666. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19667. } );
  19668. } else {
  19669. utils.each( cells, function( cellGroup ){
  19670. cellGroup.left.width -= -changeValue;
  19671. } );
  19672. }
  19673. }
  19674. }
  19675. function isEditorDisabled() {
  19676. return me.body.contentEditable === "false";
  19677. }
  19678. function changeRowHeight(td, changeValue) {
  19679. if (Math.abs(changeValue) < 10) return;
  19680. var ut = getUETable(td);
  19681. if (ut) {
  19682. var cells = ut.getSameEndPosCells(td, "y"),
  19683. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19684. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19685. for (var i = 0, cell; cell = cells[i++];) {
  19686. setCellHeight(cell, changeValue, backHeight);
  19687. }
  19688. }
  19689. }
  19690. /**
  19691. * 获取调整单元格大小的相关单元格
  19692. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19693. */
  19694. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19695. if( !table ) {
  19696. table = domUtils.findParentByTagName( cell, 'table' );
  19697. }
  19698. if( !table ) {
  19699. return null;
  19700. }
  19701. //获取到该单元格所在行的序列号
  19702. var index = domUtils.getNodeIndex( cell ),
  19703. temp = cell,
  19704. rows = table.rows,
  19705. colIndex = 0;
  19706. while( temp ) {
  19707. //获取到当前单元格在未发生单元格合并时的序列
  19708. if( temp.nodeType === 1 ) {
  19709. colIndex += (temp.colSpan || 1);
  19710. }
  19711. temp = temp.previousSibling;
  19712. }
  19713. temp = null;
  19714. //记录想关的单元格
  19715. var borderCells = [];
  19716. utils.each(rows, function( tabRow ){
  19717. var cells = tabRow.cells,
  19718. currIndex = 0;
  19719. utils.each( cells, function( tabCell ){
  19720. currIndex += (tabCell.colSpan || 1);
  19721. if( currIndex === colIndex ) {
  19722. borderCells.push({
  19723. left: tabCell,
  19724. right: tabCell.nextSibling || null
  19725. });
  19726. return false;
  19727. } else if( currIndex > colIndex ) {
  19728. if( isContainMergeCell ) {
  19729. borderCells.push({
  19730. left: tabCell
  19731. });
  19732. }
  19733. return false;
  19734. }
  19735. } );
  19736. });
  19737. return borderCells;
  19738. }
  19739. /**
  19740. * 通过给定的单元格集合获取最小的单元格width
  19741. */
  19742. function getMinWidthByTableCells( cells ) {
  19743. var minWidth = Number.MAX_VALUE;
  19744. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19745. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19746. }
  19747. return minWidth;
  19748. }
  19749. function correctChangeValue( changeValue, relatedCell, cells ) {
  19750. //为单元格的paading预留空间
  19751. changeValue -= getTabcellSpace();
  19752. if( changeValue < 0 ) {
  19753. return 0;
  19754. }
  19755. changeValue -= getTableCellWidth( relatedCell );
  19756. //确定方向
  19757. var direction = changeValue < 0 ? 'left':'right';
  19758. changeValue = Math.abs(changeValue);
  19759. //只关心非最后一个单元格就可以
  19760. utils.each( cells, function( cellGroup ){
  19761. var curCell = cellGroup[direction];
  19762. //为单元格保留最小空间
  19763. if( curCell ) {
  19764. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19765. }
  19766. } );
  19767. //修正越界
  19768. changeValue = changeValue < 0 ? 0 : changeValue;
  19769. return direction === 'left' ? -changeValue : changeValue;
  19770. }
  19771. function getTableCellWidth( cell ) {
  19772. var width = 0,
  19773. //偏移纠正量
  19774. offset = 0,
  19775. width = cell.offsetWidth - getTabcellSpace();
  19776. //最后一个节点纠正一下
  19777. if( !cell.nextSibling ) {
  19778. width -= getTableCellOffset( cell );
  19779. }
  19780. width = width < 0 ? 0 : width;
  19781. try {
  19782. cell.width = width;
  19783. } catch(e) {
  19784. }
  19785. return width;
  19786. }
  19787. /**
  19788. * 获取单元格所在表格的最末单元格的偏移量
  19789. */
  19790. function getTableCellOffset( cell ) {
  19791. tab = domUtils.findParentByTagName( cell, "table", false);
  19792. if( tab.offsetVal === undefined ) {
  19793. var prev = cell.previousSibling;
  19794. if( prev ) {
  19795. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19796. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19797. } else {
  19798. tab.offsetVal = 0;
  19799. }
  19800. }
  19801. return tab.offsetVal;
  19802. }
  19803. function getTabcellSpace() {
  19804. if( UT.tabcellSpace === undefined ) {
  19805. var cell = null,
  19806. tab = me.document.createElement("table"),
  19807. tbody = me.document.createElement("tbody"),
  19808. trow = me.document.createElement("tr"),
  19809. tabcell = me.document.createElement("td"),
  19810. mirror = null;
  19811. tabcell.style.cssText = 'border: 0;';
  19812. tabcell.width = 1;
  19813. trow.appendChild( tabcell );
  19814. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19815. tbody.appendChild( trow );
  19816. tab.appendChild( tbody );
  19817. tab.style.cssText = "visibility: hidden;";
  19818. me.body.appendChild( tab );
  19819. UT.paddingSpace = tabcell.offsetWidth - 1;
  19820. var tmpTabWidth = tab.offsetWidth;
  19821. tabcell.style.cssText = '';
  19822. mirror.style.cssText = '';
  19823. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19824. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19825. me.body.removeChild( tab );
  19826. }
  19827. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19828. return UT.tabcellSpace;
  19829. }
  19830. function getDragLine(editor, doc) {
  19831. if (mousedown)return;
  19832. dragLine = editor.document.createElement("div");
  19833. domUtils.setAttributes(dragLine, {
  19834. id:"ue_tableDragLine",
  19835. unselectable:'on',
  19836. contenteditable:false,
  19837. 'onresizestart':'return false',
  19838. 'ondragstart':'return false',
  19839. 'onselectstart':'return false',
  19840. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19841. });
  19842. editor.body.appendChild(dragLine);
  19843. }
  19844. function hideDragLine(editor) {
  19845. if (mousedown)return;
  19846. var line;
  19847. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19848. domUtils.remove(line)
  19849. }
  19850. }
  19851. /**
  19852. * 依据state(v|h)在cell位置显示横线
  19853. * @param state
  19854. * @param cell
  19855. */
  19856. function showDragLineAt(state, cell) {
  19857. if (!cell) return;
  19858. var table = domUtils.findParentByTagName(cell, "table"),
  19859. caption = table.getElementsByTagName('caption'),
  19860. width = table.offsetWidth,
  19861. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19862. tablePos = domUtils.getXY(table),
  19863. cellPos = domUtils.getXY(cell), css;
  19864. switch (state) {
  19865. case "h":
  19866. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19867. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19868. break;
  19869. case "v":
  19870. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19871. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19872. 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)';
  19873. break;
  19874. default:
  19875. }
  19876. }
  19877. /**
  19878. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19879. * @param editor
  19880. * @param flag
  19881. */
  19882. function switchBorderColor(editor, flag) {
  19883. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19884. for (var i = 0, node; node = tableArr[i++];) {
  19885. var td = domUtils.getElementsByTagName(node, "td");
  19886. if (td[0]) {
  19887. if (flag) {
  19888. color = (td[0].style.borderColor).replace(/\s/g, "");
  19889. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19890. domUtils.addClass(node, "noBorderTable")
  19891. } else {
  19892. domUtils.removeClasses(node, "noBorderTable")
  19893. }
  19894. }
  19895. }
  19896. }
  19897. function getTableWidth(editor, needIEHack, defaultValue) {
  19898. var body = editor.body;
  19899. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19900. }
  19901. /**
  19902. * 获取当前拖动的单元格
  19903. */
  19904. function getTargetTd(editor, evt) {
  19905. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19906. dir = null;
  19907. if( !target ) {
  19908. return null;
  19909. }
  19910. dir = getRelation( target, mouseCoords( evt ) );
  19911. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19912. if( !target ) {
  19913. return null;
  19914. }
  19915. if( dir === 'h1' && target.previousSibling ) {
  19916. var position = domUtils.getXY( target),
  19917. cellWidth = target.offsetWidth;
  19918. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19919. target = target.previousSibling;
  19920. }
  19921. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19922. var position = domUtils.getXY( target),
  19923. cellHeight = target.offsetHeight;
  19924. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19925. target = target.parentNode.previousSibling.firstChild;
  19926. }
  19927. }
  19928. //排除了非td内部以及用于代码高亮部分的td
  19929. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19930. }
  19931. };
  19932. // plugins/table.sort.js
  19933. /**
  19934. * Created with JetBrains PhpStorm.
  19935. * User: Jinqn
  19936. * Date: 13-10-12
  19937. * Time: 上午10:20
  19938. * To change this template use File | Settings | File Templates.
  19939. */
  19940. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19941. var table = this.table,
  19942. rows = table.rows,
  19943. trArray = [],
  19944. flag = rows[0].cells[0].tagName === "TH",
  19945. lastRowIndex = 0;
  19946. if(this.selectedTds.length){
  19947. var range = this.cellsRange,
  19948. len = range.endRowIndex + 1;
  19949. for (var i = range.beginRowIndex; i < len; i++) {
  19950. trArray[i] = rows[i];
  19951. }
  19952. trArray.splice(0,range.beginRowIndex);
  19953. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19954. }else{
  19955. for (var i = 0,len = rows.length; i < len; i++) {
  19956. trArray[i] = rows[i];
  19957. }
  19958. }
  19959. var Fn = {
  19960. 'reversecurrent': function(td1,td2){
  19961. return 1;
  19962. },
  19963. 'orderbyasc': function(td1,td2){
  19964. var value1 = td1.innerText||td1.textContent,
  19965. value2 = td2.innerText||td2.textContent;
  19966. return value1.localeCompare(value2);
  19967. },
  19968. 'reversebyasc': function(td1,td2){
  19969. var value1 = td1.innerHTML,
  19970. value2 = td2.innerHTML;
  19971. return value2.localeCompare(value1);
  19972. },
  19973. 'orderbynum': function(td1,td2){
  19974. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19975. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19976. if(value1) value1 = +value1[0];
  19977. if(value2) value2 = +value2[0];
  19978. return (value1||0) - (value2||0);
  19979. },
  19980. 'reversebynum': function(td1,td2){
  19981. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19982. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19983. if(value1) value1 = +value1[0];
  19984. if(value2) value2 = +value2[0];
  19985. return (value2||0) - (value1||0);
  19986. }
  19987. };
  19988. //对表格设置排序的标记data-sort-type
  19989. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19990. //th不参与排序
  19991. flag && trArray.splice(0, 1);
  19992. trArray = utils.sort(trArray,function (tr1, tr2) {
  19993. var result;
  19994. if (compareFn && typeof compareFn === "function") {
  19995. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19996. } else if (compareFn && typeof compareFn === "number") {
  19997. result = 1;
  19998. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19999. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20000. } else {
  20001. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20002. }
  20003. return result;
  20004. });
  20005. var fragment = table.ownerDocument.createDocumentFragment();
  20006. for (var j = 0, len = trArray.length; j < len; j++) {
  20007. fragment.appendChild(trArray[j]);
  20008. }
  20009. var tbody = table.getElementsByTagName("tbody")[0];
  20010. if(!lastRowIndex){
  20011. tbody.appendChild(fragment);
  20012. }else{
  20013. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  20014. }
  20015. };
  20016. UE.plugins['tablesort'] = function () {
  20017. var me = this,
  20018. UT = UE.UETable,
  20019. getUETable = function (tdOrTable) {
  20020. return UT.getUETable(tdOrTable);
  20021. },
  20022. getTableItemsByRange = function (editor) {
  20023. return UT.getTableItemsByRange(editor);
  20024. };
  20025. me.ready(function () {
  20026. //添加表格可排序的样式
  20027. utils.cssRule('tablesort',
  20028. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20029. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20030. me.document);
  20031. //做单元格合并操作时,清除可排序标识
  20032. me.addListener("afterexeccommand", function (type, cmd) {
  20033. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20034. this.execCommand('disablesort');
  20035. }
  20036. });
  20037. });
  20038. //表格排序
  20039. UE.commands['sorttable'] = {
  20040. queryCommandState: function () {
  20041. var me = this,
  20042. tableItems = getTableItemsByRange(me);
  20043. if (!tableItems.cell) return -1;
  20044. var table = tableItems.table,
  20045. cells = table.getElementsByTagName("td");
  20046. for (var i = 0, cell; cell = cells[i++];) {
  20047. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20048. }
  20049. return 0;
  20050. },
  20051. execCommand: function (cmd, fn) {
  20052. var me = this,
  20053. range = me.selection.getRange(),
  20054. bk = range.createBookmark(true),
  20055. tableItems = getTableItemsByRange(me),
  20056. cell = tableItems.cell,
  20057. ut = getUETable(tableItems.table),
  20058. cellInfo = ut.getCellInfo(cell);
  20059. ut.sortTable(cellInfo.cellIndex, fn);
  20060. range.moveToBookmark(bk);
  20061. try{
  20062. range.select();
  20063. }catch(e){}
  20064. }
  20065. };
  20066. //设置表格可排序,清除表格可排序
  20067. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20068. queryCommandState: function (cmd) {
  20069. var table = getTableItemsByRange(this).table;
  20070. if(table && cmd=='enablesort') {
  20071. var cells = domUtils.getElementsByTagName(table, 'th td');
  20072. for(var i = 0; i<cells.length; i++) {
  20073. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20074. }
  20075. }
  20076. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20077. },
  20078. execCommand: function (cmd) {
  20079. var table = getTableItemsByRange(this).table;
  20080. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20081. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20082. }
  20083. };
  20084. };
  20085. // plugins/contextmenu.js
  20086. ///import core
  20087. ///commands 右键菜单
  20088. ///commandsName ContextMenu
  20089. ///commandsTitle 右键菜单
  20090. /**
  20091. * 右键菜单
  20092. * @function
  20093. * @name baidu.editor.plugins.contextmenu
  20094. * @author zhanyi
  20095. */
  20096. UE.plugins['contextmenu'] = function () {
  20097. var me = this;
  20098. me.setOpt('enableContextMenu',true);
  20099. if(me.getOpt('enableContextMenu') === false){
  20100. return;
  20101. }
  20102. var lang = me.getLang( "contextMenu" ),
  20103. menu,
  20104. items = me.options.contextMenu || [
  20105. {label:lang['selectall'], cmdName:'selectall'},
  20106. {
  20107. label:lang.cleardoc,
  20108. cmdName:'cleardoc',
  20109. exec:function () {
  20110. if ( confirm( lang.confirmclear ) ) {
  20111. this.execCommand( 'cleardoc' );
  20112. }
  20113. }
  20114. },
  20115. '-',
  20116. {
  20117. label:lang.unlink,
  20118. cmdName:'unlink'
  20119. },
  20120. '-',
  20121. {
  20122. group:lang.paragraph,
  20123. icon:'justifyjustify',
  20124. subMenu:[
  20125. {
  20126. label:lang.justifyleft,
  20127. cmdName:'justify',
  20128. value:'left'
  20129. },
  20130. {
  20131. label:lang.justifyright,
  20132. cmdName:'justify',
  20133. value:'right'
  20134. },
  20135. {
  20136. label:lang.justifycenter,
  20137. cmdName:'justify',
  20138. value:'center'
  20139. },
  20140. {
  20141. label:lang.justifyjustify,
  20142. cmdName:'justify',
  20143. value:'justify'
  20144. }
  20145. ]
  20146. },
  20147. '-',
  20148. {
  20149. group:lang.table,
  20150. icon:'table',
  20151. subMenu:[
  20152. {
  20153. label:lang.inserttable,
  20154. cmdName:'inserttable'
  20155. },
  20156. {
  20157. label:lang.deletetable,
  20158. cmdName:'deletetable'
  20159. },
  20160. '-',
  20161. {
  20162. label:lang.deleterow,
  20163. cmdName:'deleterow'
  20164. },
  20165. {
  20166. label:lang.deletecol,
  20167. cmdName:'deletecol'
  20168. },
  20169. {
  20170. label:lang.insertcol,
  20171. cmdName:'insertcol'
  20172. },
  20173. {
  20174. label:lang.insertcolnext,
  20175. cmdName:'insertcolnext'
  20176. },
  20177. {
  20178. label:lang.insertrow,
  20179. cmdName:'insertrow'
  20180. },
  20181. {
  20182. label:lang.insertrownext,
  20183. cmdName:'insertrownext'
  20184. },
  20185. '-',
  20186. {
  20187. label:lang.insertcaption,
  20188. cmdName:'insertcaption'
  20189. },
  20190. {
  20191. label:lang.deletecaption,
  20192. cmdName:'deletecaption'
  20193. },
  20194. {
  20195. label:lang.inserttitle,
  20196. cmdName:'inserttitle'
  20197. },
  20198. {
  20199. label:lang.deletetitle,
  20200. cmdName:'deletetitle'
  20201. },
  20202. {
  20203. label:lang.inserttitlecol,
  20204. cmdName:'inserttitlecol'
  20205. },
  20206. {
  20207. label:lang.deletetitlecol,
  20208. cmdName:'deletetitlecol'
  20209. },
  20210. '-',
  20211. {
  20212. label:lang.mergecells,
  20213. cmdName:'mergecells'
  20214. },
  20215. {
  20216. label:lang.mergeright,
  20217. cmdName:'mergeright'
  20218. },
  20219. {
  20220. label:lang.mergedown,
  20221. cmdName:'mergedown'
  20222. },
  20223. '-',
  20224. {
  20225. label:lang.splittorows,
  20226. cmdName:'splittorows'
  20227. },
  20228. {
  20229. label:lang.splittocols,
  20230. cmdName:'splittocols'
  20231. },
  20232. {
  20233. label:lang.splittocells,
  20234. cmdName:'splittocells'
  20235. },
  20236. '-',
  20237. {
  20238. label:lang.averageDiseRow,
  20239. cmdName:'averagedistributerow'
  20240. },
  20241. {
  20242. label:lang.averageDisCol,
  20243. cmdName:'averagedistributecol'
  20244. },
  20245. '-',
  20246. {
  20247. label:lang.edittd,
  20248. cmdName:'edittd',
  20249. exec:function () {
  20250. if ( UE.ui['edittd'] ) {
  20251. new UE.ui['edittd']( this );
  20252. }
  20253. this.getDialog('edittd').open();
  20254. }
  20255. },
  20256. {
  20257. label:lang.edittable,
  20258. cmdName:'edittable',
  20259. exec:function () {
  20260. if ( UE.ui['edittable'] ) {
  20261. new UE.ui['edittable']( this );
  20262. }
  20263. this.getDialog('edittable').open();
  20264. }
  20265. },
  20266. {
  20267. label:lang.setbordervisible,
  20268. cmdName:'setbordervisible'
  20269. }
  20270. ]
  20271. },
  20272. {
  20273. group:lang.tablesort,
  20274. icon:'tablesort',
  20275. subMenu:[
  20276. {
  20277. label:lang.enablesort,
  20278. cmdName:'enablesort'
  20279. },
  20280. {
  20281. label:lang.disablesort,
  20282. cmdName:'disablesort'
  20283. },
  20284. '-',
  20285. {
  20286. label:lang.reversecurrent,
  20287. cmdName:'sorttable',
  20288. value:'reversecurrent'
  20289. },
  20290. {
  20291. label:lang.orderbyasc,
  20292. cmdName:'sorttable',
  20293. value:'orderbyasc'
  20294. },
  20295. {
  20296. label:lang.reversebyasc,
  20297. cmdName:'sorttable',
  20298. value:'reversebyasc'
  20299. },
  20300. {
  20301. label:lang.orderbynum,
  20302. cmdName:'sorttable',
  20303. value:'orderbynum'
  20304. },
  20305. {
  20306. label:lang.reversebynum,
  20307. cmdName:'sorttable',
  20308. value:'reversebynum'
  20309. }
  20310. ]
  20311. },
  20312. {
  20313. group:lang.borderbk,
  20314. icon:'borderBack',
  20315. subMenu:[
  20316. {
  20317. label:lang.setcolor,
  20318. cmdName:"interlacetable",
  20319. exec:function(){
  20320. this.execCommand("interlacetable");
  20321. }
  20322. },
  20323. {
  20324. label:lang.unsetcolor,
  20325. cmdName:"uninterlacetable",
  20326. exec:function(){
  20327. this.execCommand("uninterlacetable");
  20328. }
  20329. },
  20330. {
  20331. label:lang.setbackground,
  20332. cmdName:"settablebackground",
  20333. exec:function(){
  20334. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20335. }
  20336. },
  20337. {
  20338. label:lang.unsetbackground,
  20339. cmdName:"cleartablebackground",
  20340. exec:function(){
  20341. this.execCommand("cleartablebackground");
  20342. }
  20343. },
  20344. {
  20345. label:lang.redandblue,
  20346. cmdName:"settablebackground",
  20347. exec:function(){
  20348. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20349. }
  20350. },
  20351. {
  20352. label:lang.threecolorgradient,
  20353. cmdName:"settablebackground",
  20354. exec:function(){
  20355. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20356. }
  20357. }
  20358. ]
  20359. },
  20360. {
  20361. group:lang.aligntd,
  20362. icon:'aligntd',
  20363. subMenu:[
  20364. {
  20365. cmdName:'cellalignment',
  20366. value:{align:'left',vAlign:'top'}
  20367. },
  20368. {
  20369. cmdName:'cellalignment',
  20370. value:{align:'center',vAlign:'top'}
  20371. },
  20372. {
  20373. cmdName:'cellalignment',
  20374. value:{align:'right',vAlign:'top'}
  20375. },
  20376. {
  20377. cmdName:'cellalignment',
  20378. value:{align:'left',vAlign:'middle'}
  20379. },
  20380. {
  20381. cmdName:'cellalignment',
  20382. value:{align:'center',vAlign:'middle'}
  20383. },
  20384. {
  20385. cmdName:'cellalignment',
  20386. value:{align:'right',vAlign:'middle'}
  20387. },
  20388. {
  20389. cmdName:'cellalignment',
  20390. value:{align:'left',vAlign:'bottom'}
  20391. },
  20392. {
  20393. cmdName:'cellalignment',
  20394. value:{align:'center',vAlign:'bottom'}
  20395. },
  20396. {
  20397. cmdName:'cellalignment',
  20398. value:{align:'right',vAlign:'bottom'}
  20399. }
  20400. ]
  20401. },
  20402. {
  20403. group:lang.aligntable,
  20404. icon:'aligntable',
  20405. subMenu:[
  20406. {
  20407. cmdName:'tablealignment',
  20408. className: 'left',
  20409. label:lang.tableleft,
  20410. value:"left"
  20411. },
  20412. {
  20413. cmdName:'tablealignment',
  20414. className: 'center',
  20415. label:lang.tablecenter,
  20416. value:"center"
  20417. },
  20418. {
  20419. cmdName:'tablealignment',
  20420. className: 'right',
  20421. label:lang.tableright,
  20422. value:"right"
  20423. }
  20424. ]
  20425. },
  20426. '-',
  20427. {
  20428. label:lang.insertparagraphbefore,
  20429. cmdName:'insertparagraph',
  20430. value:true
  20431. },
  20432. {
  20433. label:lang.insertparagraphafter,
  20434. cmdName:'insertparagraph'
  20435. },
  20436. {
  20437. label:lang['copy'],
  20438. cmdName:'copy'
  20439. },
  20440. {
  20441. label:lang['paste'],
  20442. cmdName:'paste'
  20443. }
  20444. ];
  20445. if ( !items.length ) {
  20446. return;
  20447. }
  20448. var uiUtils = UE.ui.uiUtils;
  20449. me.addListener( 'contextmenu', function ( type, evt ) {
  20450. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20451. me.fireEvent( 'beforeselectionchange' );
  20452. if ( menu ) {
  20453. menu.destroy();
  20454. }
  20455. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20456. var last;
  20457. (function ( item ) {
  20458. if ( item == '-' ) {
  20459. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20460. contextItems.push( '-' );
  20461. }
  20462. } else if ( item.hasOwnProperty( "group" ) ) {
  20463. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20464. (function ( subItem ) {
  20465. if ( subItem == '-' ) {
  20466. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20467. subMenu.push( '-' );
  20468. }else{
  20469. subMenu.splice(subMenu.length-1);
  20470. }
  20471. } else {
  20472. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20473. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20474. subMenu.push( {
  20475. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20476. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20477. onclick:subItem.exec ? function () {
  20478. subItem.exec.call( me );
  20479. } : function () {
  20480. me.execCommand( subItem.cmdName, subItem.value );
  20481. }
  20482. } );
  20483. }
  20484. }
  20485. })( cj );
  20486. }
  20487. if ( subMenu.length ) {
  20488. function getLabel(){
  20489. switch (item.icon){
  20490. case "table":
  20491. return me.getLang( "contextMenu.table" );
  20492. case "justifyjustify":
  20493. return me.getLang( "contextMenu.paragraph" );
  20494. case "aligntd":
  20495. return me.getLang("contextMenu.aligntd");
  20496. case "aligntable":
  20497. return me.getLang("contextMenu.aligntable");
  20498. case "tablesort":
  20499. return lang.tablesort;
  20500. case "borderBack":
  20501. return lang.borderbk;
  20502. default :
  20503. return '';
  20504. }
  20505. }
  20506. contextItems.push( {
  20507. //todo 修正成自动获取方式
  20508. 'label':getLabel(),
  20509. className:'edui-for-' + item.icon,
  20510. 'subMenu':{
  20511. items:subMenu,
  20512. editor:me
  20513. }
  20514. } );
  20515. }
  20516. } else {
  20517. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20518. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20519. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20520. contextItems.push( {
  20521. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20522. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20523. onclick:item.exec ? function () {
  20524. item.exec.call( me );
  20525. } : function () {
  20526. me.execCommand( item.cmdName, item.value );
  20527. }
  20528. } );
  20529. }
  20530. }
  20531. })( ti );
  20532. }
  20533. if ( contextItems[contextItems.length - 1] == '-' ) {
  20534. contextItems.pop();
  20535. }
  20536. menu = new UE.ui.Menu( {
  20537. items:contextItems,
  20538. className:"edui-contextmenu",
  20539. editor:me
  20540. } );
  20541. menu.render();
  20542. menu.showAt( offset );
  20543. me.fireEvent("aftershowcontextmenu",menu);
  20544. domUtils.preventDefault( evt );
  20545. if ( browser.ie ) {
  20546. var ieRange;
  20547. try {
  20548. ieRange = me.selection.getNative().createRange();
  20549. } catch ( e ) {
  20550. return;
  20551. }
  20552. if ( ieRange.item ) {
  20553. var range = new dom.Range( me.document );
  20554. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20555. }
  20556. }
  20557. });
  20558. // 添加复制的flash按钮
  20559. me.addListener('aftershowcontextmenu', function(type, menu) {
  20560. if (me.zeroclipboard) {
  20561. var items = menu.items;
  20562. for (var key in items) {
  20563. if (items[key].className == 'edui-for-copy') {
  20564. me.zeroclipboard.clip(items[key].getDom());
  20565. }
  20566. }
  20567. }
  20568. });
  20569. };
  20570. // plugins/shortcutmenu.js
  20571. ///import core
  20572. ///commands 弹出菜单
  20573. // commandsName popupmenu
  20574. ///commandsTitle 弹出菜单
  20575. /**
  20576. * 弹出菜单
  20577. * @function
  20578. * @name baidu.editor.plugins.popupmenu
  20579. * @author xuheng
  20580. */
  20581. UE.plugins['shortcutmenu'] = function () {
  20582. var me = this,
  20583. menu,
  20584. items = me.options.shortcutMenu || [];
  20585. if (!items.length) {
  20586. return;
  20587. }
  20588. me.addListener ('contextmenu mouseup' , function (type , e) {
  20589. var me = this,
  20590. customEvt = {
  20591. type : type ,
  20592. target : e.target || e.srcElement ,
  20593. screenX : e.screenX ,
  20594. screenY : e.screenY ,
  20595. clientX : e.clientX ,
  20596. clientY : e.clientY
  20597. };
  20598. setTimeout (function () {
  20599. var rng = me.selection.getRange ();
  20600. if (rng.collapsed === false || type == "contextmenu") {
  20601. if (!menu) {
  20602. menu = new baidu.editor.ui.ShortCutMenu ({
  20603. editor : me ,
  20604. items : items ,
  20605. theme : me.options.theme ,
  20606. className : 'edui-shortcutmenu'
  20607. });
  20608. menu.render ();
  20609. me.fireEvent ("afterrendershortcutmenu" , menu);
  20610. }
  20611. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20612. }
  20613. });
  20614. if (type == 'contextmenu') {
  20615. domUtils.preventDefault (e);
  20616. if (browser.ie9below) {
  20617. var ieRange;
  20618. try {
  20619. ieRange = me.selection.getNative().createRange();
  20620. } catch (e) {
  20621. return;
  20622. }
  20623. if (ieRange.item) {
  20624. var range = new dom.Range (me.document);
  20625. range.selectNode (ieRange.item (0)).select (true , true);
  20626. }
  20627. }
  20628. }
  20629. });
  20630. me.addListener ('keydown' , function (type) {
  20631. if (type == "keydown") {
  20632. menu && !menu.isHidden && menu.hide ();
  20633. }
  20634. });
  20635. };
  20636. // plugins/basestyle.js
  20637. /**
  20638. * B、I、sub、super命令支持
  20639. * @file
  20640. * @since 1.2.6.1
  20641. */
  20642. UE.plugins['basestyle'] = function(){
  20643. /**
  20644. * 字体加粗
  20645. * @command bold
  20646. * @param { String } cmd 命令字符串
  20647. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20648. * @method execCommand
  20649. * @example
  20650. * ```javascript
  20651. * //editor是编辑器实例
  20652. * //对当前选中的文本内容执行加粗操作
  20653. * //第一次执行, 文本内容加粗
  20654. * editor.execCommand( 'bold' );
  20655. *
  20656. * //第二次执行, 文本内容取消加粗
  20657. * editor.execCommand( 'bold' );
  20658. * ```
  20659. */
  20660. /**
  20661. * 字体倾斜
  20662. * @command italic
  20663. * @method execCommand
  20664. * @param { String } cmd 命令字符串
  20665. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20666. * @example
  20667. * ```javascript
  20668. * //editor是编辑器实例
  20669. * //对当前选中的文本内容执行斜体操作
  20670. * //第一次操作, 文本内容将变成斜体
  20671. * editor.execCommand( 'italic' );
  20672. *
  20673. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20674. * editor.execCommand( 'italic' );
  20675. * ```
  20676. */
  20677. /**
  20678. * 下标文本,与“superscript”命令互斥
  20679. * @command subscript
  20680. * @method execCommand
  20681. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20682. * @param { String } cmd 命令字符串
  20683. * @example
  20684. * ```javascript
  20685. * //editor是编辑器实例
  20686. * //对当前选中的文本内容执行下标操作
  20687. * //第一次操作, 文本内容将变成下标文本
  20688. * editor.execCommand( 'subscript' );
  20689. *
  20690. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20691. * editor.execCommand( 'subscript' );
  20692. * ```
  20693. */
  20694. /**
  20695. * 上标文本,与“subscript”命令互斥
  20696. * @command superscript
  20697. * @method execCommand
  20698. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20699. * @param { String } cmd 命令字符串
  20700. * @example
  20701. * ```javascript
  20702. * //editor是编辑器实例
  20703. * //对当前选中的文本内容执行上标操作
  20704. * //第一次操作, 文本内容将变成上标文本
  20705. * editor.execCommand( 'superscript' );
  20706. *
  20707. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20708. * editor.execCommand( 'superscript' );
  20709. * ```
  20710. */
  20711. var basestyles = {
  20712. 'bold':['strong','b'],
  20713. 'italic':['em','i'],
  20714. 'subscript':['sub'],
  20715. 'superscript':['sup']
  20716. },
  20717. getObj = function(editor,tagNames){
  20718. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20719. },
  20720. me = this;
  20721. //添加快捷键
  20722. me.addshortcutkey({
  20723. "Bold" : "ctrl+66",//^B
  20724. "Italic" : "ctrl+73", //^I
  20725. "Underline" : "ctrl+85"//^U
  20726. });
  20727. me.addInputRule(function(root){
  20728. utils.each(root.getNodesByTagName('b i'),function(node){
  20729. switch (node.tagName){
  20730. case 'b':
  20731. node.tagName = 'strong';
  20732. break;
  20733. case 'i':
  20734. node.tagName = 'em';
  20735. }
  20736. });
  20737. });
  20738. for ( var style in basestyles ) {
  20739. (function( cmd, tagNames ) {
  20740. me.commands[cmd] = {
  20741. execCommand : function( cmdName ) {
  20742. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20743. if ( range.collapsed ) {
  20744. if ( obj ) {
  20745. var tmpText = me.document.createTextNode('');
  20746. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20747. range.setStartBefore(tmpText);
  20748. domUtils.remove(tmpText);
  20749. } else {
  20750. var tmpNode = range.document.createElement( tagNames[0] );
  20751. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20752. tmpText = me.document.createTextNode('');
  20753. range.insertNode(tmpText)
  20754. .removeInlineStyle(['sub','sup'])
  20755. .setStartBefore(tmpText)
  20756. .collapse(true);
  20757. }
  20758. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20759. }
  20760. range.collapse( true );
  20761. } else {
  20762. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20763. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20764. range.removeInlineStyle(['sub','sup']);
  20765. }
  20766. }
  20767. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20768. }
  20769. range.select();
  20770. },
  20771. queryCommandState : function() {
  20772. return getObj(this,tagNames) ? 1 : 0;
  20773. }
  20774. };
  20775. })( style, basestyles[style] );
  20776. }
  20777. };
  20778. // plugins/elementpath.js
  20779. /**
  20780. * 选取路径命令
  20781. * @file
  20782. */
  20783. UE.plugins['elementpath'] = function(){
  20784. var currentLevel,
  20785. tagNames,
  20786. me = this;
  20787. me.setOpt('elementPathEnabled',true);
  20788. if(!me.options.elementPathEnabled){
  20789. return;
  20790. }
  20791. me.commands['elementpath'] = {
  20792. execCommand : function( cmdName, level ) {
  20793. var start = tagNames[level],
  20794. range = me.selection.getRange();
  20795. currentLevel = level*1;
  20796. range.selectNode(start).select();
  20797. },
  20798. queryCommandValue : function() {
  20799. //产生一个副本,不能修改原来的startElementPath;
  20800. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20801. names = [];
  20802. tagNames = parents;
  20803. for(var i=0,ci;ci=parents[i];i++){
  20804. if(ci.nodeType == 3) {
  20805. continue;
  20806. }
  20807. var name = ci.tagName.toLowerCase();
  20808. if(name == 'img' && ci.getAttribute('anchorname')){
  20809. name = 'anchor';
  20810. }
  20811. names[i] = name;
  20812. if(currentLevel == i){
  20813. currentLevel = -1;
  20814. break;
  20815. }
  20816. }
  20817. return names;
  20818. }
  20819. };
  20820. };
  20821. // plugins/formatmatch.js
  20822. /**
  20823. * 格式刷,只格式inline的
  20824. * @file
  20825. * @since 1.2.6.1
  20826. */
  20827. /**
  20828. * 格式刷
  20829. * @command formatmatch
  20830. * @method execCommand
  20831. * @remind 该操作不能复制段落格式
  20832. * @param { String } cmd 命令字符串
  20833. * @example
  20834. * ```javascript
  20835. * //editor是编辑器实例
  20836. * //获取格式刷
  20837. * editor.execCommand( 'formatmatch' );
  20838. * ```
  20839. */
  20840. UE.plugins['formatmatch'] = function(){
  20841. var me = this,
  20842. list = [],img,
  20843. flag = 0;
  20844. me.addListener('reset',function(){
  20845. list = [];
  20846. flag = 0;
  20847. });
  20848. function addList(type,evt){
  20849. if(browser.webkit){
  20850. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20851. }
  20852. function addFormat(range){
  20853. if(text){
  20854. range.selectNode(text);
  20855. }
  20856. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20857. }
  20858. me.undoManger && me.undoManger.save();
  20859. var range = me.selection.getRange(),
  20860. imgT = target || range.getClosedNode();
  20861. if(img && imgT && imgT.tagName == 'IMG'){
  20862. //trace:964
  20863. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20864. img = null;
  20865. }else{
  20866. if(!img){
  20867. var collapsed = range.collapsed;
  20868. if(collapsed){
  20869. var text = me.document.createTextNode('match');
  20870. range.insertNode(text).select();
  20871. }
  20872. me.__hasEnterExecCommand = true;
  20873. //不能把block上的属性干掉
  20874. //trace:1553
  20875. var removeFormatAttributes = me.options.removeFormatAttributes;
  20876. me.options.removeFormatAttributes = '';
  20877. me.execCommand('removeformat');
  20878. me.options.removeFormatAttributes = removeFormatAttributes;
  20879. me.__hasEnterExecCommand = false;
  20880. //trace:969
  20881. range = me.selection.getRange();
  20882. if(list.length){
  20883. addFormat(range);
  20884. }
  20885. if(text){
  20886. range.setStartBefore(text).collapse(true);
  20887. }
  20888. range.select();
  20889. text && domUtils.remove(text);
  20890. }
  20891. }
  20892. me.undoManger && me.undoManger.save();
  20893. me.removeListener('mouseup',addList);
  20894. flag = 0;
  20895. }
  20896. me.commands['formatmatch'] = {
  20897. execCommand : function( cmdName ) {
  20898. if(flag){
  20899. flag = 0;
  20900. list = [];
  20901. me.removeListener('mouseup',addList);
  20902. return;
  20903. }
  20904. var range = me.selection.getRange();
  20905. img = range.getClosedNode();
  20906. if(!img || img.tagName != 'IMG'){
  20907. range.collapse(true).shrinkBoundary();
  20908. var start = range.startContainer;
  20909. list = domUtils.findParents(start,true,function(node){
  20910. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20911. });
  20912. //a不能加入格式刷, 并且克隆节点
  20913. for(var i=0,ci;ci=list[i];i++){
  20914. if(ci.tagName == 'A'){
  20915. list.splice(i,1);
  20916. break;
  20917. }
  20918. }
  20919. }
  20920. me.addListener('mouseup',addList);
  20921. flag = 1;
  20922. },
  20923. queryCommandState : function() {
  20924. return flag;
  20925. },
  20926. notNeedUndo : 1
  20927. };
  20928. };
  20929. // plugins/searchreplace.js
  20930. ///import core
  20931. ///commands 查找替换
  20932. ///commandsName SearchReplace
  20933. ///commandsTitle 查询替换
  20934. ///commandsDialog dialogs\searchreplace
  20935. /**
  20936. * @description 查找替换
  20937. * @author zhanyi
  20938. */
  20939. UE.plugin.register('searchreplace',function(){
  20940. var me = this;
  20941. var _blockElm = {'table':1,'tbody':1,'tr':1,'ol':1,'ul':1};
  20942. function findTextInString(textContent,opt,currentIndex){
  20943. var str = opt.searchStr;
  20944. if(opt.dir == -1){
  20945. textContent = textContent.split('').reverse().join('');
  20946. str = str.split('').reverse().join('');
  20947. currentIndex = textContent.length - currentIndex;
  20948. }
  20949. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20950. while(match = reg.exec(textContent)){
  20951. if(match.index >= currentIndex){
  20952. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20953. }
  20954. }
  20955. return -1
  20956. }
  20957. function findTextBlockElm(node,currentIndex,opt){
  20958. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20959. if(domUtils.isBody(node)){
  20960. node = node.firstChild;
  20961. }
  20962. var first = 1;
  20963. while(node){
  20964. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20965. index = findTextInString(textContent,opt,currentIndex );
  20966. first = 0;
  20967. if(index!=-1){
  20968. return {
  20969. 'node':node,
  20970. 'index':index
  20971. }
  20972. }
  20973. node = domUtils[methodName](node);
  20974. while(node && _blockElm[node.nodeName.toLowerCase()]){
  20975. node = domUtils[methodName](node,true);
  20976. }
  20977. if(node){
  20978. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20979. }
  20980. }
  20981. }
  20982. function findNTextInBlockElm(node,index,str){
  20983. var currentIndex = 0,
  20984. currentNode = node.firstChild,
  20985. currentNodeLength = 0,
  20986. result;
  20987. while(currentNode){
  20988. if(currentNode.nodeType == 3){
  20989. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20990. currentIndex += currentNodeLength;
  20991. if(currentIndex >= index){
  20992. return {
  20993. 'node':currentNode,
  20994. 'index': currentNodeLength - (currentIndex - index)
  20995. }
  20996. }
  20997. }else if(!dtd.$empty[currentNode.tagName]){
  20998. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20999. currentIndex += currentNodeLength;
  21000. if(currentIndex >= index){
  21001. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  21002. if(result){
  21003. return result;
  21004. }
  21005. }
  21006. }
  21007. currentNode = domUtils.getNextDomNode(currentNode);
  21008. }
  21009. }
  21010. function searchReplace(me,opt){
  21011. var rng = me.selection.getRange(),
  21012. startBlockNode,
  21013. searchStr = opt.searchStr,
  21014. span = me.document.createElement('span');
  21015. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21016. rng.shrinkBoundary(true);
  21017. //判断是不是第一次选中
  21018. if(!rng.collapsed){
  21019. rng.select();
  21020. var rngText = me.selection.getText();
  21021. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  21022. if(opt.replaceStr != undefined){
  21023. replaceText(rng,opt.replaceStr);
  21024. rng.select();
  21025. return true;
  21026. }else{
  21027. rng.collapse(opt.dir == -1)
  21028. }
  21029. }
  21030. }
  21031. rng.insertNode(span);
  21032. rng.enlargeToBlockElm(true);
  21033. startBlockNode = rng.startContainer;
  21034. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21035. rng.setStartBefore(span);
  21036. domUtils.remove(span);
  21037. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  21038. if(result){
  21039. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  21040. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  21041. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  21042. if(opt.replaceStr !== undefined){
  21043. replaceText(rng,opt.replaceStr)
  21044. }
  21045. rng.select();
  21046. return true;
  21047. }else{
  21048. rng.setCursor()
  21049. }
  21050. }
  21051. function replaceText(rng,str){
  21052. str = me.document.createTextNode(str);
  21053. rng.deleteContents().insertNode(str);
  21054. }
  21055. return {
  21056. commands:{
  21057. 'searchreplace':{
  21058. execCommand:function(cmdName,opt){
  21059. utils.extend(opt,{
  21060. all : false,
  21061. casesensitive : false,
  21062. dir : 1
  21063. },true);
  21064. var num = 0;
  21065. if(opt.all){
  21066. var rng = me.selection.getRange(),
  21067. first = me.body.firstChild;
  21068. if(first && first.nodeType == 1){
  21069. rng.setStart(first,0);
  21070. rng.shrinkBoundary(true);
  21071. }else if(first.nodeType == 3){
  21072. rng.setStartBefore(first)
  21073. }
  21074. rng.collapse(true).select(true);
  21075. if(opt.replaceStr !== undefined){
  21076. me.fireEvent('saveScene');
  21077. }
  21078. while(searchReplace(this,opt)){
  21079. num++;
  21080. }
  21081. if(num){
  21082. me.fireEvent('saveScene');
  21083. }
  21084. }else{
  21085. if(opt.replaceStr !== undefined){
  21086. me.fireEvent('saveScene');
  21087. }
  21088. if(searchReplace(this,opt)){
  21089. num++
  21090. }
  21091. if(num){
  21092. me.fireEvent('saveScene');
  21093. }
  21094. }
  21095. return num;
  21096. },
  21097. notNeedUndo:1
  21098. }
  21099. }
  21100. }
  21101. });
  21102. // plugins/customstyle.js
  21103. /**
  21104. * 自定义样式
  21105. * @file
  21106. * @since 1.2.6.1
  21107. */
  21108. /**
  21109. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21110. * @command customstyle
  21111. * @method execCommand
  21112. * @param { String } cmd 命令字符串
  21113. * @example
  21114. * ```javascript
  21115. * editor.execCommand( 'customstyle' );
  21116. * ```
  21117. */
  21118. UE.plugins['customstyle'] = function() {
  21119. var me = this;
  21120. me.setOpt({ 'customstyle':[
  21121. {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;'},
  21122. {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;'},
  21123. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21124. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21125. ]});
  21126. me.commands['customstyle'] = {
  21127. execCommand : function(cmdName, obj) {
  21128. var me = this,
  21129. tagName = obj.tag,
  21130. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21131. return node.getAttribute('label');
  21132. }, true),
  21133. range,bk,tmpObj = {};
  21134. for (var p in obj) {
  21135. if(obj[p]!==undefined)
  21136. tmpObj[p] = obj[p];
  21137. }
  21138. delete tmpObj.tag;
  21139. if (node && node.getAttribute('label') == obj.label) {
  21140. range = this.selection.getRange();
  21141. bk = range.createBookmark();
  21142. if (range.collapsed) {
  21143. //trace:1732 删掉自定义标签,要有p来回填站位
  21144. if(dtd.$block[node.tagName]){
  21145. var fillNode = me.document.createElement('p');
  21146. domUtils.moveChild(node, fillNode);
  21147. node.parentNode.insertBefore(fillNode, node);
  21148. domUtils.remove(node);
  21149. }else{
  21150. domUtils.remove(node,true);
  21151. }
  21152. } else {
  21153. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21154. nodes = domUtils.getElementsByTagName(common, tagName);
  21155. if(new RegExp(tagName,'i').test(common.tagName)){
  21156. nodes.push(common);
  21157. }
  21158. for (var i = 0,ni; ni = nodes[i++];) {
  21159. if (ni.getAttribute('label') == obj.label) {
  21160. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21161. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21162. &&
  21163. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21164. )
  21165. if (dtd.$block[tagName]) {
  21166. var fillNode = me.document.createElement('p');
  21167. domUtils.moveChild(ni, fillNode);
  21168. ni.parentNode.insertBefore(fillNode, ni);
  21169. }
  21170. domUtils.remove(ni, true);
  21171. }
  21172. }
  21173. node = domUtils.findParent(common, function(node) {
  21174. return node.getAttribute('label') == obj.label;
  21175. }, true);
  21176. if (node) {
  21177. domUtils.remove(node, true);
  21178. }
  21179. }
  21180. range.moveToBookmark(bk).select();
  21181. } else {
  21182. if (dtd.$block[tagName]) {
  21183. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21184. range = me.selection.getRange();
  21185. if (!range.collapsed) {
  21186. range.collapse();
  21187. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21188. return node.getAttribute('label') == obj.label;
  21189. }, true);
  21190. var pNode = me.document.createElement('p');
  21191. domUtils.insertAfter(node, pNode);
  21192. domUtils.fillNode(me.document, pNode);
  21193. range.setStart(pNode, 0).setCursor();
  21194. }
  21195. } else {
  21196. range = me.selection.getRange();
  21197. if (range.collapsed) {
  21198. node = me.document.createElement(tagName);
  21199. domUtils.setAttributes(node, tmpObj);
  21200. range.insertNode(node).setStart(node, 0).setCursor();
  21201. return;
  21202. }
  21203. bk = range.createBookmark();
  21204. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21205. }
  21206. }
  21207. },
  21208. queryCommandValue : function() {
  21209. var parent = domUtils.filterNodeList(
  21210. this.selection.getStartElementPath(),
  21211. function(node){return node.getAttribute('label')}
  21212. );
  21213. return parent ? parent.getAttribute('label') : '';
  21214. }
  21215. };
  21216. //当去掉customstyle是,如果是块元素,用p代替
  21217. me.addListener('keyup', function(type, evt) {
  21218. var keyCode = evt.keyCode || evt.which;
  21219. if (keyCode == 32 || keyCode == 13) {
  21220. var range = me.selection.getRange();
  21221. if (range.collapsed) {
  21222. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21223. return node.getAttribute('label');
  21224. }, true);
  21225. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21226. var p = me.document.createElement('p');
  21227. domUtils.insertAfter(node, p);
  21228. domUtils.fillNode(me.document, p);
  21229. domUtils.remove(node);
  21230. range.setStart(p, 0).setCursor();
  21231. }
  21232. }
  21233. }
  21234. });
  21235. };
  21236. // plugins/catchremoteimage.js
  21237. ///import core
  21238. ///commands 远程图片抓取
  21239. ///commandsName catchRemoteImage,catchremoteimageenable
  21240. ///commandsTitle 远程图片抓取
  21241. /**
  21242. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21243. */
  21244. UE.plugins['catchremoteimage'] = function () {
  21245. var me = this,
  21246. ajax = UE.ajax;
  21247. /* 设置默认值 */
  21248. if (me.options.catchRemoteImageEnable === false) return;
  21249. me.setOpt({
  21250. catchRemoteImageEnable: false
  21251. });
  21252. me.addListener("afterpaste", function () {
  21253. me.fireEvent("catchRemoteImage");
  21254. });
  21255. me.addListener("catchRemoteImage", function () {
  21256. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21257. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21258. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21259. catcherFieldName = me.getOpt('catcherFieldName');
  21260. var remoteImages = [],
  21261. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21262. test = function (src, urls) {
  21263. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21264. return true;
  21265. }
  21266. if (urls) {
  21267. for (var j = 0, url; url = urls[j++];) {
  21268. if (src.indexOf(url) !== -1) {
  21269. return true;
  21270. }
  21271. }
  21272. }
  21273. return false;
  21274. };
  21275. for (var i = 0, ci; ci = imgs[i++];) {
  21276. if (ci.getAttribute("word_img")) {
  21277. continue;
  21278. }
  21279. var src = ci.getAttribute("_src") || ci.src || "";
  21280. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21281. remoteImages.push(src);
  21282. }
  21283. }
  21284. if (remoteImages.length) {
  21285. catchremoteimage(remoteImages, {
  21286. //成功抓取
  21287. success: function (r) {
  21288. try {
  21289. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21290. } catch (e) {
  21291. return;
  21292. }
  21293. /* 获取源路径和新路径 */
  21294. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21295. for (i = 0; ci = imgs[i++];) {
  21296. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21297. for (j = 0; cj = list[j++];) {
  21298. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21299. newSrc = catcherUrlPrefix + cj.url;
  21300. domUtils.setAttributes(ci, {
  21301. "src": newSrc,
  21302. "_src": newSrc
  21303. });
  21304. break;
  21305. }
  21306. }
  21307. }
  21308. me.fireEvent('catchremotesuccess')
  21309. },
  21310. //回调失败,本次请求超时
  21311. error: function () {
  21312. me.fireEvent("catchremoteerror");
  21313. }
  21314. });
  21315. }
  21316. function catchremoteimage(imgs, callbacks) {
  21317. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21318. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21319. isJsonp = utils.isCrossDomainUrl(url),
  21320. opt = {
  21321. 'method': 'POST',
  21322. 'dataType': isJsonp ? 'jsonp':'',
  21323. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21324. 'onsuccess': callbacks["success"],
  21325. 'onerror': callbacks["error"]
  21326. };
  21327. opt[catcherFieldName] = imgs;
  21328. ajax.request(url, opt);
  21329. }
  21330. });
  21331. };
  21332. // plugins/snapscreen.js
  21333. /**
  21334. * 截屏插件,为UEditor提供插入支持
  21335. * @file
  21336. * @since 1.4.2
  21337. */
  21338. UE.plugin.register('snapscreen', function (){
  21339. var me = this;
  21340. var snapplugin;
  21341. function getLocation(url){
  21342. var search,
  21343. a = document.createElement('a'),
  21344. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21345. a.href = url;
  21346. if (browser.ie) {
  21347. a.href = a.href;
  21348. }
  21349. search = a.search;
  21350. if (params) {
  21351. search = search + (search.indexOf('?') == -1 ? '?':'&')+ params;
  21352. search = search.replace(/[&]+/ig, '&');
  21353. }
  21354. return {
  21355. 'port': a.port,
  21356. 'hostname': a.hostname,
  21357. 'path': a.pathname + search || + a.hash
  21358. }
  21359. }
  21360. return {
  21361. commands:{
  21362. /**
  21363. * 字体背景颜色
  21364. * @command snapscreen
  21365. * @method execCommand
  21366. * @param { String } cmd 命令字符串
  21367. * @example
  21368. * ```javascript
  21369. * editor.execCommand('snapscreen');
  21370. * ```
  21371. */
  21372. 'snapscreen':{
  21373. execCommand:function (cmd) {
  21374. var url, local, res;
  21375. var lang = me.getLang("snapScreen_plugin");
  21376. if(!snapplugin){
  21377. var container = me.container;
  21378. var doc = me.container.ownerDocument || me.container.document;
  21379. snapplugin = doc.createElement("object");
  21380. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21381. return;
  21382. }
  21383. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21384. snapplugin.setAttribute("width","0");
  21385. snapplugin.setAttribute("height","0");
  21386. container.appendChild(snapplugin);
  21387. }
  21388. function onSuccess(rs){
  21389. try{
  21390. rs = eval("("+ rs +")");
  21391. if(rs.state == 'SUCCESS'){
  21392. var opt = me.options;
  21393. me.execCommand('insertimage', {
  21394. src: opt.snapscreenUrlPrefix + rs.url,
  21395. _src: opt.snapscreenUrlPrefix + rs.url,
  21396. alt: rs.title || '',
  21397. floatStyle: opt.snapscreenImgAlign
  21398. });
  21399. } else {
  21400. alert(rs.state);
  21401. }
  21402. }catch(e){
  21403. alert(lang.callBackErrorMsg);
  21404. }
  21405. }
  21406. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21407. local = getLocation(url);
  21408. setTimeout(function () {
  21409. try{
  21410. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21411. }catch(e){
  21412. me.ui._dialogs['snapscreenDialog'].open();
  21413. return;
  21414. }
  21415. onSuccess(res);
  21416. }, 50);
  21417. },
  21418. queryCommandState: function(){
  21419. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21420. }
  21421. }
  21422. }
  21423. }
  21424. });
  21425. // plugins/insertparagraph.js
  21426. /**
  21427. * 插入段落
  21428. * @file
  21429. * @since 1.2.6.1
  21430. */
  21431. /**
  21432. * 插入段落
  21433. * @command insertparagraph
  21434. * @method execCommand
  21435. * @param { String } cmd 命令字符串
  21436. * @example
  21437. * ```javascript
  21438. * //editor是编辑器实例
  21439. * editor.execCommand( 'insertparagraph' );
  21440. * ```
  21441. */
  21442. UE.commands['insertparagraph'] = {
  21443. execCommand : function( cmdName,front) {
  21444. var me = this,
  21445. range = me.selection.getRange(),
  21446. start = range.startContainer,tmpNode;
  21447. while(start ){
  21448. if(domUtils.isBody(start)){
  21449. break;
  21450. }
  21451. tmpNode = start;
  21452. start = start.parentNode;
  21453. }
  21454. if(tmpNode){
  21455. var p = me.document.createElement('p');
  21456. if(front){
  21457. tmpNode.parentNode.insertBefore(p,tmpNode)
  21458. }else{
  21459. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21460. }
  21461. domUtils.fillNode(me.document,p);
  21462. range.setStart(p,0).setCursor(false,true);
  21463. }
  21464. }
  21465. };
  21466. // plugins/webapp.js
  21467. /**
  21468. * 百度应用
  21469. * @file
  21470. * @since 1.2.6.1
  21471. */
  21472. /**
  21473. * 插入百度应用
  21474. * @command webapp
  21475. * @method execCommand
  21476. * @remind 需要百度APPKey
  21477. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21478. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21479. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21480. * @example
  21481. * ```javascript
  21482. * //editor是编辑器实例
  21483. * //在编辑器里插入一个“植物大战僵尸”的APP
  21484. * editor.execCommand( 'webapp' , {
  21485. * title: '植物大战僵尸',
  21486. * width: 560,
  21487. * height: 465,
  21488. * logo: '应用展示的图片',
  21489. * url: '百度应用的地址'
  21490. * } );
  21491. * ```
  21492. */
  21493. //UE.plugins['webapp'] = function () {
  21494. // var me = this;
  21495. // function createInsertStr( obj, toIframe, addParagraph ) {
  21496. // return !toIframe ?
  21497. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21498. // ' 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 + '" />' +
  21499. // (addParagraph ? '</p>' : '')
  21500. // :
  21501. // '<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>';
  21502. // }
  21503. //
  21504. // function switchImgAndIframe( img2frame ) {
  21505. // var tmpdiv,
  21506. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21507. // for ( var i = 0, node; node = nodes[i++]; ) {
  21508. // if ( node.className != "edui-faked-webapp" ){
  21509. // continue;
  21510. // }
  21511. // tmpdiv = me.document.createElement( "div" );
  21512. // 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 );
  21513. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21514. // }
  21515. // }
  21516. //
  21517. // me.addListener( "beforegetcontent", function () {
  21518. // switchImgAndIframe( true );
  21519. // } );
  21520. // me.addListener( 'aftersetcontent', function () {
  21521. // switchImgAndIframe( false );
  21522. // } );
  21523. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21524. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21525. // return;
  21526. // }
  21527. // switchImgAndIframe( false );
  21528. // } );
  21529. //
  21530. // me.commands['webapp'] = {
  21531. // execCommand:function ( cmd, obj ) {
  21532. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21533. // }
  21534. // };
  21535. //};
  21536. UE.plugin.register('webapp', function (){
  21537. var me = this;
  21538. function createInsertStr(obj,toEmbed){
  21539. return !toEmbed ?
  21540. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21541. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21542. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21543. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21544. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21545. '/>'
  21546. :
  21547. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21548. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21549. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21550. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21551. }
  21552. return {
  21553. outputRule: function(root){
  21554. utils.each(root.getNodesByTagName('img'),function(node){
  21555. var html;
  21556. if(node.getAttr('class') == 'edui-faked-webapp'){
  21557. html = createInsertStr({
  21558. title:node.getAttr('title'),
  21559. 'width':node.getAttr('width'),
  21560. 'height':node.getAttr('height'),
  21561. 'align':node.getAttr('align'),
  21562. 'cssfloat':node.getStyle('float'),
  21563. 'url':node.getAttr("_url"),
  21564. 'logo':node.getAttr('_logo_url')
  21565. },true);
  21566. var embed = UE.uNode.createElement(html);
  21567. node.parentNode.replaceChild(embed,node);
  21568. }
  21569. })
  21570. },
  21571. inputRule:function(root){
  21572. utils.each(root.getNodesByTagName('iframe'),function(node){
  21573. if(node.getAttr('class') == 'edui-faked-webapp'){
  21574. var img = UE.uNode.createElement(createInsertStr({
  21575. title:node.getAttr('title'),
  21576. 'width':node.getAttr('width'),
  21577. 'height':node.getAttr('height'),
  21578. 'align':node.getAttr('align'),
  21579. 'cssfloat':node.getStyle('float'),
  21580. 'url':node.getAttr("src"),
  21581. 'logo':node.getAttr('logo_url')
  21582. }));
  21583. node.parentNode.replaceChild(img,node);
  21584. }
  21585. })
  21586. },
  21587. commands:{
  21588. /**
  21589. * 插入百度应用
  21590. * @command webapp
  21591. * @method execCommand
  21592. * @remind 需要百度APPKey
  21593. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21594. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21595. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21596. * @example
  21597. * ```javascript
  21598. * //editor是编辑器实例
  21599. * //在编辑器里插入一个“植物大战僵尸”的APP
  21600. * editor.execCommand( 'webapp' , {
  21601. * title: '植物大战僵尸',
  21602. * width: 560,
  21603. * height: 465,
  21604. * logo: '应用展示的图片',
  21605. * url: '百度应用的地址'
  21606. * } );
  21607. * ```
  21608. */
  21609. 'webapp':{
  21610. execCommand:function (cmd, obj) {
  21611. var me = this,
  21612. str = createInsertStr(utils.extend(obj,{
  21613. align:'none'
  21614. }), false);
  21615. me.execCommand("inserthtml",str);
  21616. },
  21617. queryCommandState:function () {
  21618. var me = this,
  21619. img = me.selection.getRange().getClosedNode(),
  21620. flag = img && (img.className == "edui-faked-webapp");
  21621. return flag ? 1 : 0;
  21622. }
  21623. }
  21624. }
  21625. }
  21626. });
  21627. // plugins/template.js
  21628. ///import core
  21629. ///import plugins\inserthtml.js
  21630. ///import plugins\cleardoc.js
  21631. ///commands 模板
  21632. ///commandsName template
  21633. ///commandsTitle 模板
  21634. ///commandsDialog dialogs\template
  21635. UE.plugins['template'] = function () {
  21636. UE.commands['template'] = {
  21637. execCommand:function (cmd, obj) {
  21638. obj.html && this.execCommand("inserthtml", obj.html);
  21639. }
  21640. };
  21641. this.addListener("click", function (type, evt) {
  21642. var el = evt.target || evt.srcElement,
  21643. range = this.selection.getRange();
  21644. var tnode = domUtils.findParent(el, function (node) {
  21645. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21646. return node;
  21647. }
  21648. }, true);
  21649. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21650. });
  21651. this.addListener("keydown", function (type, evt) {
  21652. var range = this.selection.getRange();
  21653. if (!range.collapsed) {
  21654. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21655. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21656. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21657. return node;
  21658. }
  21659. }, true);
  21660. if (tnode) {
  21661. domUtils.removeClasses(tnode, ["ue_t"]);
  21662. }
  21663. }
  21664. }
  21665. });
  21666. };
  21667. // plugins/music.js
  21668. /**
  21669. * 插入音乐命令
  21670. * @file
  21671. */
  21672. UE.plugin.register('music', function (){
  21673. var me = this;
  21674. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21675. return !toEmbed ?
  21676. '<img ' +
  21677. (align && !cssfloat? 'align="' + align + '"' : '') +
  21678. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21679. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21680. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21681. :
  21682. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21683. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21684. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21685. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21686. }
  21687. return {
  21688. outputRule: function(root){
  21689. utils.each(root.getNodesByTagName('img'),function(node){
  21690. var html;
  21691. if(node.getAttr('class') == 'edui-faked-music'){
  21692. var cssfloat = node.getStyle('float');
  21693. var align = node.getAttr('align');
  21694. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21695. var embed = UE.uNode.createElement(html);
  21696. node.parentNode.replaceChild(embed,node);
  21697. }
  21698. })
  21699. },
  21700. inputRule:function(root){
  21701. utils.each(root.getNodesByTagName('embed'),function(node){
  21702. if(node.getAttr('class') == 'edui-faked-music'){
  21703. var cssfloat = node.getStyle('float');
  21704. var align = node.getAttr('align');
  21705. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21706. var img = UE.uNode.createElement(html);
  21707. node.parentNode.replaceChild(img,node);
  21708. }
  21709. })
  21710. },
  21711. commands:{
  21712. /**
  21713. * 插入音乐
  21714. * @command music
  21715. * @method execCommand
  21716. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21717. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21718. * @example
  21719. * ```javascript
  21720. * //editor是编辑器实例
  21721. * //在编辑器里插入一个“植物大战僵尸”的APP
  21722. * editor.execCommand( 'music' , {
  21723. * width: 400,
  21724. * height: 95,
  21725. * align: "center",
  21726. * url: "音乐地址"
  21727. * } );
  21728. * ```
  21729. */
  21730. 'music':{
  21731. execCommand:function (cmd, musicObj) {
  21732. var me = this,
  21733. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21734. me.execCommand("inserthtml",str);
  21735. },
  21736. queryCommandState:function () {
  21737. var me = this,
  21738. img = me.selection.getRange().getClosedNode(),
  21739. flag = img && (img.className == "edui-faked-music");
  21740. return flag ? 1 : 0;
  21741. }
  21742. }
  21743. }
  21744. }
  21745. });
  21746. // plugins/autoupload.js
  21747. /**
  21748. * @description
  21749. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21750. * 2.插入粘贴板的图片,自动上传并插入到选区
  21751. * @author Jinqn
  21752. * @date 2013-10-14
  21753. */
  21754. UE.plugin.register('autoupload', function (){
  21755. function sendAndInsertFile(file, editor) {
  21756. var me = editor;
  21757. //模拟数据
  21758. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21759. loadingHtml, errorHandler, successHandler,
  21760. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21761. loadingId = 'loading_' + (+new Date()).toString(36);
  21762. fieldName = me.getOpt(filetype + 'FieldName');
  21763. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21764. maxSize = me.getOpt(filetype + 'MaxSize');
  21765. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21766. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21767. errorHandler = function(title) {
  21768. var loader = me.document.getElementById(loadingId);
  21769. loader && domUtils.remove(loader);
  21770. me.fireEvent('showmessage', {
  21771. 'id': loadingId,
  21772. 'content': title,
  21773. 'type': 'error',
  21774. 'timeout': 4000
  21775. });
  21776. };
  21777. if (filetype == 'image') {
  21778. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21779. me.options.themePath + me.options.theme +
  21780. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21781. successHandler = function(data) {
  21782. var link = urlPrefix + data.url,
  21783. loader = me.document.getElementById(loadingId);
  21784. if (loader) {
  21785. loader.setAttribute('src', link);
  21786. loader.setAttribute('_src', link);
  21787. loader.setAttribute('title', data.title || '');
  21788. loader.setAttribute('alt', data.original || '');
  21789. loader.removeAttribute('id');
  21790. domUtils.removeClasses(loader, 'loadingclass');
  21791. }
  21792. };
  21793. } else {
  21794. loadingHtml = '<p>' +
  21795. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21796. me.options.themePath + me.options.theme +
  21797. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21798. '</p>';
  21799. successHandler = function(data) {
  21800. var link = urlPrefix + data.url,
  21801. loader = me.document.getElementById(loadingId);
  21802. var rng = me.selection.getRange(),
  21803. bk = rng.createBookmark();
  21804. rng.selectNode(loader).select();
  21805. me.execCommand('insertfile', {'url': link});
  21806. rng.moveToBookmark(bk).select();
  21807. };
  21808. }
  21809. /* 插入loading的占位符 */
  21810. me.execCommand('inserthtml', loadingHtml);
  21811. /* 判断后端配置是否没有加载成功 */
  21812. if (!me.getOpt(filetype + 'ActionName')) {
  21813. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21814. return;
  21815. }
  21816. /* 判断文件大小是否超出限制 */
  21817. if(file.size > maxSize) {
  21818. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21819. return;
  21820. }
  21821. /* 判断文件格式是否超出允许 */
  21822. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21823. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21824. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21825. return;
  21826. }
  21827. /* 创建Ajax并提交 */
  21828. var xhr = new XMLHttpRequest(),
  21829. fd = new FormData(),
  21830. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21831. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21832. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21833. fd.append('type', 'ajax');
  21834. xhr.open("post", url, true);
  21835. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21836. xhr.addEventListener('load', function (e) {
  21837. try{
  21838. var json = (new Function("return " + utils.trim(e.target.response)))();
  21839. if (json.state == 'SUCCESS' && json.url) {
  21840. successHandler(json);
  21841. } else {
  21842. errorHandler(json.state);
  21843. }
  21844. }catch(er){
  21845. errorHandler(me.getLang('autoupload.loadError'));
  21846. }
  21847. });
  21848. xhr.send(fd);
  21849. }
  21850. function getPasteImage(e){
  21851. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21852. }
  21853. function getDropImage(e){
  21854. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21855. }
  21856. return {
  21857. outputRule: function(root){
  21858. utils.each(root.getNodesByTagName('img'),function(n){
  21859. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21860. n.parentNode.removeChild(n);
  21861. }
  21862. });
  21863. utils.each(root.getNodesByTagName('p'),function(n){
  21864. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21865. n.parentNode.removeChild(n);
  21866. }
  21867. });
  21868. },
  21869. bindEvents:{
  21870. //插入粘贴板的图片,拖放插入图片
  21871. 'ready':function(e){
  21872. var me = this;
  21873. if(window.FormData && window.FileReader) {
  21874. domUtils.on(me.body, 'paste drop', function(e){
  21875. var hasImg = false,
  21876. items;
  21877. //获取粘贴板文件列表或者拖放文件列表
  21878. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21879. if(items){
  21880. var len = items.length,
  21881. file;
  21882. while (len--){
  21883. file = items[len];
  21884. if(file.getAsFile) file = file.getAsFile();
  21885. if(file && file.size > 0) {
  21886. sendAndInsertFile(file, me);
  21887. hasImg = true;
  21888. }
  21889. }
  21890. hasImg && e.preventDefault();
  21891. }
  21892. });
  21893. //取消拖放图片时出现的文字光标位置提示
  21894. domUtils.on(me.body, 'dragover', function (e) {
  21895. if(e.dataTransfer.types[0] == 'Files') {
  21896. e.preventDefault();
  21897. }
  21898. });
  21899. //设置loading的样式
  21900. utils.cssRule('loading',
  21901. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21902. + this.options.themePath
  21903. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21904. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21905. + this.options.themePath
  21906. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21907. '}',
  21908. this.document);
  21909. }
  21910. }
  21911. }
  21912. }
  21913. });
  21914. // plugins/autosave.js
  21915. UE.plugin.register('autosave', function (){
  21916. var me = this,
  21917. //无限循环保护
  21918. lastSaveTime = new Date(),
  21919. //最小保存间隔时间
  21920. MIN_TIME = 20,
  21921. //auto save key
  21922. saveKey = null;
  21923. function save ( editor ) {
  21924. var saveData;
  21925. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21926. return;
  21927. }
  21928. if ( !editor.hasContents() ) {
  21929. //这里不能调用命令来删除, 会造成事件死循环
  21930. saveKey && me.removePreferences( saveKey );
  21931. return;
  21932. }
  21933. lastSaveTime = new Date();
  21934. editor._saveFlag = null;
  21935. saveData = me.body.innerHTML;
  21936. if ( editor.fireEvent( "beforeautosave", {
  21937. content: saveData
  21938. } ) === false ) {
  21939. return;
  21940. }
  21941. me.setPreferences( saveKey, saveData );
  21942. editor.fireEvent( "afterautosave", {
  21943. content: saveData
  21944. } );
  21945. }
  21946. return {
  21947. defaultOptions: {
  21948. //默认间隔时间
  21949. saveInterval: 500,
  21950. enableAutoSave: true // HaoChuan9421
  21951. },
  21952. bindEvents:{
  21953. 'ready':function(){
  21954. var _suffix = "-drafts-data",
  21955. key = null;
  21956. if ( me.key ) {
  21957. key = me.key + _suffix;
  21958. } else {
  21959. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21960. }
  21961. //页面地址+编辑器ID 保持唯一
  21962. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21963. },
  21964. 'contentchange': function () {
  21965. // HaoChuan9421
  21966. if (!me.getOpt('enableAutoSave')) {
  21967. return;
  21968. }
  21969. if ( !saveKey ) {
  21970. return;
  21971. }
  21972. if ( me._saveFlag ) {
  21973. window.clearTimeout( me._saveFlag );
  21974. }
  21975. if ( me.options.saveInterval > 0 ) {
  21976. me._saveFlag = window.setTimeout( function () {
  21977. save( me );
  21978. }, me.options.saveInterval );
  21979. } else {
  21980. save(me);
  21981. }
  21982. }
  21983. },
  21984. commands:{
  21985. 'clearlocaldata':{
  21986. execCommand:function (cmd, name) {
  21987. if ( saveKey && me.getPreferences( saveKey ) ) {
  21988. me.removePreferences( saveKey )
  21989. }
  21990. },
  21991. notNeedUndo: true,
  21992. ignoreContentChange:true
  21993. },
  21994. 'getlocaldata':{
  21995. execCommand:function (cmd, name) {
  21996. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21997. },
  21998. notNeedUndo: true,
  21999. ignoreContentChange:true
  22000. },
  22001. 'drafts':{
  22002. execCommand:function (cmd, name) {
  22003. if ( saveKey ) {
  22004. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  22005. me.focus(true);
  22006. }
  22007. },
  22008. queryCommandState: function () {
  22009. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  22010. },
  22011. notNeedUndo: true,
  22012. ignoreContentChange:true
  22013. }
  22014. }
  22015. }
  22016. });
  22017. // plugins/charts.js
  22018. UE.plugin.register('charts', function (){
  22019. var me = this;
  22020. return {
  22021. bindEvents: {
  22022. 'chartserror': function () {
  22023. }
  22024. },
  22025. commands:{
  22026. 'charts': {
  22027. execCommand: function ( cmd, data ) {
  22028. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22029. flagText = [],
  22030. config = {};
  22031. if ( !tableNode ) {
  22032. return false;
  22033. }
  22034. if ( !validData( tableNode ) ) {
  22035. me.fireEvent( "chartserror" );
  22036. return false;
  22037. }
  22038. config.title = data.title || '';
  22039. config.subTitle = data.subTitle || '';
  22040. config.xTitle = data.xTitle || '';
  22041. config.yTitle = data.yTitle || '';
  22042. config.suffix = data.suffix || '';
  22043. config.tip = data.tip || '';
  22044. //数据对齐方式
  22045. config.dataFormat = data.tableDataFormat || '';
  22046. //图表类型
  22047. config.chartType = data.chartType || 0;
  22048. for ( var key in config ) {
  22049. if ( !config.hasOwnProperty( key ) ) {
  22050. continue;
  22051. }
  22052. flagText.push( key+":"+config[ key ] );
  22053. }
  22054. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  22055. domUtils.addClass( tableNode, "edui-charts-table" );
  22056. },
  22057. queryCommandState: function ( cmd, name ) {
  22058. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22059. return tableNode && validData( tableNode ) ? 0 : -1;
  22060. }
  22061. }
  22062. },
  22063. inputRule:function(root){
  22064. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22065. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22066. tableNode.setAttr("style");
  22067. }
  22068. })
  22069. },
  22070. outputRule:function(root){
  22071. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22072. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22073. tableNode.setAttr("style", "display: none;");
  22074. }
  22075. })
  22076. }
  22077. }
  22078. function validData ( table ) {
  22079. var firstRows = null,
  22080. cellCount = 0;
  22081. //行数不够
  22082. if ( table.rows.length < 2 ) {
  22083. return false;
  22084. }
  22085. //列数不够
  22086. if ( table.rows[0].cells.length < 2 ) {
  22087. return false;
  22088. }
  22089. //第一行所有cell必须是th
  22090. firstRows = table.rows[ 0 ].cells;
  22091. cellCount = firstRows.length;
  22092. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22093. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22094. return false;
  22095. }
  22096. }
  22097. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22098. //每行单元格数不匹配, 返回false
  22099. if ( row.cells.length != cellCount ) {
  22100. return false;
  22101. }
  22102. //第一列不是th也返回false
  22103. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22104. return false;
  22105. }
  22106. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22107. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22108. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22109. //必须是数字
  22110. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22111. return false;
  22112. }
  22113. }
  22114. }
  22115. return true;
  22116. }
  22117. });
  22118. // plugins/section.js
  22119. /**
  22120. * 目录大纲支持插件
  22121. * @file
  22122. * @since 1.3.0
  22123. */
  22124. UE.plugin.register('section', function (){
  22125. /* 目录节点对象 */
  22126. function Section(option){
  22127. this.tag = '';
  22128. this.level = -1,
  22129. this.dom = null;
  22130. this.nextSection = null;
  22131. this.previousSection = null;
  22132. this.parentSection = null;
  22133. this.startAddress = [];
  22134. this.endAddress = [];
  22135. this.children = [];
  22136. }
  22137. function getSection(option) {
  22138. var section = new Section();
  22139. return utils.extend(section, option);
  22140. }
  22141. function getNodeFromAddress(startAddress, root) {
  22142. var current = root;
  22143. for(var i = 0;i < startAddress.length; i++) {
  22144. if(!current.childNodes) return null;
  22145. current = current.childNodes[startAddress[i]];
  22146. }
  22147. return current;
  22148. }
  22149. var me = this;
  22150. return {
  22151. bindMultiEvents:{
  22152. type: 'aftersetcontent afterscencerestore',
  22153. handler: function(){
  22154. me.fireEvent('updateSections');
  22155. }
  22156. },
  22157. bindEvents:{
  22158. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22159. 'ready': function (){
  22160. me.fireEvent('updateSections');
  22161. domUtils.on(me.body, 'drop paste', function(){
  22162. me.fireEvent('updateSections');
  22163. });
  22164. },
  22165. /* 执行paragraph命令之后 */
  22166. 'afterexeccommand': function (type, cmd) {
  22167. if(cmd == 'paragraph') {
  22168. me.fireEvent('updateSections');
  22169. }
  22170. },
  22171. /* 部分键盘操作,触发updateSections事件 */
  22172. 'keyup': function (type, e) {
  22173. var me = this,
  22174. range = me.selection.getRange();
  22175. if(range.collapsed != true) {
  22176. me.fireEvent('updateSections');
  22177. } else {
  22178. var keyCode = e.keyCode || e.which;
  22179. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22180. me.fireEvent('updateSections');
  22181. }
  22182. }
  22183. }
  22184. },
  22185. commands:{
  22186. 'getsections': {
  22187. execCommand: function (cmd, levels) {
  22188. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22189. for (var i = 0; i < levelFn.length; i++) {
  22190. if (typeof levelFn[i] == 'string') {
  22191. levelFn[i] = function(fn){
  22192. return function(node){
  22193. return node.tagName == fn.toUpperCase()
  22194. };
  22195. }(levelFn[i]);
  22196. } else if (typeof levelFn[i] != 'function') {
  22197. levelFn[i] = function (node) {
  22198. return null;
  22199. }
  22200. }
  22201. }
  22202. function getSectionLevel(node) {
  22203. for (var i = 0; i < levelFn.length; i++) {
  22204. if (levelFn[i](node)) return i;
  22205. }
  22206. return -1;
  22207. }
  22208. var me = this,
  22209. Directory = getSection({'level':-1, 'title':'root'}),
  22210. previous = Directory;
  22211. function traversal(node, Directory) {
  22212. var level,
  22213. tmpSection = null,
  22214. parent,
  22215. child,
  22216. children = node.childNodes;
  22217. for (var i = 0, len = children.length; i < len; i++) {
  22218. child = children[i];
  22219. level = getSectionLevel(child);
  22220. if (level >= 0) {
  22221. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22222. current = getSection({
  22223. 'tag': child.tagName,
  22224. 'title': child.innerText || child.textContent || '',
  22225. 'level': level,
  22226. 'dom': child,
  22227. 'startAddress': utils.clone(address, []),
  22228. 'endAddress': utils.clone(address, []),
  22229. 'children': []
  22230. });
  22231. previous.nextSection = current;
  22232. current.previousSection = previous;
  22233. parent = previous;
  22234. while(level <= parent.level){
  22235. parent = parent.parentSection;
  22236. }
  22237. current.parentSection = parent;
  22238. parent.children.push(current);
  22239. tmpSection = previous = current;
  22240. } else {
  22241. child.nodeType === 1 && traversal(child, Directory);
  22242. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22243. }
  22244. }
  22245. }
  22246. traversal(me.body, Directory);
  22247. return Directory;
  22248. },
  22249. notNeedUndo: true
  22250. },
  22251. 'movesection': {
  22252. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22253. var me = this,
  22254. targetAddress,
  22255. target;
  22256. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22257. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22258. target = getNodeFromAddress(targetAddress, me.body);
  22259. /* 判断目标地址是否被源章节包含 */
  22260. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22261. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22262. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22263. current,
  22264. nextNode;
  22265. if(isAfter) {
  22266. current = endNode;
  22267. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22268. nextNode = current.previousSibling;
  22269. domUtils.insertAfter(target, current);
  22270. if(current == startNode) break;
  22271. current = nextNode;
  22272. }
  22273. } else {
  22274. current = startNode;
  22275. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22276. nextNode = current.nextSibling;
  22277. target.parentNode.insertBefore(current, target);
  22278. if(current == endNode) break;
  22279. current = nextNode;
  22280. }
  22281. }
  22282. me.fireEvent('updateSections');
  22283. /* 获取地址的包含关系 */
  22284. function isContainsAddress(startAddress, endAddress, addressTarget){
  22285. var isAfterStartAddress = false,
  22286. isBeforeEndAddress = false;
  22287. for(var i = 0; i< startAddress.length; i++){
  22288. if(i >= addressTarget.length) break;
  22289. if(addressTarget[i] > startAddress[i]) {
  22290. isAfterStartAddress = true;
  22291. break;
  22292. } else if(addressTarget[i] < startAddress[i]) {
  22293. break;
  22294. }
  22295. }
  22296. for(var i = 0; i< endAddress.length; i++){
  22297. if(i >= addressTarget.length) break;
  22298. if(addressTarget[i] < startAddress[i]) {
  22299. isBeforeEndAddress = true;
  22300. break;
  22301. } else if(addressTarget[i] > startAddress[i]) {
  22302. break;
  22303. }
  22304. }
  22305. return isAfterStartAddress && isBeforeEndAddress;
  22306. }
  22307. }
  22308. },
  22309. 'deletesection': {
  22310. execCommand: function (cmd, section, keepChildren) {
  22311. var me = this;
  22312. if(!section) return;
  22313. function getNodeFromAddress(startAddress) {
  22314. var current = me.body;
  22315. for(var i = 0;i < startAddress.length; i++) {
  22316. if(!current.childNodes) return null;
  22317. current = current.childNodes[startAddress[i]];
  22318. }
  22319. return current;
  22320. }
  22321. var startNode = getNodeFromAddress(section.startAddress),
  22322. endNode = getNodeFromAddress(section.endAddress),
  22323. current = startNode,
  22324. nextNode;
  22325. if(!keepChildren) {
  22326. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22327. nextNode = current.nextSibling;
  22328. domUtils.remove(current);
  22329. current = nextNode;
  22330. }
  22331. } else {
  22332. domUtils.remove(current);
  22333. }
  22334. me.fireEvent('updateSections');
  22335. }
  22336. },
  22337. 'selectsection': {
  22338. execCommand: function (cmd, section) {
  22339. if(!section && !section.dom) return false;
  22340. var me = this,
  22341. range = me.selection.getRange(),
  22342. address = {
  22343. 'startAddress':utils.clone(section.startAddress, []),
  22344. 'endAddress':utils.clone(section.endAddress, [])
  22345. };
  22346. address.endAddress[address.endAddress.length - 1]++;
  22347. range.moveToAddress(address).select().scrollToView();
  22348. return true;
  22349. },
  22350. notNeedUndo: true
  22351. },
  22352. 'scrolltosection': {
  22353. execCommand: function (cmd, section) {
  22354. if(!section && !section.dom) return false;
  22355. var me = this,
  22356. range = me.selection.getRange(),
  22357. address = {
  22358. 'startAddress':section.startAddress,
  22359. 'endAddress':section.endAddress
  22360. };
  22361. address.endAddress[address.endAddress.length - 1]++;
  22362. range.moveToAddress(address).scrollToView();
  22363. return true;
  22364. },
  22365. notNeedUndo: true
  22366. }
  22367. }
  22368. }
  22369. });
  22370. // plugins/simpleupload.js
  22371. /**
  22372. * @description
  22373. * 简单上传:点击按钮,直接选择文件上传。
  22374. * 原 UEditor 作者使用了 form 表单 + iframe 的方式上传
  22375. * 但由于同源策略的限制,父页面无法访问跨域的 iframe 内容
  22376. * 导致无法获取接口返回的数据,使得单图上传无法在跨域的情况下使用
  22377. * 这里改为普通的XHR上传,兼容到IE10+
  22378. * @author HaoChuan9421 <hc199421@gmail.com>
  22379. * @date 2018-12-20
  22380. */
  22381. UE.plugin.register('simpleupload', function() {
  22382. var me = this,
  22383. containerBtn,
  22384. timestrap = (+new Date()).toString(36);
  22385. function initUploadBtn() {
  22386. var w = containerBtn.offsetWidth || 20,
  22387. h = containerBtn.offsetHeight || 20,
  22388. btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
  22389. var form = document.createElement('form');
  22390. var input = document.createElement('input');
  22391. form.id = 'edui_form_' + timestrap;
  22392. form.enctype = 'multipart/form-data';
  22393. form.style = btnStyle;
  22394. input.id = 'edui_input_' + timestrap;
  22395. input.type = 'file'
  22396. input.accept = 'image/*';
  22397. input.name = me.options.imageFieldName;
  22398. input.style = btnStyle;
  22399. form.appendChild(input);
  22400. containerBtn.appendChild(form);
  22401. input.addEventListener('change', function(event) {
  22402. if (!input.value) return;
  22403. var loadingId = 'loading_' + (+new Date()).toString(36);
  22404. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22405. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22406. var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  22407. var allowFiles = me.getOpt('imageAllowFiles');
  22408. me.focus();
  22409. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22410. function showErrorLoader(title) {
  22411. if (loadingId) {
  22412. var loader = me.document.getElementById(loadingId);
  22413. loader && domUtils.remove(loader);
  22414. me.fireEvent('showmessage', {
  22415. 'id': loadingId,
  22416. 'content': title,
  22417. 'type': 'error',
  22418. 'timeout': 4000
  22419. });
  22420. }
  22421. }
  22422. /* 判断后端配置是否没有加载成功 */
  22423. if (!me.getOpt('imageActionName')) {
  22424. showErrorLoader(me.getLang('autoupload.errorLoadConfig'));
  22425. return;
  22426. }
  22427. // 判断文件格式是否错误
  22428. var filename = input.value,
  22429. fileext = filename ? filename.substr(filename.lastIndexOf('.')) : '';
  22430. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22431. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22432. return;
  22433. }
  22434. var xhr = new XMLHttpRequest()
  22435. xhr.open('post', action, true)
  22436. if (me.options.headers && Object.prototype.toString.apply(me.options.headers) === "[object Object]") {
  22437. for (var key in me.options.headers) {
  22438. xhr.setRequestHeader(key, me.options.headers[key])
  22439. }
  22440. }
  22441. xhr.onload = function() {
  22442. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
  22443. var res = JSON.parse(xhr.responseText)
  22444. var link = me.options.imageUrlPrefix + res.url;
  22445. if (res.state == 'SUCCESS' && res.url) {
  22446. loader = me.document.getElementById(loadingId);
  22447. loader.setAttribute('src', link);
  22448. loader.setAttribute('_src', link);
  22449. loader.setAttribute('title', res.title || '');
  22450. loader.setAttribute('alt', res.original || '');
  22451. loader.removeAttribute('id');
  22452. domUtils.removeClasses(loader, 'loadingclass');
  22453. me.fireEvent("contentchange");
  22454. } else {
  22455. showErrorLoader(res.state);
  22456. }
  22457. } else {
  22458. showErrorLoader(me.getLang('simpleupload.loadError'));
  22459. }
  22460. };
  22461. xhr.onerror = function() {
  22462. showErrorLoader(me.getLang('simpleupload.loadError'));
  22463. };
  22464. xhr.send(new FormData(form));
  22465. form.reset();
  22466. })
  22467. }
  22468. return {
  22469. bindEvents: {
  22470. 'ready': function() {
  22471. //设置loading的样式
  22472. utils.cssRule('loading',
  22473. '.loadingclass{display:inline-block;cursor:default;background: url(\'' +
  22474. this.options.themePath +
  22475. this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22476. '.loaderrorclass{display:inline-block;cursor:default;background: url(\'' +
  22477. this.options.themePath +
  22478. this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22479. '}',
  22480. this.document);
  22481. },
  22482. /* 初始化简单上传按钮 */
  22483. 'simpleuploadbtnready': function(type, container) {
  22484. containerBtn = container;
  22485. me.afterConfigReady(initUploadBtn);
  22486. }
  22487. },
  22488. outputRule: function(root) {
  22489. utils.each(root.getNodesByTagName('img'), function(n) {
  22490. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22491. n.parentNode.removeChild(n);
  22492. }
  22493. });
  22494. }
  22495. }
  22496. });
  22497. // plugins/serverparam.js
  22498. /**
  22499. * 服务器提交的额外参数列表设置插件
  22500. * @file
  22501. * @since 1.2.6.1
  22502. */
  22503. UE.plugin.register('serverparam', function (){
  22504. var me = this,
  22505. serverParam = {};
  22506. return {
  22507. commands:{
  22508. /**
  22509. * 修改服务器提交的额外参数列表,清除所有项
  22510. * @command serverparam
  22511. * @method execCommand
  22512. * @param { String } cmd 命令字符串
  22513. * @example
  22514. * ```javascript
  22515. * editor.execCommand('serverparam');
  22516. * editor.queryCommandValue('serverparam'); //返回空
  22517. * ```
  22518. */
  22519. /**
  22520. * 修改服务器提交的额外参数列表,删除指定项
  22521. * @command serverparam
  22522. * @method execCommand
  22523. * @param { String } cmd 命令字符串
  22524. * @param { String } key 要清除的属性
  22525. * @example
  22526. * ```javascript
  22527. * editor.execCommand('serverparam', 'name'); //删除属性name
  22528. * ```
  22529. */
  22530. /**
  22531. * 修改服务器提交的额外参数列表,使用键值添加项
  22532. * @command serverparam
  22533. * @method execCommand
  22534. * @param { String } cmd 命令字符串
  22535. * @param { String } key 要添加的属性
  22536. * @param { String } value 要添加属性的值
  22537. * @example
  22538. * ```javascript
  22539. * editor.execCommand('serverparam', 'name', 'hello');
  22540. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22541. * ```
  22542. */
  22543. /**
  22544. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22545. * @command serverparam
  22546. * @method execCommand
  22547. * @param { String } cmd 命令字符串
  22548. * @param { Object } key 传入的键值对对象
  22549. * @example
  22550. * ```javascript
  22551. * editor.execCommand('serverparam', {'name': 'hello'});
  22552. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22553. * ```
  22554. */
  22555. /**
  22556. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22557. * @command serverparam
  22558. * @method execCommand
  22559. * @param { String } cmd 命令字符串
  22560. * @param { Function } key 自定义获取参数的函数
  22561. * @example
  22562. * ```javascript
  22563. * editor.execCommand('serverparam', function(editor){
  22564. * return {'key': 'value'};
  22565. * });
  22566. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22567. * ```
  22568. */
  22569. /**
  22570. * 获取服务器提交的额外参数列表
  22571. * @command serverparam
  22572. * @method queryCommandValue
  22573. * @param { String } cmd 命令字符串
  22574. * @example
  22575. * ```javascript
  22576. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22577. * ```
  22578. */
  22579. 'serverparam':{
  22580. execCommand:function (cmd, key, value) {
  22581. if (key === undefined || key === null) { //不传参数,清空列表
  22582. serverParam = {};
  22583. } else if (utils.isString(key)) { //传入键值
  22584. if(value === undefined || value === null) {
  22585. delete serverParam[key];
  22586. } else {
  22587. serverParam[key] = value;
  22588. }
  22589. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22590. utils.extend(serverParam, key, true);
  22591. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22592. utils.extend(serverParam, key(), true);
  22593. }
  22594. },
  22595. queryCommandValue: function(){
  22596. return serverParam || {};
  22597. }
  22598. }
  22599. }
  22600. }
  22601. });
  22602. // plugins/insertfile.js
  22603. /**
  22604. * 插入附件
  22605. */
  22606. UE.plugin.register('insertfile', function (){
  22607. var me = this;
  22608. function getFileIcon(url){
  22609. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22610. maps = {
  22611. "rar":"icon_rar.gif",
  22612. "zip":"icon_rar.gif",
  22613. "tar":"icon_rar.gif",
  22614. "gz":"icon_rar.gif",
  22615. "bz2":"icon_rar.gif",
  22616. "doc":"icon_doc.gif",
  22617. "docx":"icon_doc.gif",
  22618. "pdf":"icon_pdf.gif",
  22619. "mp3":"icon_mp3.gif",
  22620. "xls":"icon_xls.gif",
  22621. "chm":"icon_chm.gif",
  22622. "ppt":"icon_ppt.gif",
  22623. "pptx":"icon_ppt.gif",
  22624. "avi":"icon_mv.gif",
  22625. "rmvb":"icon_mv.gif",
  22626. "wmv":"icon_mv.gif",
  22627. "flv":"icon_mv.gif",
  22628. "swf":"icon_mv.gif",
  22629. "rm":"icon_mv.gif",
  22630. "exe":"icon_exe.gif",
  22631. "psd":"icon_psd.gif",
  22632. "txt":"icon_txt.gif",
  22633. "jpg":"icon_jpg.gif",
  22634. "png":"icon_jpg.gif",
  22635. "jpeg":"icon_jpg.gif",
  22636. "gif":"icon_jpg.gif",
  22637. "ico":"icon_jpg.gif",
  22638. "bmp":"icon_jpg.gif"
  22639. };
  22640. return maps[ext] ? maps[ext]:maps['txt'];
  22641. }
  22642. return {
  22643. commands:{
  22644. 'insertfile': {
  22645. execCommand: function (command, filelist){
  22646. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22647. var i, item, icon, title,
  22648. html = '',
  22649. URL = me.getOpt('UEDITOR_HOME_URL'),
  22650. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22651. for (i = 0; i < filelist.length; i++) {
  22652. item = filelist[i];
  22653. icon = iconDir + getFileIcon(item.url);
  22654. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22655. html += '<p style="line-height: 16px;">' +
  22656. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22657. '<a style="font-size:12px; color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22658. '</p>';
  22659. }
  22660. me.execCommand('insertHtml', html);
  22661. }
  22662. }
  22663. }
  22664. }
  22665. });
  22666. // plugins/xssFilter.js
  22667. /**
  22668. * @file xssFilter.js
  22669. * @desc xss过滤器
  22670. * @author robbenmu
  22671. */
  22672. UE.plugins.xssFilter = function() {
  22673. var config = UEDITOR_CONFIG;
  22674. var whitList = config.whitList;
  22675. function filter(node) {
  22676. var tagName = node.tagName;
  22677. var attrs = node.attrs;
  22678. if (!whitList.hasOwnProperty(tagName)) {
  22679. node.parentNode.removeChild(node);
  22680. return false;
  22681. }
  22682. UE.utils.each(attrs, function (val, key) {
  22683. if (whitList[tagName].indexOf(key) === -1) {
  22684. node.setAttr(key);
  22685. }
  22686. });
  22687. }
  22688. // 添加inserthtml\paste等操作用的过滤规则
  22689. if (whitList && config.xssFilterRules) {
  22690. this.options.filterRules = function () {
  22691. var result = {};
  22692. UE.utils.each(whitList, function(val, key) {
  22693. result[key] = function (node) {
  22694. return filter(node);
  22695. };
  22696. });
  22697. return result;
  22698. }();
  22699. }
  22700. var tagList = [];
  22701. UE.utils.each(whitList, function (val, key) {
  22702. tagList.push(key);
  22703. });
  22704. // 添加input过滤规则
  22705. //
  22706. if (whitList && config.inputXssFilter) {
  22707. this.addInputRule(function (root) {
  22708. root.traversal(function(node) {
  22709. if (node.type !== 'element') {
  22710. return false;
  22711. }
  22712. filter(node);
  22713. });
  22714. });
  22715. }
  22716. // 添加output过滤规则
  22717. //
  22718. if (whitList && config.outputXssFilter) {
  22719. this.addOutputRule(function (root) {
  22720. root.traversal(function(node) {
  22721. if (node.type !== 'element') {
  22722. return false;
  22723. }
  22724. filter(node);
  22725. });
  22726. });
  22727. }
  22728. };
  22729. // ui/ui.js
  22730. var baidu = baidu || {};
  22731. baidu.editor = baidu.editor || {};
  22732. UE.ui = baidu.editor.ui = {};
  22733. // ui/uiutils.js
  22734. (function (){
  22735. var browser = baidu.editor.browser,
  22736. domUtils = baidu.editor.dom.domUtils;
  22737. var magic = '$EDITORUI';
  22738. var root = window[magic] = {};
  22739. var uidMagic = 'ID' + magic;
  22740. var uidCount = 0;
  22741. var uiUtils = baidu.editor.ui.uiUtils = {
  22742. uid: function (obj){
  22743. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22744. },
  22745. hook: function ( fn, callback ) {
  22746. var dg;
  22747. if (fn && fn._callbacks) {
  22748. dg = fn;
  22749. } else {
  22750. dg = function (){
  22751. var q;
  22752. if (fn) {
  22753. q = fn.apply(this, arguments);
  22754. }
  22755. var callbacks = dg._callbacks;
  22756. var k = callbacks.length;
  22757. while (k --) {
  22758. var r = callbacks[k].apply(this, arguments);
  22759. if (q === undefined) {
  22760. q = r;
  22761. }
  22762. }
  22763. return q;
  22764. };
  22765. dg._callbacks = [];
  22766. }
  22767. dg._callbacks.push(callback);
  22768. return dg;
  22769. },
  22770. createElementByHtml: function (html){
  22771. var el = document.createElement('div');
  22772. el.innerHTML = html;
  22773. el = el.firstChild;
  22774. el.parentNode.removeChild(el);
  22775. return el;
  22776. },
  22777. getViewportElement: function (){
  22778. return (browser.ie && browser.quirks) ?
  22779. document.body : document.documentElement;
  22780. },
  22781. getClientRect: function (element){
  22782. var bcr;
  22783. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22784. try{
  22785. bcr = element.getBoundingClientRect();
  22786. }catch(e){
  22787. bcr={left:0,top:0,height:0,width:0}
  22788. }
  22789. var rect = {
  22790. left: Math.round(bcr.left),
  22791. top: Math.round(bcr.top),
  22792. height: Math.round(bcr.bottom - bcr.top),
  22793. width: Math.round(bcr.right - bcr.left)
  22794. };
  22795. var doc;
  22796. while ((doc = element.ownerDocument) !== document &&
  22797. (element = domUtils.getWindow(doc).frameElement)) {
  22798. bcr = element.getBoundingClientRect();
  22799. rect.left += bcr.left;
  22800. rect.top += bcr.top;
  22801. }
  22802. rect.bottom = rect.top + rect.height;
  22803. rect.right = rect.left + rect.width;
  22804. return rect;
  22805. },
  22806. getViewportRect: function (){
  22807. var viewportEl = uiUtils.getViewportElement();
  22808. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22809. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22810. return {
  22811. left: 0,
  22812. top: 0,
  22813. height: height,
  22814. width: width,
  22815. bottom: height,
  22816. right: width
  22817. };
  22818. },
  22819. setViewportOffset: function (element, offset){
  22820. var rect;
  22821. var fixedLayer = uiUtils.getFixedLayer();
  22822. if (element.parentNode === fixedLayer) {
  22823. element.style.left = offset.left + 'px';
  22824. element.style.top = offset.top + 'px';
  22825. } else {
  22826. domUtils.setViewportOffset(element, offset);
  22827. }
  22828. },
  22829. getEventOffset: function (evt){
  22830. var el = evt.target || evt.srcElement;
  22831. var rect = uiUtils.getClientRect(el);
  22832. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22833. return {
  22834. left: offset.left - rect.left,
  22835. top: offset.top - rect.top
  22836. };
  22837. },
  22838. getViewportOffsetByEvent: function (evt){
  22839. var el = evt.target || evt.srcElement;
  22840. var frameEl = domUtils.getWindow(el).frameElement;
  22841. var offset = {
  22842. left: evt.clientX,
  22843. top: evt.clientY
  22844. };
  22845. if (frameEl && el.ownerDocument !== document) {
  22846. var rect = uiUtils.getClientRect(frameEl);
  22847. offset.left += rect.left;
  22848. offset.top += rect.top;
  22849. }
  22850. return offset;
  22851. },
  22852. setGlobal: function (id, obj){
  22853. root[id] = obj;
  22854. return magic + '["' + id + '"]';
  22855. },
  22856. unsetGlobal: function (id){
  22857. delete root[id];
  22858. },
  22859. copyAttributes: function (tgt, src){
  22860. var attributes = src.attributes;
  22861. var k = attributes.length;
  22862. while (k --) {
  22863. var attrNode = attributes[k];
  22864. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22865. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22866. }
  22867. }
  22868. if (src.className) {
  22869. domUtils.addClass(tgt,src.className);
  22870. }
  22871. if (src.style.cssText) {
  22872. tgt.style.cssText += ';' + src.style.cssText;
  22873. }
  22874. },
  22875. removeStyle: function (el, styleName){
  22876. if (el.style.removeProperty) {
  22877. el.style.removeProperty(styleName);
  22878. } else if (el.style.removeAttribute) {
  22879. el.style.removeAttribute(styleName);
  22880. } else throw '';
  22881. },
  22882. contains: function (elA, elB){
  22883. return elA && elB && (elA === elB ? false : (
  22884. elA.contains ? elA.contains(elB) :
  22885. elA.compareDocumentPosition(elB) & 16
  22886. ));
  22887. },
  22888. startDrag: function (evt, callbacks,doc){
  22889. var doc = doc || document;
  22890. var startX = evt.clientX;
  22891. var startY = evt.clientY;
  22892. function handleMouseMove(evt){
  22893. var x = evt.clientX - startX;
  22894. var y = evt.clientY - startY;
  22895. callbacks.ondragmove(x, y,evt);
  22896. if (evt.stopPropagation) {
  22897. evt.stopPropagation();
  22898. } else {
  22899. evt.cancelBubble = true;
  22900. }
  22901. }
  22902. if (doc.addEventListener) {
  22903. function handleMouseUp(evt){
  22904. doc.removeEventListener('mousemove', handleMouseMove, true);
  22905. doc.removeEventListener('mouseup', handleMouseUp, true);
  22906. window.removeEventListener('mouseup', handleMouseUp, true);
  22907. callbacks.ondragstop();
  22908. }
  22909. doc.addEventListener('mousemove', handleMouseMove, true);
  22910. doc.addEventListener('mouseup', handleMouseUp, true);
  22911. window.addEventListener('mouseup', handleMouseUp, true);
  22912. evt.preventDefault();
  22913. } else {
  22914. var elm = evt.srcElement;
  22915. elm.setCapture();
  22916. function releaseCaptrue(){
  22917. elm.releaseCapture();
  22918. elm.detachEvent('onmousemove', handleMouseMove);
  22919. elm.detachEvent('onmouseup', releaseCaptrue);
  22920. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  22921. callbacks.ondragstop();
  22922. }
  22923. elm.attachEvent('onmousemove', handleMouseMove);
  22924. elm.attachEvent('onmouseup', releaseCaptrue);
  22925. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  22926. evt.returnValue = false;
  22927. }
  22928. callbacks.ondragstart();
  22929. },
  22930. getFixedLayer: function (){
  22931. var layer = document.getElementById('edui_fixedlayer');
  22932. if (layer == null) {
  22933. layer = document.createElement('div');
  22934. layer.id = 'edui_fixedlayer';
  22935. document.body.appendChild(layer);
  22936. if (browser.ie && browser.version <= 8) {
  22937. layer.style.position = 'absolute';
  22938. bindFixedLayer();
  22939. setTimeout(updateFixedOffset);
  22940. } else {
  22941. layer.style.position = 'fixed';
  22942. }
  22943. layer.style.left = '0';
  22944. layer.style.top = '0';
  22945. layer.style.width = '0';
  22946. layer.style.height = '0';
  22947. }
  22948. return layer;
  22949. },
  22950. makeUnselectable: function (element){
  22951. if (browser.opera || (browser.ie && browser.version < 9)) {
  22952. element.unselectable = 'on';
  22953. if (element.hasChildNodes()) {
  22954. for (var i=0; i<element.childNodes.length; i++) {
  22955. if (element.childNodes[i].nodeType == 1) {
  22956. uiUtils.makeUnselectable(element.childNodes[i]);
  22957. }
  22958. }
  22959. }
  22960. } else {
  22961. if (element.style.MozUserSelect !== undefined) {
  22962. element.style.MozUserSelect = 'none';
  22963. } else if (element.style.WebkitUserSelect !== undefined) {
  22964. element.style.WebkitUserSelect = 'none';
  22965. } else if (element.style.KhtmlUserSelect !== undefined) {
  22966. element.style.KhtmlUserSelect = 'none';
  22967. }
  22968. }
  22969. }
  22970. };
  22971. function updateFixedOffset(){
  22972. var layer = document.getElementById('edui_fixedlayer');
  22973. uiUtils.setViewportOffset(layer, {
  22974. left: 0,
  22975. top: 0
  22976. });
  22977. // layer.style.display = 'none';
  22978. // layer.style.display = 'block';
  22979. //#trace: 1354
  22980. // setTimeout(updateFixedOffset);
  22981. }
  22982. function bindFixedLayer(adjOffset){
  22983. domUtils.on(window, 'scroll', updateFixedOffset);
  22984. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  22985. }
  22986. })();
  22987. // ui/uibase.js
  22988. (function () {
  22989. var utils = baidu.editor.utils,
  22990. uiUtils = baidu.editor.ui.uiUtils,
  22991. EventBase = baidu.editor.EventBase,
  22992. UIBase = baidu.editor.ui.UIBase = function () {
  22993. };
  22994. UIBase.prototype = {
  22995. className:'',
  22996. uiName:'',
  22997. initOptions:function (options) {
  22998. var me = this;
  22999. for (var k in options) {
  23000. me[k] = options[k];
  23001. }
  23002. this.id = this.id || 'edui' + uiUtils.uid();
  23003. },
  23004. initUIBase:function () {
  23005. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23006. },
  23007. render:function (holder) {
  23008. var html = this.renderHtml();
  23009. var el = uiUtils.createElementByHtml(html);
  23010. //by xuheng 给每个node添加class
  23011. var list = domUtils.getElementsByTagName(el, "*");
  23012. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23013. var layer = document.getElementById('edui_fixedlayer');
  23014. for (var i = 0, node; node = list[i++];) {
  23015. domUtils.addClass(node, theme);
  23016. }
  23017. domUtils.addClass(el, theme);
  23018. if(layer){
  23019. layer.className="";
  23020. domUtils.addClass(layer,theme);
  23021. }
  23022. var seatEl = this.getDom();
  23023. if (seatEl != null) {
  23024. seatEl.parentNode.replaceChild(el, seatEl);
  23025. uiUtils.copyAttributes(el, seatEl);
  23026. } else {
  23027. if (typeof holder == 'string') {
  23028. holder = document.getElementById(holder);
  23029. }
  23030. holder = holder || uiUtils.getFixedLayer();
  23031. domUtils.addClass(holder, theme);
  23032. holder.appendChild(el);
  23033. }
  23034. this.postRender();
  23035. },
  23036. getDom:function (name) {
  23037. if (!name) {
  23038. return document.getElementById(this.id);
  23039. } else {
  23040. return document.getElementById(this.id + '_' + name);
  23041. }
  23042. },
  23043. postRender:function () {
  23044. this.fireEvent('postrender');
  23045. },
  23046. getHtmlTpl:function () {
  23047. return '';
  23048. },
  23049. formatHtml:function (tpl) {
  23050. var prefix = 'edui-' + this.uiName;
  23051. return (tpl
  23052. .replace(/##/g, this.id)
  23053. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23054. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23055. .replace(/\$\$/g, this._globalKey));
  23056. },
  23057. renderHtml:function () {
  23058. return this.formatHtml(this.getHtmlTpl());
  23059. },
  23060. dispose:function () {
  23061. var box = this.getDom();
  23062. if (box) baidu.editor.dom.domUtils.remove(box);
  23063. uiUtils.unsetGlobal(this.id);
  23064. }
  23065. };
  23066. utils.inherits(UIBase, EventBase);
  23067. })();
  23068. // ui/separator.js
  23069. (function (){
  23070. var utils = baidu.editor.utils,
  23071. UIBase = baidu.editor.ui.UIBase,
  23072. Separator = baidu.editor.ui.Separator = function (options){
  23073. this.initOptions(options);
  23074. this.initSeparator();
  23075. };
  23076. Separator.prototype = {
  23077. uiName: 'separator',
  23078. initSeparator: function (){
  23079. this.initUIBase();
  23080. },
  23081. getHtmlTpl: function (){
  23082. return '<div id="##" class="edui-box %%"></div>';
  23083. }
  23084. };
  23085. utils.inherits(Separator, UIBase);
  23086. })();
  23087. // ui/mask.js
  23088. ///import core
  23089. ///import uicore
  23090. (function (){
  23091. var utils = baidu.editor.utils,
  23092. domUtils = baidu.editor.dom.domUtils,
  23093. UIBase = baidu.editor.ui.UIBase,
  23094. uiUtils = baidu.editor.ui.uiUtils;
  23095. var Mask = baidu.editor.ui.Mask = function (options){
  23096. this.initOptions(options);
  23097. this.initUIBase();
  23098. };
  23099. Mask.prototype = {
  23100. getHtmlTpl: function (){
  23101. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23102. },
  23103. postRender: function (){
  23104. var me = this;
  23105. domUtils.on(window, 'resize', function (){
  23106. setTimeout(function (){
  23107. if (!me.isHidden()) {
  23108. me._fill();
  23109. }
  23110. });
  23111. });
  23112. },
  23113. show: function (zIndex){
  23114. this._fill();
  23115. this.getDom().style.display = '';
  23116. this.getDom().style.zIndex = zIndex;
  23117. },
  23118. hide: function (){
  23119. this.getDom().style.display = 'none';
  23120. this.getDom().style.zIndex = '';
  23121. },
  23122. isHidden: function (){
  23123. return this.getDom().style.display == 'none';
  23124. },
  23125. _onMouseDown: function (){
  23126. return false;
  23127. },
  23128. _onClick: function (e, target){
  23129. this.fireEvent('click', e, target);
  23130. },
  23131. _fill: function (){
  23132. var el = this.getDom();
  23133. var vpRect = uiUtils.getViewportRect();
  23134. el.style.width = vpRect.width + 'px';
  23135. el.style.height = vpRect.height + 'px';
  23136. }
  23137. };
  23138. utils.inherits(Mask, UIBase);
  23139. })();
  23140. // ui/popup.js
  23141. ///import core
  23142. ///import uicore
  23143. (function () {
  23144. var utils = baidu.editor.utils,
  23145. uiUtils = baidu.editor.ui.uiUtils,
  23146. domUtils = baidu.editor.dom.domUtils,
  23147. UIBase = baidu.editor.ui.UIBase,
  23148. Popup = baidu.editor.ui.Popup = function (options){
  23149. this.initOptions(options);
  23150. this.initPopup();
  23151. };
  23152. var allPopups = [];
  23153. function closeAllPopup( evt,el ){
  23154. for ( var i = 0; i < allPopups.length; i++ ) {
  23155. var pop = allPopups[i];
  23156. if (!pop.isHidden()) {
  23157. if (pop.queryAutoHide(el) !== false) {
  23158. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23159. pop.hide();
  23160. }
  23161. }
  23162. }
  23163. if(allPopups.length)
  23164. pop.editor.fireEvent("afterhidepop");
  23165. }
  23166. Popup.postHide = closeAllPopup;
  23167. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23168. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23169. Popup.prototype = {
  23170. SHADOW_RADIUS: 5,
  23171. content: null,
  23172. _hidden: false,
  23173. autoRender: true,
  23174. canSideLeft: true,
  23175. canSideUp: true,
  23176. initPopup: function (){
  23177. this.initUIBase();
  23178. allPopups.push( this );
  23179. },
  23180. getHtmlTpl: function (){
  23181. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23182. ' <div id="##_body" class="edui-popup-body">' +
  23183. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23184. ' <div class="edui-shadow"></div>' +
  23185. ' <div id="##_content" class="edui-popup-content">' +
  23186. this.getContentHtmlTpl() +
  23187. ' </div>' +
  23188. ' </div>' +
  23189. '</div>';
  23190. },
  23191. getContentHtmlTpl: function (){
  23192. if(this.content){
  23193. if (typeof this.content == 'string') {
  23194. return this.content;
  23195. }
  23196. return this.content.renderHtml();
  23197. }else{
  23198. return ''
  23199. }
  23200. },
  23201. _UIBase_postRender: UIBase.prototype.postRender,
  23202. postRender: function (){
  23203. if (this.content instanceof UIBase) {
  23204. this.content.postRender();
  23205. }
  23206. //捕获鼠标滚轮
  23207. if( this.captureWheel && !this.captured ) {
  23208. this.captured = true;
  23209. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23210. _height = this.getDom().offsetHeight,
  23211. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23212. content = this.getDom('content'),
  23213. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23214. me = this;
  23215. ifr.length && ( ifr = ifr[0] );
  23216. while( _top + _height > winHeight ) {
  23217. _height -= 30;
  23218. }
  23219. content.style.height = _height + 'px';
  23220. //同步更改iframe高度
  23221. ifr && ( ifr.style.height = _height + 'px' );
  23222. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23223. if( window.XMLHttpRequest ) {
  23224. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23225. if(e.preventDefault) {
  23226. e.preventDefault();
  23227. } else {
  23228. e.returnValue = false;
  23229. }
  23230. if( e.wheelDelta ) {
  23231. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23232. } else {
  23233. content.scrollTop -= ( e.detail / -3 )*60;
  23234. }
  23235. });
  23236. } else {
  23237. //ie6
  23238. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23239. e.returnValue = false;
  23240. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23241. });
  23242. }
  23243. }
  23244. this.fireEvent('postRenderAfter');
  23245. this.hide(true);
  23246. this._UIBase_postRender();
  23247. },
  23248. _doAutoRender: function (){
  23249. if (!this.getDom() && this.autoRender) {
  23250. this.render();
  23251. }
  23252. },
  23253. mesureSize: function (){
  23254. var box = this.getDom('content');
  23255. return uiUtils.getClientRect(box);
  23256. },
  23257. fitSize: function (){
  23258. if( this.captureWheel && this.sized ) {
  23259. return this.__size;
  23260. }
  23261. this.sized = true;
  23262. var popBodyEl = this.getDom('body');
  23263. popBodyEl.style.width = '';
  23264. popBodyEl.style.height = '';
  23265. var size = this.mesureSize();
  23266. if( this.captureWheel ) {
  23267. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23268. var height = parseInt( this.getDom('content').style.height, 10 );
  23269. !window.isNaN( height ) && ( size.height = height );
  23270. } else {
  23271. popBodyEl.style.width = size.width + 'px';
  23272. }
  23273. popBodyEl.style.height = size.height + 'px';
  23274. this.__size = size;
  23275. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23276. return size;
  23277. },
  23278. showAnchor: function ( element, hoz ){
  23279. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23280. },
  23281. showAnchorRect: function ( rect, hoz, adj ){
  23282. this._doAutoRender();
  23283. var vpRect = uiUtils.getViewportRect();
  23284. this.getDom().style.visibility = 'hidden';
  23285. this._show();
  23286. var popSize = this.fitSize();
  23287. var sideLeft, sideUp, left, top;
  23288. if (hoz) {
  23289. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23290. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23291. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23292. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23293. } else {
  23294. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23295. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23296. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23297. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23298. }
  23299. var popEl = this.getDom();
  23300. uiUtils.setViewportOffset(popEl, {
  23301. left: left,
  23302. top: top
  23303. });
  23304. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23305. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23306. if(this.editor){
  23307. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23308. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23309. }
  23310. this.getDom().style.visibility = 'visible';
  23311. },
  23312. showAt: function (offset) {
  23313. var left = offset.left;
  23314. var top = offset.top;
  23315. var rect = {
  23316. left: left,
  23317. top: top,
  23318. right: left,
  23319. bottom: top,
  23320. height: 0,
  23321. width: 0
  23322. };
  23323. this.showAnchorRect(rect, false, true);
  23324. },
  23325. _show: function (){
  23326. if (this._hidden) {
  23327. var box = this.getDom();
  23328. box.style.display = '';
  23329. this._hidden = false;
  23330. // if (box.setActive) {
  23331. // box.setActive();
  23332. // }
  23333. this.fireEvent('show');
  23334. }
  23335. },
  23336. isHidden: function (){
  23337. return this._hidden;
  23338. },
  23339. show: function (){
  23340. this._doAutoRender();
  23341. this._show();
  23342. },
  23343. hide: function (notNofity){
  23344. if (!this._hidden && this.getDom()) {
  23345. this.getDom().style.display = 'none';
  23346. this._hidden = true;
  23347. if (!notNofity) {
  23348. this.fireEvent('hide');
  23349. }
  23350. }
  23351. },
  23352. queryAutoHide: function (el){
  23353. return !el || !uiUtils.contains(this.getDom(), el);
  23354. }
  23355. };
  23356. utils.inherits(Popup, UIBase);
  23357. domUtils.on( document, 'mousedown', function ( evt ) {
  23358. var el = evt.target || evt.srcElement;
  23359. closeAllPopup( evt,el );
  23360. } );
  23361. domUtils.on( window, 'scroll', function (evt,el) {
  23362. closeAllPopup( evt,el );
  23363. } );
  23364. })();
  23365. // ui/colorpicker.js
  23366. ///import core
  23367. ///import uicore
  23368. (function (){
  23369. var utils = baidu.editor.utils,
  23370. UIBase = baidu.editor.ui.UIBase,
  23371. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23372. this.initOptions(options);
  23373. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23374. this.initUIBase();
  23375. };
  23376. ColorPicker.prototype = {
  23377. getHtmlTpl: function (){
  23378. return genColorPicker(this.noColorText,this.editor);
  23379. },
  23380. _onTableClick: function (evt){
  23381. var tgt = evt.target || evt.srcElement;
  23382. var color = tgt.getAttribute('data-color');
  23383. if (color) {
  23384. this.fireEvent('pickcolor', color);
  23385. }
  23386. },
  23387. _onTableOver: function (evt){
  23388. var tgt = evt.target || evt.srcElement;
  23389. var color = tgt.getAttribute('data-color');
  23390. if (color) {
  23391. this.getDom('preview').style.backgroundColor = color;
  23392. }
  23393. },
  23394. _onTableOut: function (){
  23395. this.getDom('preview').style.backgroundColor = '';
  23396. },
  23397. _onPickNoColor: function (){
  23398. this.fireEvent('picknocolor');
  23399. }
  23400. };
  23401. utils.inherits(ColorPicker, UIBase);
  23402. var COLORS = (
  23403. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23404. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23405. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23406. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23407. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23408. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23409. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23410. function genColorPicker(noColorText,editor){
  23411. var html = '<div id="##" class="edui-colorpicker %%">' +
  23412. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23413. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23414. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23415. '</div>' +
  23416. '<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">' +
  23417. '<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>'+
  23418. '<tr class="edui-colorpicker-tablefirstrow" >';
  23419. for (var i=0; i<COLORS.length; i++) {
  23420. if (i && i%10 === 0) {
  23421. 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"':'')+'>';
  23422. }
  23423. 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"' +
  23424. ' data-color="#'+ COLORS[i] +'"'+
  23425. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23426. (i<10 || i>=60?'border-width:1px;':
  23427. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23428. 'border-width:0 1px 0 1px;')+
  23429. '"' +
  23430. '></a></td>':'';
  23431. }
  23432. html += '</tr></table></div>';
  23433. return html;
  23434. }
  23435. })();
  23436. // ui/tablepicker.js
  23437. ///import core
  23438. ///import uicore
  23439. (function (){
  23440. var utils = baidu.editor.utils,
  23441. uiUtils = baidu.editor.ui.uiUtils,
  23442. UIBase = baidu.editor.ui.UIBase;
  23443. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23444. this.initOptions(options);
  23445. this.initTablePicker();
  23446. };
  23447. TablePicker.prototype = {
  23448. defaultNumRows: 10,
  23449. defaultNumCols: 10,
  23450. maxNumRows: 20,
  23451. maxNumCols: 20,
  23452. numRows: 10,
  23453. numCols: 10,
  23454. lengthOfCellSide: 22,
  23455. initTablePicker: function (){
  23456. this.initUIBase();
  23457. },
  23458. getHtmlTpl: function (){
  23459. var me = this;
  23460. return '<div id="##" class="edui-tablepicker %%">' +
  23461. '<div class="edui-tablepicker-body">' +
  23462. '<div class="edui-infoarea">' +
  23463. '<span id="##_label" class="edui-label"></span>' +
  23464. '</div>' +
  23465. '<div class="edui-pickarea"' +
  23466. ' onmousemove="$$._onMouseMove(event, this);"' +
  23467. ' onmouseover="$$._onMouseOver(event, this);"' +
  23468. ' onmouseout="$$._onMouseOut(event, this);"' +
  23469. ' onclick="$$._onClick(event, this);"' +
  23470. '>' +
  23471. '<div id="##_overlay" class="edui-overlay"></div>' +
  23472. '</div>' +
  23473. '</div>' +
  23474. '</div>';
  23475. },
  23476. _UIBase_render: UIBase.prototype.render,
  23477. render: function (holder){
  23478. this._UIBase_render(holder);
  23479. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23480. },
  23481. _track: function (numCols, numRows){
  23482. var style = this.getDom('overlay').style;
  23483. var sideLen = this.lengthOfCellSide;
  23484. style.width = numCols * sideLen + 'px';
  23485. style.height = numRows * sideLen + 'px';
  23486. var label = this.getDom('label');
  23487. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23488. this.numCols = numCols;
  23489. this.numRows = numRows;
  23490. },
  23491. _onMouseOver: function (evt, el){
  23492. var rel = evt.relatedTarget || evt.fromElement;
  23493. if (!uiUtils.contains(el, rel) && el !== rel) {
  23494. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23495. this.getDom('overlay').style.visibility = '';
  23496. }
  23497. },
  23498. _onMouseOut: function (evt, el){
  23499. var rel = evt.relatedTarget || evt.toElement;
  23500. if (!uiUtils.contains(el, rel) && el !== rel) {
  23501. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23502. this.getDom('overlay').style.visibility = 'hidden';
  23503. }
  23504. },
  23505. _onMouseMove: function (evt, el){
  23506. var style = this.getDom('overlay').style;
  23507. var offset = uiUtils.getEventOffset(evt);
  23508. var sideLen = this.lengthOfCellSide;
  23509. var numCols = Math.ceil(offset.left / sideLen);
  23510. var numRows = Math.ceil(offset.top / sideLen);
  23511. this._track(numCols, numRows);
  23512. },
  23513. _onClick: function (){
  23514. this.fireEvent('picktable', this.numCols, this.numRows);
  23515. }
  23516. };
  23517. utils.inherits(TablePicker, UIBase);
  23518. })();
  23519. // ui/stateful.js
  23520. (function (){
  23521. var browser = baidu.editor.browser,
  23522. domUtils = baidu.editor.dom.domUtils,
  23523. uiUtils = baidu.editor.ui.uiUtils;
  23524. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23525. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23526. ( browser.ie ? (
  23527. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23528. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23529. : (
  23530. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23531. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23532. baidu.editor.ui.Stateful = {
  23533. alwalysHoverable: false,
  23534. target:null,//目标元素和this指向dom不一样
  23535. Stateful_init: function (){
  23536. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23537. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23538. },
  23539. Stateful_getHtmlTpl: function (){
  23540. var tpl = this._Stateful_dGetHtmlTpl();
  23541. // 使用function避免$转义
  23542. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23543. },
  23544. Stateful_onMouseEnter: function (evt, el){
  23545. this.target=el;
  23546. if (!this.isDisabled() || this.alwalysHoverable) {
  23547. this.addState('hover');
  23548. this.fireEvent('over');
  23549. }
  23550. },
  23551. Stateful_onMouseLeave: function (evt, el){
  23552. if (!this.isDisabled() || this.alwalysHoverable) {
  23553. this.removeState('hover');
  23554. this.removeState('active');
  23555. this.fireEvent('out');
  23556. }
  23557. },
  23558. Stateful_onMouseOver: function (evt, el){
  23559. var rel = evt.relatedTarget;
  23560. if (!uiUtils.contains(el, rel) && el !== rel) {
  23561. this.Stateful_onMouseEnter(evt, el);
  23562. }
  23563. },
  23564. Stateful_onMouseOut: function (evt, el){
  23565. var rel = evt.relatedTarget;
  23566. if (!uiUtils.contains(el, rel) && el !== rel) {
  23567. this.Stateful_onMouseLeave(evt, el);
  23568. }
  23569. },
  23570. Stateful_onMouseDown: function (evt, el){
  23571. if (!this.isDisabled()) {
  23572. this.addState('active');
  23573. }
  23574. },
  23575. Stateful_onMouseUp: function (evt, el){
  23576. if (!this.isDisabled()) {
  23577. this.removeState('active');
  23578. }
  23579. },
  23580. Stateful_postRender: function (){
  23581. if (this.disabled && !this.hasState('disabled')) {
  23582. this.addState('disabled');
  23583. }
  23584. },
  23585. hasState: function (state){
  23586. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23587. },
  23588. addState: function (state){
  23589. if (!this.hasState(state)) {
  23590. this.getStateDom().className += ' edui-state-' + state;
  23591. }
  23592. },
  23593. removeState: function (state){
  23594. if (this.hasState(state)) {
  23595. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23596. }
  23597. },
  23598. getStateDom: function (){
  23599. return this.getDom('state');
  23600. },
  23601. isChecked: function (){
  23602. return this.hasState('checked');
  23603. },
  23604. setChecked: function (checked){
  23605. if (!this.isDisabled() && checked) {
  23606. this.addState('checked');
  23607. } else {
  23608. this.removeState('checked');
  23609. }
  23610. },
  23611. isDisabled: function (){
  23612. return this.hasState('disabled');
  23613. },
  23614. setDisabled: function (disabled){
  23615. if (disabled) {
  23616. this.removeState('hover');
  23617. this.removeState('checked');
  23618. this.removeState('active');
  23619. this.addState('disabled');
  23620. } else {
  23621. this.removeState('disabled');
  23622. }
  23623. }
  23624. };
  23625. })();
  23626. // ui/button.js
  23627. ///import core
  23628. ///import uicore
  23629. ///import ui/stateful.js
  23630. (function (){
  23631. var utils = baidu.editor.utils,
  23632. UIBase = baidu.editor.ui.UIBase,
  23633. Stateful = baidu.editor.ui.Stateful,
  23634. Button = baidu.editor.ui.Button = function (options){
  23635. if(options.name){
  23636. var btnName = options.name;
  23637. var cssRules = options.cssRules;
  23638. if(!options.className){
  23639. options.className = 'edui-for-' + btnName;
  23640. }
  23641. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23642. }
  23643. this.initOptions(options);
  23644. this.initButton();
  23645. };
  23646. Button.prototype = {
  23647. uiName: 'button',
  23648. label: '',
  23649. title: '',
  23650. showIcon: true,
  23651. showText: true,
  23652. cssRules:'',
  23653. initButton: function (){
  23654. this.initUIBase();
  23655. this.Stateful_init();
  23656. if(this.cssRules){
  23657. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23658. }
  23659. },
  23660. getHtmlTpl: function (){
  23661. return '<div id="##" class="edui-box %%">' +
  23662. '<div id="##_state" stateful>' +
  23663. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23664. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23665. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23666. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23667. '</div>' +
  23668. '</div>' +
  23669. '</div></div>';
  23670. },
  23671. postRender: function (){
  23672. this.Stateful_postRender();
  23673. this.setDisabled(this.disabled)
  23674. },
  23675. _onMouseDown: function (e){
  23676. var target = e.target || e.srcElement,
  23677. tagName = target && target.tagName && target.tagName.toLowerCase();
  23678. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  23679. return false;
  23680. }
  23681. },
  23682. _onClick: function (){
  23683. if (!this.isDisabled()) {
  23684. this.fireEvent('click');
  23685. }
  23686. },
  23687. setTitle: function(text){
  23688. var label = this.getDom('label');
  23689. label.innerHTML = text;
  23690. }
  23691. };
  23692. utils.inherits(Button, UIBase);
  23693. utils.extend(Button.prototype, Stateful);
  23694. })();
  23695. // ui/splitbutton.js
  23696. ///import core
  23697. ///import uicore
  23698. ///import ui/stateful.js
  23699. (function (){
  23700. var utils = baidu.editor.utils,
  23701. uiUtils = baidu.editor.ui.uiUtils,
  23702. domUtils = baidu.editor.dom.domUtils,
  23703. UIBase = baidu.editor.ui.UIBase,
  23704. Stateful = baidu.editor.ui.Stateful,
  23705. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23706. this.initOptions(options);
  23707. this.initSplitButton();
  23708. };
  23709. SplitButton.prototype = {
  23710. popup: null,
  23711. uiName: 'splitbutton',
  23712. title: '',
  23713. initSplitButton: function (){
  23714. this.initUIBase();
  23715. this.Stateful_init();
  23716. var me = this;
  23717. if (this.popup != null) {
  23718. var popup = this.popup;
  23719. this.popup = null;
  23720. this.setPopup(popup);
  23721. }
  23722. },
  23723. _UIBase_postRender: UIBase.prototype.postRender,
  23724. postRender: function (){
  23725. this.Stateful_postRender();
  23726. this._UIBase_postRender();
  23727. },
  23728. setPopup: function (popup){
  23729. if (this.popup === popup) return;
  23730. if (this.popup != null) {
  23731. this.popup.dispose();
  23732. }
  23733. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23734. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23735. popup.addListener('postrender', utils.bind(function (){
  23736. popup.getDom('body').appendChild(
  23737. uiUtils.createElementByHtml('<div id="' +
  23738. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23739. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23740. );
  23741. popup.getDom().className += ' ' + this.className;
  23742. }, this));
  23743. this.popup = popup;
  23744. },
  23745. _onPopupShow: function (){
  23746. this.addState('opened');
  23747. },
  23748. _onPopupHide: function (){
  23749. this.removeState('opened');
  23750. },
  23751. getHtmlTpl: function (){
  23752. return '<div id="##" class="edui-box %%">' +
  23753. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23754. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23755. '<div class="edui-box edui-icon"></div>' +
  23756. '</div>' +
  23757. '<div class="edui-box edui-splitborder"></div>' +
  23758. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23759. '</div></div></div>';
  23760. },
  23761. showPopup: function (){
  23762. // 当popup往上弹出的时候,做特殊处理
  23763. var rect = uiUtils.getClientRect(this.getDom());
  23764. rect.top -= this.popup.SHADOW_RADIUS;
  23765. rect.height += this.popup.SHADOW_RADIUS;
  23766. this.popup.showAnchorRect(rect);
  23767. },
  23768. _onArrowClick: function (event, el){
  23769. if (!this.isDisabled()) {
  23770. this.showPopup();
  23771. }
  23772. },
  23773. _onButtonClick: function (){
  23774. if (!this.isDisabled()) {
  23775. this.fireEvent('buttonclick');
  23776. }
  23777. }
  23778. };
  23779. utils.inherits(SplitButton, UIBase);
  23780. utils.extend(SplitButton.prototype, Stateful, true);
  23781. })();
  23782. // ui/colorbutton.js
  23783. ///import core
  23784. ///import uicore
  23785. ///import ui/colorpicker.js
  23786. ///import ui/popup.js
  23787. ///import ui/splitbutton.js
  23788. (function (){
  23789. var utils = baidu.editor.utils,
  23790. uiUtils = baidu.editor.ui.uiUtils,
  23791. ColorPicker = baidu.editor.ui.ColorPicker,
  23792. Popup = baidu.editor.ui.Popup,
  23793. SplitButton = baidu.editor.ui.SplitButton,
  23794. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23795. this.initOptions(options);
  23796. this.initColorButton();
  23797. };
  23798. ColorButton.prototype = {
  23799. initColorButton: function (){
  23800. var me = this;
  23801. this.popup = new Popup({
  23802. content: new ColorPicker({
  23803. noColorText: me.editor.getLang("clearColor"),
  23804. editor:me.editor,
  23805. onpickcolor: function (t, color){
  23806. me._onPickColor(color);
  23807. },
  23808. onpicknocolor: function (t, color){
  23809. me._onPickNoColor(color);
  23810. }
  23811. }),
  23812. editor:me.editor
  23813. });
  23814. this.initSplitButton();
  23815. },
  23816. _SplitButton_postRender: SplitButton.prototype.postRender,
  23817. postRender: function (){
  23818. this._SplitButton_postRender();
  23819. this.getDom('button_body').appendChild(
  23820. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23821. );
  23822. this.getDom().className += ' edui-colorbutton';
  23823. },
  23824. setColor: function (color){
  23825. this.getDom('colorlump').style.backgroundColor = color;
  23826. this.color = color;
  23827. },
  23828. _onPickColor: function (color){
  23829. if (this.fireEvent('pickcolor', color) !== false) {
  23830. this.setColor(color);
  23831. this.popup.hide();
  23832. }
  23833. },
  23834. _onPickNoColor: function (color){
  23835. if (this.fireEvent('picknocolor') !== false) {
  23836. this.popup.hide();
  23837. }
  23838. }
  23839. };
  23840. utils.inherits(ColorButton, SplitButton);
  23841. })();
  23842. // ui/tablebutton.js
  23843. ///import core
  23844. ///import uicore
  23845. ///import ui/popup.js
  23846. ///import ui/tablepicker.js
  23847. ///import ui/splitbutton.js
  23848. (function (){
  23849. var utils = baidu.editor.utils,
  23850. Popup = baidu.editor.ui.Popup,
  23851. TablePicker = baidu.editor.ui.TablePicker,
  23852. SplitButton = baidu.editor.ui.SplitButton,
  23853. TableButton = baidu.editor.ui.TableButton = function (options){
  23854. this.initOptions(options);
  23855. this.initTableButton();
  23856. };
  23857. TableButton.prototype = {
  23858. initTableButton: function (){
  23859. var me = this;
  23860. this.popup = new Popup({
  23861. content: new TablePicker({
  23862. editor:me.editor,
  23863. onpicktable: function (t, numCols, numRows){
  23864. me._onPickTable(numCols, numRows);
  23865. }
  23866. }),
  23867. 'editor':me.editor
  23868. });
  23869. this.initSplitButton();
  23870. },
  23871. _onPickTable: function (numCols, numRows){
  23872. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23873. this.popup.hide();
  23874. }
  23875. }
  23876. };
  23877. utils.inherits(TableButton, SplitButton);
  23878. })();
  23879. // ui/autotypesetpicker.js
  23880. ///import core
  23881. ///import uicore
  23882. (function () {
  23883. var utils = baidu.editor.utils,
  23884. UIBase = baidu.editor.ui.UIBase;
  23885. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23886. this.initOptions(options);
  23887. this.initAutoTypeSetPicker();
  23888. };
  23889. AutoTypeSetPicker.prototype = {
  23890. initAutoTypeSetPicker:function () {
  23891. this.initUIBase();
  23892. },
  23893. getHtmlTpl:function () {
  23894. var me = this.editor,
  23895. opt = me.options.autotypeset,
  23896. lang = me.getLang("autoTypeSet");
  23897. var textAlignInputName = 'textAlignValue' + me.uid,
  23898. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23899. symbolConverInputName = 'symbolConverValue' + me.uid;
  23900. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23901. '<div class="edui-autotypesetpicker-body">' +
  23902. '<table >' +
  23903. '<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>' +
  23904. '<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>' +
  23905. '<tr>' +
  23906. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  23907. '<td colspan="2" id="' + textAlignInputName + '">' +
  23908. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23909. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23910. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23911. '</td>' +
  23912. '</tr>' +
  23913. '<tr>' +
  23914. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  23915. '<td nowrap id="'+ imageBlockInputName +'">' +
  23916. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  23917. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23918. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23919. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23920. '</td>' +
  23921. '</tr>' +
  23922. '<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>' +
  23923. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  23924. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  23925. '<tr>' +
  23926. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  23927. '<td id="' + symbolConverInputName + '">' +
  23928. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  23929. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  23930. '</td>' +
  23931. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  23932. '</tr>' +
  23933. '</table>' +
  23934. '</div>' +
  23935. '</div>';
  23936. },
  23937. _UIBase_render:UIBase.prototype.render
  23938. };
  23939. utils.inherits(AutoTypeSetPicker, UIBase);
  23940. })();
  23941. // ui/autotypesetbutton.js
  23942. ///import core
  23943. ///import uicore
  23944. ///import ui/popup.js
  23945. ///import ui/autotypesetpicker.js
  23946. ///import ui/splitbutton.js
  23947. (function (){
  23948. var utils = baidu.editor.utils,
  23949. Popup = baidu.editor.ui.Popup,
  23950. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  23951. SplitButton = baidu.editor.ui.SplitButton,
  23952. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  23953. this.initOptions(options);
  23954. this.initAutoTypeSetButton();
  23955. };
  23956. function getPara(me){
  23957. var opt = {},
  23958. cont = me.getDom(),
  23959. editorId = me.editor.uid,
  23960. inputType = null,
  23961. attrName = null,
  23962. ipts = domUtils.getElementsByTagName(cont,"input");
  23963. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  23964. inputType = ipt.getAttribute("type");
  23965. if(inputType=="checkbox"){
  23966. attrName = ipt.getAttribute("name");
  23967. opt[attrName] && delete opt[attrName];
  23968. if(ipt.checked){
  23969. var attrValue = document.getElementById( attrName + "Value" + editorId );
  23970. if(attrValue){
  23971. if(/input/ig.test(attrValue.tagName)){
  23972. opt[attrName] = attrValue.value;
  23973. } else {
  23974. var iptChilds = attrValue.getElementsByTagName("input");
  23975. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  23976. if(iptchild.checked){
  23977. opt[attrName] = iptchild.value;
  23978. break;
  23979. }
  23980. }
  23981. }
  23982. } else {
  23983. opt[attrName] = true;
  23984. }
  23985. } else {
  23986. opt[attrName] = false;
  23987. }
  23988. } else {
  23989. opt[ipt.getAttribute("value")] = ipt.checked;
  23990. }
  23991. }
  23992. var selects = domUtils.getElementsByTagName(cont,"select");
  23993. for(var i=0,si;si=selects[i++];){
  23994. var attr = si.getAttribute('name');
  23995. opt[attr] = opt[attr] ? si.value : '';
  23996. }
  23997. utils.extend(me.editor.options.autotypeset,opt);
  23998. me.editor.setPreferences('autotypeset', opt);
  23999. }
  24000. AutoTypeSetButton.prototype = {
  24001. initAutoTypeSetButton: function (){
  24002. var me = this;
  24003. this.popup = new Popup({
  24004. //传入配置参数
  24005. content: new AutoTypeSetPicker({editor:me.editor}),
  24006. 'editor':me.editor,
  24007. hide : function(){
  24008. if (!this._hidden && this.getDom()) {
  24009. getPara(this);
  24010. this.getDom().style.display = 'none';
  24011. this._hidden = true;
  24012. this.fireEvent('hide');
  24013. }
  24014. }
  24015. });
  24016. var flag = 0;
  24017. this.popup.addListener('postRenderAfter',function(){
  24018. var popupUI = this;
  24019. if(flag)return;
  24020. var cont = this.getDom(),
  24021. btn = cont.getElementsByTagName('button')[0];
  24022. btn.onclick = function(){
  24023. getPara(popupUI);
  24024. me.editor.execCommand('autotypeset');
  24025. popupUI.hide()
  24026. };
  24027. domUtils.on(cont, 'click', function(e) {
  24028. var target = e.target || e.srcElement,
  24029. editorId = me.editor.uid;
  24030. if (target && target.tagName == 'INPUT') {
  24031. // 点击图片浮动的checkbox,去除对应的radio
  24032. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24033. var checked = target.checked,
  24034. radioTd = document.getElementById( target.name + 'Value' + editorId),
  24035. radios = radioTd.getElementsByTagName('input'),
  24036. defalutSelect = {
  24037. 'imageBlockLine': 'none',
  24038. 'textAlign': 'left',
  24039. 'symbolConver': 'tobdc'
  24040. };
  24041. for (var i = 0; i < radios.length; i++) {
  24042. if (checked) {
  24043. if (radios[i].value == defalutSelect[target.name]) {
  24044. radios[i].checked = 'checked';
  24045. }
  24046. } else {
  24047. radios[i].checked = false;
  24048. }
  24049. }
  24050. }
  24051. // 点击radio,选中对应的checkbox
  24052. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24053. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24054. checkboxs && (checkboxs[0].checked = true);
  24055. }
  24056. getPara(popupUI);
  24057. }
  24058. });
  24059. flag = 1;
  24060. });
  24061. this.initSplitButton();
  24062. }
  24063. };
  24064. utils.inherits(AutoTypeSetButton, SplitButton);
  24065. })();
  24066. // ui/cellalignpicker.js
  24067. ///import core
  24068. ///import uicore
  24069. (function () {
  24070. var utils = baidu.editor.utils,
  24071. Popup = baidu.editor.ui.Popup,
  24072. Stateful = baidu.editor.ui.Stateful,
  24073. UIBase = baidu.editor.ui.UIBase;
  24074. /**
  24075. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24076. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24077. * @update 2013/4/2 hancong03@baidu.com
  24078. */
  24079. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24080. this.initOptions(options);
  24081. this.initSelected();
  24082. this.initCellAlignPicker();
  24083. };
  24084. CellAlignPicker.prototype = {
  24085. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24086. initSelected: function(){
  24087. var status = {
  24088. valign: {
  24089. top: 0,
  24090. middle: 1,
  24091. bottom: 2
  24092. },
  24093. align: {
  24094. left: 0,
  24095. center: 1,
  24096. right: 2
  24097. },
  24098. count: 3
  24099. },
  24100. result = -1;
  24101. if( this.selected ) {
  24102. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  24103. }
  24104. },
  24105. initCellAlignPicker:function () {
  24106. this.initUIBase();
  24107. this.Stateful_init();
  24108. },
  24109. getHtmlTpl:function () {
  24110. var alignType = [ 'left', 'center', 'right' ],
  24111. COUNT = 9,
  24112. tempClassName = null,
  24113. tempIndex = -1,
  24114. tmpl = [];
  24115. for( var i= 0; i<COUNT; i++ ) {
  24116. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24117. tempIndex = i % 3;
  24118. tempIndex === 0 && tmpl.push('<tr>');
  24119. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  24120. tempIndex === 2 && tmpl.push('</tr>');
  24121. }
  24122. return '<div id="##" class="edui-cellalignpicker %%">' +
  24123. '<div class="edui-cellalignpicker-body">' +
  24124. '<table onclick="$$._onClick(event);">' +
  24125. tmpl.join('') +
  24126. '</table>' +
  24127. '</div>' +
  24128. '</div>';
  24129. },
  24130. getStateDom: function (){
  24131. return this.target;
  24132. },
  24133. _onClick: function (evt){
  24134. var target= evt.target || evt.srcElement;
  24135. if(/icon/.test(target.className)){
  24136. this.items[target.parentNode.getAttribute("index")].onclick();
  24137. Popup.postHide(evt);
  24138. }
  24139. },
  24140. _UIBase_render:UIBase.prototype.render
  24141. };
  24142. utils.inherits(CellAlignPicker, UIBase);
  24143. utils.extend(CellAlignPicker.prototype, Stateful,true);
  24144. })();
  24145. // ui/pastepicker.js
  24146. ///import core
  24147. ///import uicore
  24148. (function () {
  24149. var utils = baidu.editor.utils,
  24150. Stateful = baidu.editor.ui.Stateful,
  24151. uiUtils = baidu.editor.ui.uiUtils,
  24152. UIBase = baidu.editor.ui.UIBase;
  24153. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24154. this.initOptions(options);
  24155. this.initPastePicker();
  24156. };
  24157. PastePicker.prototype = {
  24158. initPastePicker:function () {
  24159. this.initUIBase();
  24160. this.Stateful_init();
  24161. },
  24162. getHtmlTpl:function () {
  24163. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24164. '<div class="edui-pastecontainer">' +
  24165. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24166. '<div class="edui-button">' +
  24167. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24168. '<div class="edui-richtxticon"></div></div>' +
  24169. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24170. '<div class="edui-tagicon"></div></div>' +
  24171. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24172. '<div class="edui-plaintxticon"></div></div>' +
  24173. '</div>' +
  24174. '</div>' +
  24175. '</div>'
  24176. },
  24177. getStateDom:function () {
  24178. return this.target;
  24179. },
  24180. format:function (param) {
  24181. this.editor.ui._isTransfer = true;
  24182. this.editor.fireEvent('pasteTransfer', param);
  24183. },
  24184. _onClick:function (cur) {
  24185. var node = domUtils.getNextDomNode(cur),
  24186. screenHt = uiUtils.getViewportRect().height,
  24187. subPop = uiUtils.getClientRect(node);
  24188. if ((subPop.top + subPop.height) > screenHt)
  24189. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24190. else
  24191. node.style.top = "";
  24192. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24193. node.style.visibility = "visible";
  24194. domUtils.addClass(cur, "edui-state-opened");
  24195. } else {
  24196. node.style.visibility = "hidden";
  24197. domUtils.removeClasses(cur, "edui-state-opened")
  24198. }
  24199. },
  24200. _UIBase_render:UIBase.prototype.render
  24201. };
  24202. utils.inherits(PastePicker, UIBase);
  24203. utils.extend(PastePicker.prototype, Stateful, true);
  24204. })();
  24205. // ui/toolbar.js
  24206. (function (){
  24207. var utils = baidu.editor.utils,
  24208. uiUtils = baidu.editor.ui.uiUtils,
  24209. UIBase = baidu.editor.ui.UIBase,
  24210. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24211. this.initOptions(options);
  24212. this.initToolbar();
  24213. };
  24214. Toolbar.prototype = {
  24215. items: null,
  24216. initToolbar: function (){
  24217. this.items = this.items || [];
  24218. this.initUIBase();
  24219. },
  24220. add: function (item,index){
  24221. if(index === undefined){
  24222. this.items.push(item);
  24223. }else{
  24224. this.items.splice(index,0,item)
  24225. }
  24226. },
  24227. getHtmlTpl: function (){
  24228. var buff = [];
  24229. for (var i=0; i<this.items.length; i++) {
  24230. buff[i] = this.items[i].renderHtml();
  24231. }
  24232. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24233. buff.join('') +
  24234. '</div>'
  24235. },
  24236. postRender: function (){
  24237. var box = this.getDom();
  24238. for (var i=0; i<this.items.length; i++) {
  24239. this.items[i].postRender();
  24240. }
  24241. uiUtils.makeUnselectable(box);
  24242. },
  24243. _onMouseDown: function (e){
  24244. var target = e.target || e.srcElement,
  24245. tagName = target && target.tagName && target.tagName.toLowerCase();
  24246. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24247. return false;
  24248. }
  24249. }
  24250. };
  24251. utils.inherits(Toolbar, UIBase);
  24252. })();
  24253. // ui/menu.js
  24254. ///import core
  24255. ///import uicore
  24256. ///import ui\popup.js
  24257. ///import ui\stateful.js
  24258. (function () {
  24259. var utils = baidu.editor.utils,
  24260. domUtils = baidu.editor.dom.domUtils,
  24261. uiUtils = baidu.editor.ui.uiUtils,
  24262. UIBase = baidu.editor.ui.UIBase,
  24263. Popup = baidu.editor.ui.Popup,
  24264. Stateful = baidu.editor.ui.Stateful,
  24265. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24266. Menu = baidu.editor.ui.Menu = function (options) {
  24267. this.initOptions(options);
  24268. this.initMenu();
  24269. };
  24270. var menuSeparator = {
  24271. renderHtml:function () {
  24272. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24273. },
  24274. postRender:function () {
  24275. },
  24276. queryAutoHide:function () {
  24277. return true;
  24278. }
  24279. };
  24280. Menu.prototype = {
  24281. items:null,
  24282. uiName:'menu',
  24283. initMenu:function () {
  24284. this.items = this.items || [];
  24285. this.initPopup();
  24286. this.initItems();
  24287. },
  24288. initItems:function () {
  24289. for (var i = 0; i < this.items.length; i++) {
  24290. var item = this.items[i];
  24291. if (item == '-') {
  24292. this.items[i] = this.getSeparator();
  24293. } else if (!(item instanceof MenuItem)) {
  24294. item.editor = this.editor;
  24295. item.theme = this.editor.options.theme;
  24296. this.items[i] = this.createItem(item);
  24297. }
  24298. }
  24299. },
  24300. getSeparator:function () {
  24301. return menuSeparator;
  24302. },
  24303. createItem:function (item) {
  24304. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24305. item.menu = this;
  24306. return new MenuItem(item);
  24307. },
  24308. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24309. getContentHtmlTpl:function () {
  24310. if (this.items.length == 0) {
  24311. return this._Popup_getContentHtmlTpl();
  24312. }
  24313. var buff = [];
  24314. for (var i = 0; i < this.items.length; i++) {
  24315. var item = this.items[i];
  24316. buff[i] = item.renderHtml();
  24317. }
  24318. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24319. },
  24320. _Popup_postRender:Popup.prototype.postRender,
  24321. postRender:function () {
  24322. var me = this;
  24323. for (var i = 0; i < this.items.length; i++) {
  24324. var item = this.items[i];
  24325. item.ownerMenu = this;
  24326. item.postRender();
  24327. }
  24328. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24329. evt = evt || event;
  24330. var rel = evt.relatedTarget || evt.fromElement;
  24331. var el = me.getDom();
  24332. if (!uiUtils.contains(el, rel) && el !== rel) {
  24333. me.fireEvent('over');
  24334. }
  24335. });
  24336. this._Popup_postRender();
  24337. },
  24338. queryAutoHide:function (el) {
  24339. if (el) {
  24340. if (uiUtils.contains(this.getDom(), el)) {
  24341. return false;
  24342. }
  24343. for (var i = 0; i < this.items.length; i++) {
  24344. var item = this.items[i];
  24345. if (item.queryAutoHide(el) === false) {
  24346. return false;
  24347. }
  24348. }
  24349. }
  24350. },
  24351. clearItems:function () {
  24352. for (var i = 0; i < this.items.length; i++) {
  24353. var item = this.items[i];
  24354. clearTimeout(item._showingTimer);
  24355. clearTimeout(item._closingTimer);
  24356. if (item.subMenu) {
  24357. item.subMenu.destroy();
  24358. }
  24359. }
  24360. this.items = [];
  24361. },
  24362. destroy:function () {
  24363. if (this.getDom()) {
  24364. domUtils.remove(this.getDom());
  24365. }
  24366. this.clearItems();
  24367. },
  24368. dispose:function () {
  24369. this.destroy();
  24370. }
  24371. };
  24372. utils.inherits(Menu, Popup);
  24373. /**
  24374. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24375. * @type {Function}
  24376. */
  24377. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24378. this.initOptions(options);
  24379. this.initUIBase();
  24380. this.Stateful_init();
  24381. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24382. if (options.className && options.className.indexOf("aligntd") != -1) {
  24383. var me = this;
  24384. //获取单元格对齐初始状态
  24385. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24386. this.subMenu = new Popup({
  24387. content:new CellAlignPicker(this.subMenu),
  24388. parentMenu:me,
  24389. editor:me.editor,
  24390. destroy:function () {
  24391. if (this.getDom()) {
  24392. domUtils.remove(this.getDom());
  24393. }
  24394. }
  24395. });
  24396. this.subMenu.addListener("postRenderAfter", function () {
  24397. domUtils.on(this.getDom(), "mouseover", function () {
  24398. me.addState('opened');
  24399. });
  24400. });
  24401. } else {
  24402. this.subMenu = new Menu(this.subMenu);
  24403. }
  24404. }
  24405. };
  24406. MenuItem.prototype = {
  24407. label:'',
  24408. subMenu:null,
  24409. ownerMenu:null,
  24410. uiName:'menuitem',
  24411. alwalysHoverable:true,
  24412. getHtmlTpl:function () {
  24413. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24414. '<div class="%%-body">' +
  24415. this.renderLabelHtml() +
  24416. '</div>' +
  24417. '</div>';
  24418. },
  24419. postRender:function () {
  24420. var me = this;
  24421. this.addListener('over', function () {
  24422. me.ownerMenu.fireEvent('submenuover', me);
  24423. if (me.subMenu) {
  24424. me.delayShowSubMenu();
  24425. }
  24426. });
  24427. if (this.subMenu) {
  24428. this.getDom().className += ' edui-hassubmenu';
  24429. this.subMenu.render();
  24430. this.addListener('out', function () {
  24431. me.delayHideSubMenu();
  24432. });
  24433. this.subMenu.addListener('over', function () {
  24434. clearTimeout(me._closingTimer);
  24435. me._closingTimer = null;
  24436. me.addState('opened');
  24437. });
  24438. this.ownerMenu.addListener('hide', function () {
  24439. me.hideSubMenu();
  24440. });
  24441. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24442. if (subMenu !== me) {
  24443. me.delayHideSubMenu();
  24444. }
  24445. });
  24446. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24447. this.subMenu.queryAutoHide = function (el) {
  24448. if (el && uiUtils.contains(me.getDom(), el)) {
  24449. return false;
  24450. }
  24451. return this._bakQueryAutoHide(el);
  24452. };
  24453. }
  24454. this.getDom().style.tabIndex = '-1';
  24455. uiUtils.makeUnselectable(this.getDom());
  24456. this.Stateful_postRender();
  24457. },
  24458. delayShowSubMenu:function () {
  24459. var me = this;
  24460. if (!me.isDisabled()) {
  24461. me.addState('opened');
  24462. clearTimeout(me._showingTimer);
  24463. clearTimeout(me._closingTimer);
  24464. me._closingTimer = null;
  24465. me._showingTimer = setTimeout(function () {
  24466. me.showSubMenu();
  24467. }, 250);
  24468. }
  24469. },
  24470. delayHideSubMenu:function () {
  24471. var me = this;
  24472. if (!me.isDisabled()) {
  24473. me.removeState('opened');
  24474. clearTimeout(me._showingTimer);
  24475. if (!me._closingTimer) {
  24476. me._closingTimer = setTimeout(function () {
  24477. if (!me.hasState('opened')) {
  24478. me.hideSubMenu();
  24479. }
  24480. me._closingTimer = null;
  24481. }, 400);
  24482. }
  24483. }
  24484. },
  24485. renderLabelHtml:function () {
  24486. return '<div class="edui-arrow"></div>' +
  24487. '<div class="edui-box edui-icon"></div>' +
  24488. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24489. },
  24490. getStateDom:function () {
  24491. return this.getDom();
  24492. },
  24493. queryAutoHide:function (el) {
  24494. if (this.subMenu && this.hasState('opened')) {
  24495. return this.subMenu.queryAutoHide(el);
  24496. }
  24497. },
  24498. _onClick:function (event, this_) {
  24499. if (this.hasState('disabled')) return;
  24500. if (this.fireEvent('click', event, this_) !== false) {
  24501. if (this.subMenu) {
  24502. this.showSubMenu();
  24503. } else {
  24504. Popup.postHide(event);
  24505. }
  24506. }
  24507. },
  24508. showSubMenu:function () {
  24509. var rect = uiUtils.getClientRect(this.getDom());
  24510. rect.right -= 5;
  24511. rect.left += 2;
  24512. rect.width -= 7;
  24513. rect.top -= 4;
  24514. rect.bottom += 4;
  24515. rect.height += 8;
  24516. this.subMenu.showAnchorRect(rect, true, true);
  24517. },
  24518. hideSubMenu:function () {
  24519. this.subMenu.hide();
  24520. }
  24521. };
  24522. utils.inherits(MenuItem, UIBase);
  24523. utils.extend(MenuItem.prototype, Stateful, true);
  24524. })();
  24525. // ui/combox.js
  24526. ///import core
  24527. ///import uicore
  24528. ///import ui/menu.js
  24529. ///import ui/splitbutton.js
  24530. (function (){
  24531. // todo: menu和item提成通用list
  24532. var utils = baidu.editor.utils,
  24533. uiUtils = baidu.editor.ui.uiUtils,
  24534. Menu = baidu.editor.ui.Menu,
  24535. SplitButton = baidu.editor.ui.SplitButton,
  24536. Combox = baidu.editor.ui.Combox = function (options){
  24537. this.initOptions(options);
  24538. this.initCombox();
  24539. };
  24540. Combox.prototype = {
  24541. uiName: 'combox',
  24542. onbuttonclick:function () {
  24543. this.showPopup();
  24544. },
  24545. initCombox: function (){
  24546. var me = this;
  24547. this.items = this.items || [];
  24548. for (var i=0; i<this.items.length; i++) {
  24549. var item = this.items[i];
  24550. item.uiName = 'listitem';
  24551. item.index = i;
  24552. item.onclick = function (){
  24553. me.selectByIndex(this.index);
  24554. };
  24555. }
  24556. this.popup = new Menu({
  24557. items: this.items,
  24558. uiName: 'list',
  24559. editor:this.editor,
  24560. captureWheel: true,
  24561. combox: this
  24562. });
  24563. this.initSplitButton();
  24564. },
  24565. _SplitButton_postRender: SplitButton.prototype.postRender,
  24566. postRender: function (){
  24567. this._SplitButton_postRender();
  24568. this.setLabel(this.label || '');
  24569. this.setValue(this.initValue || '');
  24570. },
  24571. showPopup: function (){
  24572. var rect = uiUtils.getClientRect(this.getDom());
  24573. rect.top += 1;
  24574. rect.bottom -= 1;
  24575. rect.height -= 2;
  24576. this.popup.showAnchorRect(rect);
  24577. },
  24578. getValue: function (){
  24579. return this.value;
  24580. },
  24581. setValue: function (value){
  24582. var index = this.indexByValue(value);
  24583. if (index != -1) {
  24584. this.selectedIndex = index;
  24585. this.setLabel(this.items[index].label);
  24586. this.value = this.items[index].value;
  24587. } else {
  24588. this.selectedIndex = -1;
  24589. this.setLabel(this.getLabelForUnknowValue(value));
  24590. this.value = value;
  24591. }
  24592. },
  24593. setLabel: function (label){
  24594. this.getDom('button_body').innerHTML = label;
  24595. this.label = label;
  24596. },
  24597. getLabelForUnknowValue: function (value){
  24598. return value;
  24599. },
  24600. indexByValue: function (value){
  24601. for (var i=0; i<this.items.length; i++) {
  24602. if (value == this.items[i].value) {
  24603. return i;
  24604. }
  24605. }
  24606. return -1;
  24607. },
  24608. getItem: function (index){
  24609. return this.items[index];
  24610. },
  24611. selectByIndex: function (index){
  24612. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24613. this.selectedIndex = index;
  24614. this.value = this.items[index].value;
  24615. this.setLabel(this.items[index].label);
  24616. }
  24617. }
  24618. };
  24619. utils.inherits(Combox, SplitButton);
  24620. })();
  24621. // ui/dialog.js
  24622. ///import core
  24623. ///import uicore
  24624. ///import ui/mask.js
  24625. ///import ui/button.js
  24626. (function (){
  24627. var utils = baidu.editor.utils,
  24628. domUtils = baidu.editor.dom.domUtils,
  24629. uiUtils = baidu.editor.ui.uiUtils,
  24630. Mask = baidu.editor.ui.Mask,
  24631. UIBase = baidu.editor.ui.UIBase,
  24632. Button = baidu.editor.ui.Button,
  24633. Dialog = baidu.editor.ui.Dialog = function (options){
  24634. if(options.name){
  24635. var name = options.name;
  24636. var cssRules = options.cssRules;
  24637. if(!options.className){
  24638. options.className = 'edui-for-' + name;
  24639. }
  24640. if(cssRules){
  24641. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24642. }
  24643. }
  24644. this.initOptions(utils.extend({
  24645. autoReset: true,
  24646. draggable: true,
  24647. onok: function (){},
  24648. oncancel: function (){},
  24649. onclose: function (t, ok){
  24650. return ok ? this.onok() : this.oncancel();
  24651. },
  24652. //是否控制dialog中的scroll事件, 默认为不阻止
  24653. holdScroll: false
  24654. },options));
  24655. this.initDialog();
  24656. };
  24657. var modalMask;
  24658. var dragMask;
  24659. var activeDialog;
  24660. Dialog.prototype = {
  24661. draggable: false,
  24662. uiName: 'dialog',
  24663. initDialog: function (){
  24664. var me = this,
  24665. theme=this.editor.options.theme;
  24666. if(this.cssRules){
  24667. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24668. }
  24669. this.initUIBase();
  24670. this.modalMask = (modalMask || (modalMask = new Mask({
  24671. className: 'edui-dialog-modalmask',
  24672. theme:theme,
  24673. onclick: function (){
  24674. activeDialog && activeDialog.close(false);
  24675. }
  24676. })));
  24677. this.dragMask = (dragMask || (dragMask = new Mask({
  24678. className: 'edui-dialog-dragmask',
  24679. theme:theme
  24680. })));
  24681. this.closeButton = new Button({
  24682. className: 'edui-dialog-closebutton',
  24683. title: me.closeDialog,
  24684. theme:theme,
  24685. onclick: function (){
  24686. me.close(false);
  24687. }
  24688. });
  24689. this.fullscreen && this.initResizeEvent();
  24690. if (this.buttons) {
  24691. for (var i=0; i<this.buttons.length; i++) {
  24692. if (!(this.buttons[i] instanceof Button)) {
  24693. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24694. editor : this.editor
  24695. },true));
  24696. }
  24697. }
  24698. }
  24699. },
  24700. initResizeEvent: function () {
  24701. var me = this;
  24702. domUtils.on( window, "resize", function () {
  24703. if ( me._hidden || me._hidden === undefined ) {
  24704. return;
  24705. }
  24706. if ( me.__resizeTimer ) {
  24707. window.clearTimeout( me.__resizeTimer );
  24708. }
  24709. me.__resizeTimer = window.setTimeout( function () {
  24710. me.__resizeTimer = null;
  24711. var dialogWrapNode = me.getDom(),
  24712. contentNode = me.getDom('content'),
  24713. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24714. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24715. vpRect = uiUtils.getViewportRect();
  24716. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24717. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24718. dialogWrapNode.style.width = vpRect.width + "px";
  24719. dialogWrapNode.style.height = vpRect.height + "px";
  24720. me.fireEvent( "resize" );
  24721. }, 100 );
  24722. } );
  24723. },
  24724. fitSize: function (){
  24725. var popBodyEl = this.getDom('body');
  24726. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24727. // uiUtils.removeStyle(popBodyEl, 'width');
  24728. // uiUtils.removeStyle(popBodyEl, 'height');
  24729. // }
  24730. var size = this.mesureSize();
  24731. popBodyEl.style.width = size.width + 'px';
  24732. popBodyEl.style.height = size.height + 'px';
  24733. return size;
  24734. },
  24735. safeSetOffset: function (offset){
  24736. var me = this;
  24737. var el = me.getDom();
  24738. var vpRect = uiUtils.getViewportRect();
  24739. var rect = uiUtils.getClientRect(el);
  24740. var left = offset.left;
  24741. if (left + rect.width > vpRect.right) {
  24742. left = vpRect.right - rect.width;
  24743. }
  24744. var top = offset.top;
  24745. if (top + rect.height > vpRect.bottom) {
  24746. top = vpRect.bottom - rect.height;
  24747. }
  24748. el.style.left = Math.max(left, 0) + 'px';
  24749. el.style.top = Math.max(top, 0) + 'px';
  24750. },
  24751. showAtCenter: function (){
  24752. var vpRect = uiUtils.getViewportRect();
  24753. if ( !this.fullscreen ) {
  24754. this.getDom().style.display = '';
  24755. var popSize = this.fitSize();
  24756. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24757. var left = vpRect.width / 2 - popSize.width / 2;
  24758. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24759. var popEl = this.getDom();
  24760. this.safeSetOffset({
  24761. left: Math.max(left | 0, 0),
  24762. top: Math.max(top | 0, 0)
  24763. });
  24764. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24765. popEl.className += ' edui-state-centered';
  24766. }
  24767. } else {
  24768. var dialogWrapNode = this.getDom(),
  24769. contentNode = this.getDom('content');
  24770. dialogWrapNode.style.display = "block";
  24771. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24772. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24773. dialogWrapNode.style.left = "-100000px";
  24774. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24775. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24776. dialogWrapNode.style.width = vpRect.width + "px";
  24777. dialogWrapNode.style.height = vpRect.height + "px";
  24778. dialogWrapNode.style.left = 0;
  24779. //保存环境的overflow值
  24780. this._originalContext = {
  24781. html: {
  24782. overflowX: document.documentElement.style.overflowX,
  24783. overflowY: document.documentElement.style.overflowY
  24784. },
  24785. body: {
  24786. overflowX: document.body.style.overflowX,
  24787. overflowY: document.body.style.overflowY
  24788. }
  24789. };
  24790. document.documentElement.style.overflowX = 'hidden';
  24791. document.documentElement.style.overflowY = 'hidden';
  24792. document.body.style.overflowX = 'hidden';
  24793. document.body.style.overflowY = 'hidden';
  24794. }
  24795. this._show();
  24796. },
  24797. getContentHtml: function (){
  24798. var contentHtml = '';
  24799. if (typeof this.content == 'string') {
  24800. contentHtml = this.content;
  24801. } else if (this.iframeUrl) {
  24802. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24803. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24804. }
  24805. return contentHtml;
  24806. },
  24807. getHtmlTpl: function (){
  24808. var footHtml = '';
  24809. if (this.buttons) {
  24810. var buff = [];
  24811. for (var i=0; i<this.buttons.length; i++) {
  24812. buff[i] = this.buttons[i].renderHtml();
  24813. }
  24814. footHtml = '<div class="%%-foot">' +
  24815. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24816. '</div>';
  24817. }
  24818. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24819. '<div class="%%-shadow"></div>' +
  24820. '<div id="##_titlebar" class="%%-titlebar">' +
  24821. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24822. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24823. '</div>' +
  24824. this.closeButton.renderHtml() +
  24825. '</div>' +
  24826. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24827. footHtml +
  24828. '</div></div></div>';
  24829. },
  24830. postRender: function (){
  24831. // todo: 保持居中/记住上次关闭位置选项
  24832. if (!this.modalMask.getDom()) {
  24833. this.modalMask.render();
  24834. this.modalMask.hide();
  24835. }
  24836. if (!this.dragMask.getDom()) {
  24837. this.dragMask.render();
  24838. this.dragMask.hide();
  24839. }
  24840. var me = this;
  24841. this.addListener('show', function (){
  24842. me.modalMask.show(this.getDom().style.zIndex - 2);
  24843. });
  24844. this.addListener('hide', function (){
  24845. me.modalMask.hide();
  24846. });
  24847. if (this.buttons) {
  24848. for (var i=0; i<this.buttons.length; i++) {
  24849. this.buttons[i].postRender();
  24850. }
  24851. }
  24852. domUtils.on(window, 'resize', function (){
  24853. setTimeout(function (){
  24854. if (!me.isHidden()) {
  24855. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24856. }
  24857. });
  24858. });
  24859. //hold住scroll事件,防止dialog的滚动影响页面
  24860. // if( this.holdScroll ) {
  24861. //
  24862. // if( !me.iframeUrl ) {
  24863. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24864. // domUtils.preventDefault(e);
  24865. // } );
  24866. // } else {
  24867. // me.addListener('dialogafterreset', function(){
  24868. // window.setTimeout(function(){
  24869. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24870. //
  24871. // if( browser.ie ) {
  24872. //
  24873. // var timer = window.setInterval(function(){
  24874. //
  24875. // if( iframeWindow.document && iframeWindow.document.body ) {
  24876. // window.clearInterval( timer );
  24877. // timer = null;
  24878. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24879. // domUtils.preventDefault(e);
  24880. // } );
  24881. // }
  24882. //
  24883. // }, 100);
  24884. //
  24885. // } else {
  24886. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24887. // domUtils.preventDefault(e);
  24888. // } );
  24889. // }
  24890. //
  24891. // }, 1);
  24892. // });
  24893. // }
  24894. //
  24895. // }
  24896. this._hide();
  24897. },
  24898. mesureSize: function (){
  24899. var body = this.getDom('body');
  24900. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24901. var dialogBodyStyle = body.style;
  24902. dialogBodyStyle.width = width;
  24903. return uiUtils.getClientRect(body);
  24904. },
  24905. _onTitlebarMouseDown: function (evt, el){
  24906. if (this.draggable) {
  24907. var rect;
  24908. var vpRect = uiUtils.getViewportRect();
  24909. var me = this;
  24910. uiUtils.startDrag(evt, {
  24911. ondragstart: function (){
  24912. rect = uiUtils.getClientRect(me.getDom());
  24913. me.getDom('contmask').style.visibility = 'visible';
  24914. me.dragMask.show(me.getDom().style.zIndex - 1);
  24915. },
  24916. ondragmove: function (x, y){
  24917. var left = rect.left + x;
  24918. var top = rect.top + y;
  24919. me.safeSetOffset({
  24920. left: left,
  24921. top: top
  24922. });
  24923. },
  24924. ondragstop: function (){
  24925. me.getDom('contmask').style.visibility = 'hidden';
  24926. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  24927. me.dragMask.hide();
  24928. }
  24929. });
  24930. }
  24931. },
  24932. reset: function (){
  24933. this.getDom('content').innerHTML = this.getContentHtml();
  24934. this.fireEvent('dialogafterreset');
  24935. },
  24936. _show: function (){
  24937. if (this._hidden) {
  24938. this.getDom().style.display = '';
  24939. //要高过编辑器的zindxe
  24940. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  24941. this._hidden = false;
  24942. this.fireEvent('show');
  24943. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  24944. }
  24945. },
  24946. isHidden: function (){
  24947. return this._hidden;
  24948. },
  24949. _hide: function (){
  24950. if (!this._hidden) {
  24951. var wrapNode = this.getDom();
  24952. wrapNode.style.display = 'none';
  24953. wrapNode.style.zIndex = '';
  24954. wrapNode.style.width = '';
  24955. wrapNode.style.height = '';
  24956. this._hidden = true;
  24957. this.fireEvent('hide');
  24958. }
  24959. },
  24960. open: function (){
  24961. if (this.autoReset) {
  24962. //有可能还没有渲染
  24963. try{
  24964. this.reset();
  24965. }catch(e){
  24966. this.render();
  24967. this.open()
  24968. }
  24969. }
  24970. this.showAtCenter();
  24971. if (this.iframeUrl) {
  24972. try {
  24973. this.getDom('iframe').focus();
  24974. } catch(ex){}
  24975. }
  24976. activeDialog = this;
  24977. },
  24978. _onCloseButtonClick: function (evt, el){
  24979. this.close(false);
  24980. },
  24981. close: function (ok){
  24982. if (this.fireEvent('close', ok) !== false) {
  24983. //还原环境
  24984. if ( this.fullscreen ) {
  24985. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  24986. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  24987. document.body.style.overflowX = this._originalContext.body.overflowX;
  24988. document.body.style.overflowY = this._originalContext.body.overflowY;
  24989. delete this._originalContext;
  24990. }
  24991. this._hide();
  24992. //销毁content
  24993. var content = this.getDom('content');
  24994. var iframe = this.getDom('iframe');
  24995. if (content && iframe) {
  24996. var doc = iframe.contentDocument || iframe.contentWindow.document;
  24997. doc && (doc.body.innerHTML = '');
  24998. domUtils.remove(content);
  24999. }
  25000. }
  25001. }
  25002. };
  25003. utils.inherits(Dialog, UIBase);
  25004. })();
  25005. // ui/menubutton.js
  25006. ///import core
  25007. ///import uicore
  25008. ///import ui/menu.js
  25009. ///import ui/splitbutton.js
  25010. (function (){
  25011. var utils = baidu.editor.utils,
  25012. Menu = baidu.editor.ui.Menu,
  25013. SplitButton = baidu.editor.ui.SplitButton,
  25014. MenuButton = baidu.editor.ui.MenuButton = function (options){
  25015. this.initOptions(options);
  25016. this.initMenuButton();
  25017. };
  25018. MenuButton.prototype = {
  25019. initMenuButton: function (){
  25020. var me = this;
  25021. this.uiName = "menubutton";
  25022. this.popup = new Menu({
  25023. items: me.items,
  25024. className: me.className,
  25025. editor:me.editor
  25026. });
  25027. this.popup.addListener('show', function (){
  25028. var list = this;
  25029. for (var i=0; i<list.items.length; i++) {
  25030. list.items[i].removeState('checked');
  25031. if (list.items[i].value == me._value) {
  25032. list.items[i].addState('checked');
  25033. this.value = me._value;
  25034. }
  25035. }
  25036. });
  25037. this.initSplitButton();
  25038. },
  25039. setValue : function(value){
  25040. this._value = value;
  25041. }
  25042. };
  25043. utils.inherits(MenuButton, SplitButton);
  25044. })();
  25045. // ui/multiMenu.js
  25046. ///import core
  25047. ///import uicore
  25048. ///commands 表情
  25049. (function(){
  25050. var utils = baidu.editor.utils,
  25051. Popup = baidu.editor.ui.Popup,
  25052. SplitButton = baidu.editor.ui.SplitButton,
  25053. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25054. this.initOptions(options);
  25055. this.initMultiMenu();
  25056. };
  25057. MultiMenuPop.prototype = {
  25058. initMultiMenu: function (){
  25059. var me = this;
  25060. this.popup = new Popup({
  25061. content: '',
  25062. editor : me.editor,
  25063. iframe_rendered: false,
  25064. onshow: function (){
  25065. if (!this.iframe_rendered) {
  25066. this.iframe_rendered = true;
  25067. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25068. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25069. }
  25070. }
  25071. // canSideUp:false,
  25072. // canSideLeft:false
  25073. });
  25074. this.onbuttonclick = function(){
  25075. this.showPopup();
  25076. };
  25077. this.initSplitButton();
  25078. }
  25079. };
  25080. utils.inherits(MultiMenuPop, SplitButton);
  25081. })();
  25082. // ui/shortcutmenu.js
  25083. (function () {
  25084. var UI = baidu.editor.ui,
  25085. UIBase = UI.UIBase,
  25086. uiUtils = UI.uiUtils,
  25087. utils = baidu.editor.utils,
  25088. domUtils = baidu.editor.dom.domUtils;
  25089. var allMenus = [],//存储所有快捷菜单
  25090. timeID,
  25091. isSubMenuShow = false;//是否有子pop显示
  25092. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25093. this.initOptions (options);
  25094. this.initShortCutMenu ();
  25095. };
  25096. ShortCutMenu.postHide = hideAllMenu;
  25097. ShortCutMenu.prototype = {
  25098. isHidden : true ,
  25099. SPACE : 5 ,
  25100. initShortCutMenu : function () {
  25101. this.items = this.items || [];
  25102. this.initUIBase ();
  25103. this.initItems ();
  25104. this.initEvent ();
  25105. allMenus.push (this);
  25106. } ,
  25107. initEvent : function () {
  25108. var me = this,
  25109. doc = me.editor.document;
  25110. domUtils.on (doc , "mousemove" , function (e) {
  25111. if (me.isHidden === false) {
  25112. //有pop显示就不隐藏快捷菜单
  25113. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25114. var flag = true,
  25115. el = me.getDom (),
  25116. wt = el.offsetWidth,
  25117. ht = el.offsetHeight,
  25118. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25119. distanceY = ht / 2,//距离中心Y标准
  25120. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25121. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25122. clearTimeout (timeID);
  25123. timeID = setTimeout (function () {
  25124. if (y > 0 && y < distanceY) {
  25125. me.setOpacity (el , "1");
  25126. } else if (y > distanceY && y < distanceY + 70) {
  25127. me.setOpacity (el , "0.5");
  25128. flag = false;
  25129. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25130. me.hide ();
  25131. }
  25132. if (flag && x > 0 && x < distanceX) {
  25133. me.setOpacity (el , "1")
  25134. } else if (x > distanceX && x < distanceX + 70) {
  25135. me.setOpacity (el , "0.5")
  25136. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25137. me.hide ();
  25138. }
  25139. });
  25140. }
  25141. });
  25142. //ie\ff下 mouseout不准
  25143. if (browser.chrome) {
  25144. domUtils.on (doc , "mouseout" , function (e) {
  25145. var relatedTgt = e.relatedTarget || e.toElement;
  25146. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25147. me.hide ();
  25148. }
  25149. });
  25150. }
  25151. me.editor.addListener ("afterhidepop" , function () {
  25152. if (!me.isHidden) {
  25153. isSubMenuShow = true;
  25154. }
  25155. });
  25156. } ,
  25157. initItems : function () {
  25158. if (utils.isArray (this.items)) {
  25159. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25160. var item = this.items[i].toLowerCase ();
  25161. if (UI[item]) {
  25162. this.items[i] = new UI[item] (this.editor);
  25163. this.items[i].className += " edui-shortcutsubmenu ";
  25164. }
  25165. }
  25166. }
  25167. } ,
  25168. setOpacity : function (el , value) {
  25169. if (browser.ie && browser.version < 9) {
  25170. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25171. } else {
  25172. el.style.opacity = value;
  25173. }
  25174. } ,
  25175. getSubMenuMark : function () {
  25176. isSubMenuShow = false;
  25177. var layerEle = uiUtils.getFixedLayer ();
  25178. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25179. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25180. });
  25181. for (var i = 0, node ; node = list[i++] ;) {
  25182. if (node.style.display != "none") {
  25183. isSubMenuShow = true;
  25184. }
  25185. }
  25186. return isSubMenuShow;
  25187. } ,
  25188. show : function (e , hasContextmenu) {
  25189. var me = this,
  25190. offset = {},
  25191. el = this.getDom (),
  25192. fixedlayer = uiUtils.getFixedLayer ();
  25193. function setPos (offset) {
  25194. if (offset.left < 0) {
  25195. offset.left = 0;
  25196. }
  25197. if (offset.top < 0) {
  25198. offset.top = 0;
  25199. }
  25200. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25201. }
  25202. function setPosByCxtMenu (menu) {
  25203. if (!menu.tagName) {
  25204. menu = menu.getDom ();
  25205. }
  25206. offset.left = parseInt (menu.style.left);
  25207. offset.top = parseInt (menu.style.top);
  25208. offset.top -= el.offsetHeight + 15;
  25209. setPos (offset);
  25210. }
  25211. me.eventType = e.type;
  25212. el.style.cssText = "display:block;left:-9999px";
  25213. if (e.type == "contextmenu" && hasContextmenu) {
  25214. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25215. if (menu) {
  25216. setPosByCxtMenu (menu)
  25217. } else {
  25218. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25219. setPosByCxtMenu (menu);
  25220. });
  25221. }
  25222. } else {
  25223. offset = uiUtils.getViewportOffsetByEvent (e);
  25224. offset.top -= el.offsetHeight + me.SPACE;
  25225. offset.left += me.SPACE + 20;
  25226. setPos (offset);
  25227. me.setOpacity (el , 0.2);
  25228. }
  25229. me.isHidden = false;
  25230. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25231. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25232. if (me.editor) {
  25233. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25234. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25235. }
  25236. } ,
  25237. hide : function () {
  25238. if (this.getDom ()) {
  25239. this.getDom ().style.display = "none";
  25240. }
  25241. this.isHidden = true;
  25242. } ,
  25243. postRender : function () {
  25244. if (utils.isArray (this.items)) {
  25245. for (var i = 0, item ; item = this.items[i++] ;) {
  25246. item.postRender ();
  25247. }
  25248. }
  25249. } ,
  25250. getHtmlTpl : function () {
  25251. var buff;
  25252. if (utils.isArray (this.items)) {
  25253. buff = [];
  25254. for (var i = 0 ; i < this.items.length ; i++) {
  25255. buff[i] = this.items[i].renderHtml ();
  25256. }
  25257. buff = buff.join ("");
  25258. } else {
  25259. buff = this.items;
  25260. }
  25261. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25262. buff +
  25263. '</div>';
  25264. }
  25265. };
  25266. utils.inherits (ShortCutMenu , UIBase);
  25267. function hideAllMenu (e) {
  25268. var tgt = e.target || e.srcElement,
  25269. cur = domUtils.findParent (tgt , function (node) {
  25270. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25271. } , true);
  25272. if (!cur) {
  25273. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25274. menu.hide ()
  25275. }
  25276. }
  25277. }
  25278. domUtils.on (document , 'mousedown' , function (e) {
  25279. hideAllMenu (e);
  25280. });
  25281. domUtils.on (window , 'scroll' , function (e) {
  25282. hideAllMenu (e);
  25283. });
  25284. }) ();
  25285. // ui/breakline.js
  25286. (function (){
  25287. var utils = baidu.editor.utils,
  25288. UIBase = baidu.editor.ui.UIBase,
  25289. Breakline = baidu.editor.ui.Breakline = function (options){
  25290. this.initOptions(options);
  25291. this.initSeparator();
  25292. };
  25293. Breakline.prototype = {
  25294. uiName: 'Breakline',
  25295. initSeparator: function (){
  25296. this.initUIBase();
  25297. },
  25298. getHtmlTpl: function (){
  25299. return '<br/>';
  25300. }
  25301. };
  25302. utils.inherits(Breakline, UIBase);
  25303. })();
  25304. // ui/message.js
  25305. ///import core
  25306. ///import uicore
  25307. (function () {
  25308. var utils = baidu.editor.utils,
  25309. domUtils = baidu.editor.dom.domUtils,
  25310. UIBase = baidu.editor.ui.UIBase,
  25311. Message = baidu.editor.ui.Message = function (options){
  25312. this.initOptions(options);
  25313. this.initMessage();
  25314. };
  25315. Message.prototype = {
  25316. initMessage: function (){
  25317. this.initUIBase();
  25318. },
  25319. getHtmlTpl: function (){
  25320. return '<div id="##" class="edui-message %%">' +
  25321. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25322. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25323. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25324. ' <div class="edui-shadow"></div>' +
  25325. ' <div id="##_content" class="edui-message-content">' +
  25326. ' </div>' +
  25327. ' </div>' +
  25328. '</div>';
  25329. },
  25330. reset: function(opt){
  25331. var me = this;
  25332. if (!opt.keepshow) {
  25333. clearTimeout(this.timer);
  25334. me.timer = setTimeout(function(){
  25335. me.hide();
  25336. }, opt.timeout || 4000);
  25337. }
  25338. opt.content !== undefined && me.setContent(opt.content);
  25339. opt.type !== undefined && me.setType(opt.type);
  25340. me.show();
  25341. },
  25342. postRender: function(){
  25343. var me = this,
  25344. closer = this.getDom('closer');
  25345. closer && domUtils.on(closer, 'click', function(){
  25346. me.hide();
  25347. });
  25348. },
  25349. setContent: function(content){
  25350. this.getDom('content').innerHTML = content;
  25351. },
  25352. setType: function(type){
  25353. type = type || 'info';
  25354. var body = this.getDom('body');
  25355. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25356. },
  25357. getContent: function(){
  25358. return this.getDom('content').innerHTML;
  25359. },
  25360. getType: function(){
  25361. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25362. return arr ? arr[1]:'';
  25363. },
  25364. show: function (){
  25365. this.getDom().style.display = 'block';
  25366. },
  25367. hide: function (){
  25368. var dom = this.getDom();
  25369. if (dom) {
  25370. dom.style.display = 'none';
  25371. dom.parentNode && dom.parentNode.removeChild(dom);
  25372. }
  25373. }
  25374. };
  25375. utils.inherits(Message, UIBase);
  25376. })();
  25377. // adapter/editorui.js
  25378. //ui跟编辑器的适配層
  25379. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25380. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25381. (function () {
  25382. var utils = baidu.editor.utils;
  25383. var editorui = baidu.editor.ui;
  25384. var _Dialog = editorui.Dialog;
  25385. editorui.buttons = {};
  25386. editorui.Dialog = function (options) {
  25387. var dialog = new _Dialog(options);
  25388. dialog.addListener('hide', function () {
  25389. if (dialog.editor) {
  25390. var editor = dialog.editor;
  25391. try {
  25392. if (browser.gecko) {
  25393. var y = editor.window.scrollY,
  25394. x = editor.window.scrollX;
  25395. editor.body.focus();
  25396. editor.window.scrollTo(x, y);
  25397. } else {
  25398. editor.focus();
  25399. }
  25400. } catch (ex) {
  25401. }
  25402. }
  25403. });
  25404. return dialog;
  25405. };
  25406. var iframeUrlMap = {
  25407. 'anchor':'~/dialogs/anchor/anchor.html',
  25408. 'insertimage':'~/dialogs/image/image.html',
  25409. 'link':'~/dialogs/link/link.html',
  25410. 'spechars':'~/dialogs/spechars/spechars.html',
  25411. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25412. 'map':'~/dialogs/map/map.html',
  25413. 'gmap':'~/dialogs/gmap/gmap.html',
  25414. 'insertvideo':'~/dialogs/video/video.html',
  25415. 'help':'~/dialogs/help/help.html',
  25416. 'preview':'~/dialogs/preview/preview.html',
  25417. 'emotion':'~/dialogs/emotion/emotion.html',
  25418. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25419. 'attachment':'~/dialogs/attachment/attachment.html',
  25420. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25421. 'edittip':'~/dialogs/table/edittip.html',
  25422. 'edittable':'~/dialogs/table/edittable.html',
  25423. 'edittd':'~/dialogs/table/edittd.html',
  25424. 'webapp':'~/dialogs/webapp/webapp.html',
  25425. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25426. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25427. 'music':'~/dialogs/music/music.html',
  25428. 'template':'~/dialogs/template/template.html',
  25429. 'background':'~/dialogs/background/background.html',
  25430. 'charts': '~/dialogs/charts/charts.html'
  25431. };
  25432. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25433. var btnCmds = ['undo', 'redo', 'formatmatch',
  25434. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25435. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25436. 'blockquote', 'pasteplain', 'pagebreak',
  25437. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25438. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25439. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25440. for (var i = 0, ci; ci = btnCmds[i++];) {
  25441. ci = ci.toLowerCase();
  25442. editorui[ci] = function (cmd) {
  25443. return function (editor) {
  25444. var ui = new editorui.Button({
  25445. className:'edui-for-' + cmd,
  25446. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25447. onclick:function () {
  25448. editor.execCommand(cmd);
  25449. },
  25450. theme:editor.options.theme,
  25451. showText:false
  25452. });
  25453. editorui.buttons[cmd] = ui;
  25454. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25455. var state = editor.queryCommandState(cmd);
  25456. if (state == -1) {
  25457. ui.setDisabled(true);
  25458. ui.setChecked(false);
  25459. } else {
  25460. if (!uiReady) {
  25461. ui.setDisabled(false);
  25462. ui.setChecked(state);
  25463. }
  25464. }
  25465. });
  25466. return ui;
  25467. };
  25468. }(ci);
  25469. }
  25470. //清除文档
  25471. editorui.cleardoc = function (editor) {
  25472. var ui = new editorui.Button({
  25473. className:'edui-for-cleardoc',
  25474. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25475. theme:editor.options.theme,
  25476. onclick:function () {
  25477. if (confirm(editor.getLang("confirmClear"))) {
  25478. editor.execCommand('cleardoc');
  25479. }
  25480. }
  25481. });
  25482. editorui.buttons["cleardoc"] = ui;
  25483. editor.addListener('selectionchange', function () {
  25484. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25485. });
  25486. return ui;
  25487. };
  25488. //排版,图片排版,文字方向
  25489. var typeset = {
  25490. 'justify':['left', 'right', 'center', 'justify'],
  25491. 'imagefloat':['none', 'left', 'center', 'right'],
  25492. 'directionality':['ltr', 'rtl']
  25493. };
  25494. for (var p in typeset) {
  25495. (function (cmd, val) {
  25496. for (var i = 0, ci; ci = val[i++];) {
  25497. (function (cmd2) {
  25498. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25499. var ui = new editorui.Button({
  25500. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25501. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25502. theme:editor.options.theme,
  25503. onclick:function () {
  25504. editor.execCommand(cmd, cmd2);
  25505. }
  25506. });
  25507. editorui.buttons[cmd] = ui;
  25508. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25509. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25510. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25511. });
  25512. return ui;
  25513. };
  25514. })(ci)
  25515. }
  25516. })(p, typeset[p])
  25517. }
  25518. //字体颜色和背景颜色
  25519. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25520. editorui[ci] = function (cmd) {
  25521. return function (editor) {
  25522. var ui = new editorui.ColorButton({
  25523. className:'edui-for-' + cmd,
  25524. color:'default',
  25525. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25526. editor:editor,
  25527. onpickcolor:function (t, color) {
  25528. editor.execCommand(cmd, color);
  25529. },
  25530. onpicknocolor:function () {
  25531. editor.execCommand(cmd, 'default');
  25532. this.setColor('transparent');
  25533. this.color = 'default';
  25534. },
  25535. onbuttonclick:function () {
  25536. editor.execCommand(cmd, this.color);
  25537. }
  25538. });
  25539. editorui.buttons[cmd] = ui;
  25540. editor.addListener('selectionchange', function () {
  25541. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25542. });
  25543. return ui;
  25544. };
  25545. }(ci);
  25546. }
  25547. var dialogBtns = {
  25548. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25549. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25550. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25551. };
  25552. for (var p in dialogBtns) {
  25553. (function (type, vals) {
  25554. for (var i = 0, ci; ci = vals[i++];) {
  25555. //todo opera下存在问题
  25556. if (browser.opera && ci === "searchreplace") {
  25557. continue;
  25558. }
  25559. (function (cmd) {
  25560. editorui[cmd] = function (editor, iframeUrl, title) {
  25561. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25562. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25563. var dialog;
  25564. //没有iframeUrl不创建dialog
  25565. if (iframeUrl) {
  25566. dialog = new editorui.Dialog(utils.extend({
  25567. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25568. editor:editor,
  25569. className:'edui-for-' + cmd,
  25570. title:title,
  25571. holdScroll: cmd === 'insertimage',
  25572. fullscreen: /charts|preview/.test(cmd),
  25573. closeDialog:editor.getLang("closeDialog")
  25574. }, type == 'ok' ? {
  25575. buttons:[
  25576. {
  25577. className:'edui-okbutton',
  25578. label:editor.getLang("ok"),
  25579. editor:editor,
  25580. onclick:function () {
  25581. dialog.close(true);
  25582. }
  25583. },
  25584. {
  25585. className:'edui-cancelbutton',
  25586. label:editor.getLang("cancel"),
  25587. editor:editor,
  25588. onclick:function () {
  25589. dialog.close(false);
  25590. }
  25591. }
  25592. ]
  25593. } : {}));
  25594. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25595. }
  25596. var ui = new editorui.Button({
  25597. className:'edui-for-' + cmd,
  25598. title:title,
  25599. onclick:function () {
  25600. if (dialog) {
  25601. switch (cmd) {
  25602. case "wordimage":
  25603. var images = editor.execCommand("wordimage");
  25604. if (images && images.length) {
  25605. dialog.render();
  25606. dialog.open();
  25607. }
  25608. break;
  25609. case "scrawl":
  25610. if (editor.queryCommandState("scrawl") != -1) {
  25611. dialog.render();
  25612. dialog.open();
  25613. }
  25614. break;
  25615. default:
  25616. dialog.render();
  25617. dialog.open();
  25618. }
  25619. }
  25620. },
  25621. theme:editor.options.theme,
  25622. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25623. });
  25624. editorui.buttons[cmd] = ui;
  25625. editor.addListener('selectionchange', function () {
  25626. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25627. var unNeedCheckState = {'edittable':1};
  25628. if (cmd in unNeedCheckState)return;
  25629. var state = editor.queryCommandState(cmd);
  25630. if (ui.getDom()) {
  25631. ui.setDisabled(state == -1);
  25632. ui.setChecked(state);
  25633. }
  25634. });
  25635. return ui;
  25636. };
  25637. })(ci.toLowerCase())
  25638. }
  25639. })(p, dialogBtns[p]);
  25640. }
  25641. editorui.snapscreen = function (editor, iframeUrl, title) {
  25642. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25643. var ui = new editorui.Button({
  25644. className:'edui-for-snapscreen',
  25645. title:title,
  25646. onclick:function () {
  25647. editor.execCommand("snapscreen");
  25648. },
  25649. theme:editor.options.theme
  25650. });
  25651. editorui.buttons['snapscreen'] = ui;
  25652. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25653. if (iframeUrl) {
  25654. var dialog = new editorui.Dialog({
  25655. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25656. editor:editor,
  25657. className:'edui-for-snapscreen',
  25658. title:title,
  25659. buttons:[
  25660. {
  25661. className:'edui-okbutton',
  25662. label:editor.getLang("ok"),
  25663. editor:editor,
  25664. onclick:function () {
  25665. dialog.close(true);
  25666. }
  25667. },
  25668. {
  25669. className:'edui-cancelbutton',
  25670. label:editor.getLang("cancel"),
  25671. editor:editor,
  25672. onclick:function () {
  25673. dialog.close(false);
  25674. }
  25675. }
  25676. ]
  25677. });
  25678. dialog.render();
  25679. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25680. }
  25681. editor.addListener('selectionchange', function () {
  25682. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25683. });
  25684. return ui;
  25685. };
  25686. editorui.insertcode = function (editor, list, title) {
  25687. list = editor.options['insertcode'] || [];
  25688. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25689. // if (!list.length) return;
  25690. var items = [];
  25691. utils.each(list,function(key,val){
  25692. items.push({
  25693. label:key,
  25694. value:val,
  25695. theme:editor.options.theme,
  25696. renderLabelHtml:function () {
  25697. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25698. }
  25699. });
  25700. });
  25701. var ui = new editorui.Combox({
  25702. editor:editor,
  25703. items:items,
  25704. onselect:function (t, index) {
  25705. editor.execCommand('insertcode', this.items[index].value);
  25706. },
  25707. onbuttonclick:function () {
  25708. this.showPopup();
  25709. },
  25710. title:title,
  25711. initValue:title,
  25712. className:'edui-for-insertcode',
  25713. indexByValue:function (value) {
  25714. if (value) {
  25715. for (var i = 0, ci; ci = this.items[i]; i++) {
  25716. if (ci.value.indexOf(value) != -1)
  25717. return i;
  25718. }
  25719. }
  25720. return -1;
  25721. }
  25722. });
  25723. editorui.buttons['insertcode'] = ui;
  25724. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25725. if (!uiReady) {
  25726. var state = editor.queryCommandState('insertcode');
  25727. if (state == -1) {
  25728. ui.setDisabled(true);
  25729. } else {
  25730. ui.setDisabled(false);
  25731. var value = editor.queryCommandValue('insertcode');
  25732. if(!value){
  25733. ui.setValue(title);
  25734. return;
  25735. }
  25736. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25737. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25738. ui.setValue(value);
  25739. }
  25740. }
  25741. });
  25742. return ui;
  25743. };
  25744. editorui.fontfamily = function (editor, list, title) {
  25745. list = editor.options['fontfamily'] || [];
  25746. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25747. if (!list.length) return;
  25748. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25749. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25750. (function (key, val) {
  25751. items.push({
  25752. label:key,
  25753. value:val,
  25754. theme:editor.options.theme,
  25755. renderLabelHtml:function () {
  25756. return '<div class="edui-label %%-label" style="font-family:' +
  25757. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25758. }
  25759. });
  25760. })(ci.label || langLabel, ci.val)
  25761. }
  25762. var ui = new editorui.Combox({
  25763. editor:editor,
  25764. items:items,
  25765. onselect:function (t, index) {
  25766. editor.execCommand('FontFamily', this.items[index].value);
  25767. },
  25768. onbuttonclick:function () {
  25769. this.showPopup();
  25770. },
  25771. title:title,
  25772. initValue:title,
  25773. className:'edui-for-fontfamily',
  25774. indexByValue:function (value) {
  25775. if (value) {
  25776. for (var i = 0, ci; ci = this.items[i]; i++) {
  25777. if (ci.value.indexOf(value) != -1)
  25778. return i;
  25779. }
  25780. }
  25781. return -1;
  25782. }
  25783. });
  25784. editorui.buttons['fontfamily'] = ui;
  25785. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25786. if (!uiReady) {
  25787. var state = editor.queryCommandState('FontFamily');
  25788. if (state == -1) {
  25789. ui.setDisabled(true);
  25790. } else {
  25791. ui.setDisabled(false);
  25792. var value = editor.queryCommandValue('FontFamily');
  25793. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25794. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25795. ui.setValue(value);
  25796. }
  25797. }
  25798. });
  25799. return ui;
  25800. };
  25801. editorui.fontsize = function (editor, list, title) {
  25802. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25803. list = list || editor.options['fontsize'] || [];
  25804. if (!list.length) return;
  25805. var items = [];
  25806. for (var i = 0; i < list.length; i++) {
  25807. var size = list[i] + 'px';
  25808. items.push({
  25809. label:size,
  25810. value:size,
  25811. theme:editor.options.theme,
  25812. renderLabelHtml:function () {
  25813. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25814. this.value + '">' + (this.label || '') + '</div>';
  25815. }
  25816. });
  25817. }
  25818. var ui = new editorui.Combox({
  25819. editor:editor,
  25820. items:items,
  25821. title:title,
  25822. initValue:title,
  25823. onselect:function (t, index) {
  25824. editor.execCommand('FontSize', this.items[index].value);
  25825. },
  25826. onbuttonclick:function () {
  25827. this.showPopup();
  25828. },
  25829. className:'edui-for-fontsize'
  25830. });
  25831. editorui.buttons['fontsize'] = ui;
  25832. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25833. if (!uiReady) {
  25834. var state = editor.queryCommandState('FontSize');
  25835. if (state == -1) {
  25836. ui.setDisabled(true);
  25837. } else {
  25838. ui.setDisabled(false);
  25839. ui.setValue(editor.queryCommandValue('FontSize'));
  25840. }
  25841. }
  25842. });
  25843. return ui;
  25844. };
  25845. editorui.paragraph = function (editor, list, title) {
  25846. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25847. list = editor.options['paragraph'] || [];
  25848. if (utils.isEmptyObject(list)) return;
  25849. var items = [];
  25850. for (var i in list) {
  25851. items.push({
  25852. value:i,
  25853. label:list[i] || editor.getLang("paragraph")[i],
  25854. theme:editor.options.theme,
  25855. renderLabelHtml:function () {
  25856. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25857. }
  25858. })
  25859. }
  25860. var ui = new editorui.Combox({
  25861. editor:editor,
  25862. items:items,
  25863. title:title,
  25864. initValue:title,
  25865. className:'edui-for-paragraph',
  25866. onselect:function (t, index) {
  25867. editor.execCommand('Paragraph', this.items[index].value);
  25868. },
  25869. onbuttonclick:function () {
  25870. this.showPopup();
  25871. }
  25872. });
  25873. editorui.buttons['paragraph'] = ui;
  25874. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25875. if (!uiReady) {
  25876. var state = editor.queryCommandState('Paragraph');
  25877. if (state == -1) {
  25878. ui.setDisabled(true);
  25879. } else {
  25880. ui.setDisabled(false);
  25881. var value = editor.queryCommandValue('Paragraph');
  25882. var index = ui.indexByValue(value);
  25883. if (index != -1) {
  25884. ui.setValue(value);
  25885. } else {
  25886. ui.setValue(ui.initValue);
  25887. }
  25888. }
  25889. }
  25890. });
  25891. return ui;
  25892. };
  25893. //自定义标题
  25894. editorui.customstyle = function (editor) {
  25895. var list = editor.options['customstyle'] || [],
  25896. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25897. if (!list.length)return;
  25898. var langCs = editor.getLang('customstyle');
  25899. for (var i = 0, items = [], t; t = list[i++];) {
  25900. (function (t) {
  25901. var ck = {};
  25902. ck.label = t.label ? t.label : langCs[t.name];
  25903. ck.style = t.style;
  25904. ck.className = t.className;
  25905. ck.tag = t.tag;
  25906. items.push({
  25907. label:ck.label,
  25908. value:ck,
  25909. theme:editor.options.theme,
  25910. renderLabelHtml:function () {
  25911. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  25912. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  25913. + '</div>';
  25914. }
  25915. });
  25916. })(t);
  25917. }
  25918. var ui = new editorui.Combox({
  25919. editor:editor,
  25920. items:items,
  25921. title:title,
  25922. initValue:title,
  25923. className:'edui-for-customstyle',
  25924. onselect:function (t, index) {
  25925. editor.execCommand('customstyle', this.items[index].value);
  25926. },
  25927. onbuttonclick:function () {
  25928. this.showPopup();
  25929. },
  25930. indexByValue:function (value) {
  25931. for (var i = 0, ti; ti = this.items[i++];) {
  25932. if (ti.label == value) {
  25933. return i - 1
  25934. }
  25935. }
  25936. return -1;
  25937. }
  25938. });
  25939. editorui.buttons['customstyle'] = ui;
  25940. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25941. if (!uiReady) {
  25942. var state = editor.queryCommandState('customstyle');
  25943. if (state == -1) {
  25944. ui.setDisabled(true);
  25945. } else {
  25946. ui.setDisabled(false);
  25947. var value = editor.queryCommandValue('customstyle');
  25948. var index = ui.indexByValue(value);
  25949. if (index != -1) {
  25950. ui.setValue(value);
  25951. } else {
  25952. ui.setValue(ui.initValue);
  25953. }
  25954. }
  25955. }
  25956. });
  25957. return ui;
  25958. };
  25959. editorui.inserttable = function (editor, iframeUrl, title) {
  25960. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  25961. var ui = new editorui.TableButton({
  25962. editor:editor,
  25963. title:title,
  25964. className:'edui-for-inserttable',
  25965. onpicktable:function (t, numCols, numRows) {
  25966. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  25967. },
  25968. onbuttonclick:function () {
  25969. this.showPopup();
  25970. }
  25971. });
  25972. editorui.buttons['inserttable'] = ui;
  25973. editor.addListener('selectionchange', function () {
  25974. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  25975. });
  25976. return ui;
  25977. };
  25978. editorui.lineheight = function (editor) {
  25979. var val = editor.options.lineheight || [];
  25980. if (!val.length)return;
  25981. for (var i = 0, ci, items = []; ci = val[i++];) {
  25982. items.push({
  25983. //todo:写死了
  25984. label:ci,
  25985. value:ci,
  25986. theme:editor.options.theme,
  25987. onclick:function () {
  25988. editor.execCommand("lineheight", this.value);
  25989. }
  25990. })
  25991. }
  25992. var ui = new editorui.MenuButton({
  25993. editor:editor,
  25994. className:'edui-for-lineheight',
  25995. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  25996. items:items,
  25997. onbuttonclick:function () {
  25998. var value = editor.queryCommandValue('LineHeight') || this.value;
  25999. editor.execCommand("LineHeight", value);
  26000. }
  26001. });
  26002. editorui.buttons['lineheight'] = ui;
  26003. editor.addListener('selectionchange', function () {
  26004. var state = editor.queryCommandState('LineHeight');
  26005. if (state == -1) {
  26006. ui.setDisabled(true);
  26007. } else {
  26008. ui.setDisabled(false);
  26009. var value = editor.queryCommandValue('LineHeight');
  26010. value && ui.setValue((value + '').replace(/cm/, ''));
  26011. ui.setChecked(state)
  26012. }
  26013. });
  26014. return ui;
  26015. };
  26016. var rowspacings = ['top', 'bottom'];
  26017. for (var r = 0, ri; ri = rowspacings[r++];) {
  26018. (function (cmd) {
  26019. editorui['rowspacing' + cmd] = function (editor) {
  26020. var val = editor.options['rowspacing' + cmd] || [];
  26021. if (!val.length) return null;
  26022. for (var i = 0, ci, items = []; ci = val[i++];) {
  26023. items.push({
  26024. label:ci,
  26025. value:ci,
  26026. theme:editor.options.theme,
  26027. onclick:function () {
  26028. editor.execCommand("rowspacing", this.value, cmd);
  26029. }
  26030. })
  26031. }
  26032. var ui = new editorui.MenuButton({
  26033. editor:editor,
  26034. className:'edui-for-rowspacing' + cmd,
  26035. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26036. items:items,
  26037. onbuttonclick:function () {
  26038. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26039. editor.execCommand("rowspacing", value, cmd);
  26040. }
  26041. });
  26042. editorui.buttons[cmd] = ui;
  26043. editor.addListener('selectionchange', function () {
  26044. var state = editor.queryCommandState('rowspacing', cmd);
  26045. if (state == -1) {
  26046. ui.setDisabled(true);
  26047. } else {
  26048. ui.setDisabled(false);
  26049. var value = editor.queryCommandValue('rowspacing', cmd);
  26050. value && ui.setValue((value + '').replace(/%/, ''));
  26051. ui.setChecked(state)
  26052. }
  26053. });
  26054. return ui;
  26055. }
  26056. })(ri)
  26057. }
  26058. //有序,无序列表
  26059. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26060. for (var l = 0, cl; cl = lists[l++];) {
  26061. (function (cmd) {
  26062. editorui[cmd] = function (editor) {
  26063. var vals = editor.options[cmd],
  26064. _onMenuClick = function () {
  26065. editor.execCommand(cmd, this.value);
  26066. }, items = [];
  26067. for (var i in vals) {
  26068. items.push({
  26069. label:vals[i] || editor.getLang()[cmd][i] || "",
  26070. value:i,
  26071. theme:editor.options.theme,
  26072. onclick:_onMenuClick
  26073. })
  26074. }
  26075. var ui = new editorui.MenuButton({
  26076. editor:editor,
  26077. className:'edui-for-' + cmd,
  26078. title:editor.getLang("labelMap." + cmd) || '',
  26079. 'items':items,
  26080. onbuttonclick:function () {
  26081. var value = editor.queryCommandValue(cmd) || this.value;
  26082. editor.execCommand(cmd, value);
  26083. }
  26084. });
  26085. editorui.buttons[cmd] = ui;
  26086. editor.addListener('selectionchange', function () {
  26087. var state = editor.queryCommandState(cmd);
  26088. if (state == -1) {
  26089. ui.setDisabled(true);
  26090. } else {
  26091. ui.setDisabled(false);
  26092. var value = editor.queryCommandValue(cmd);
  26093. ui.setValue(value);
  26094. ui.setChecked(state)
  26095. }
  26096. });
  26097. return ui;
  26098. };
  26099. })(cl)
  26100. }
  26101. editorui.fullscreen = function (editor, title) {
  26102. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26103. var ui = new editorui.Button({
  26104. className:'edui-for-fullscreen',
  26105. title:title,
  26106. theme:editor.options.theme,
  26107. onclick:function () {
  26108. if (editor.ui) {
  26109. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26110. }
  26111. this.setChecked(editor.ui.isFullScreen());
  26112. }
  26113. });
  26114. editorui.buttons['fullscreen'] = ui;
  26115. editor.addListener('selectionchange', function () {
  26116. var state = editor.queryCommandState('fullscreen');
  26117. ui.setDisabled(state == -1);
  26118. ui.setChecked(editor.ui.isFullScreen());
  26119. });
  26120. return ui;
  26121. };
  26122. // 表情
  26123. editorui["emotion"] = function (editor, iframeUrl) {
  26124. var cmd = "emotion";
  26125. var ui = new editorui.MultiMenuPop({
  26126. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26127. editor:editor,
  26128. className:'edui-for-' + cmd,
  26129. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26130. });
  26131. editorui.buttons[cmd] = ui;
  26132. editor.addListener('selectionchange', function () {
  26133. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26134. });
  26135. return ui;
  26136. };
  26137. editorui.autotypeset = function (editor) {
  26138. var ui = new editorui.AutoTypeSetButton({
  26139. editor:editor,
  26140. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26141. className:'edui-for-autotypeset',
  26142. onbuttonclick:function () {
  26143. editor.execCommand('autotypeset')
  26144. }
  26145. });
  26146. editorui.buttons['autotypeset'] = ui;
  26147. editor.addListener('selectionchange', function () {
  26148. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26149. });
  26150. return ui;
  26151. };
  26152. /* 简单上传插件 */
  26153. editorui["simpleupload"] = function (editor) {
  26154. var name = 'simpleupload',
  26155. ui = new editorui.Button({
  26156. className:'edui-for-' + name,
  26157. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26158. onclick:function () {},
  26159. theme:editor.options.theme,
  26160. showText:false
  26161. });
  26162. editorui.buttons[name] = ui;
  26163. editor.addListener('ready', function() {
  26164. var b = ui.getDom('body'),
  26165. iconSpan = b.children[0];
  26166. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26167. });
  26168. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26169. var state = editor.queryCommandState(name);
  26170. if (state == -1) {
  26171. ui.setDisabled(true);
  26172. ui.setChecked(false);
  26173. } else {
  26174. if (!uiReady) {
  26175. ui.setDisabled(false);
  26176. ui.setChecked(state);
  26177. }
  26178. }
  26179. });
  26180. return ui;
  26181. };
  26182. })();
  26183. // adapter/editor.js
  26184. ///import core
  26185. ///commands 全屏
  26186. ///commandsName FullScreen
  26187. ///commandsTitle 全屏
  26188. (function () {
  26189. var utils = baidu.editor.utils,
  26190. uiUtils = baidu.editor.ui.uiUtils,
  26191. UIBase = baidu.editor.ui.UIBase,
  26192. domUtils = baidu.editor.dom.domUtils;
  26193. var nodeStack = [];
  26194. function EditorUI(options) {
  26195. this.initOptions(options);
  26196. this.initEditorUI();
  26197. }
  26198. EditorUI.prototype = {
  26199. uiName:'editor',
  26200. initEditorUI:function () {
  26201. this.editor.ui = this;
  26202. this._dialogs = {};
  26203. this.initUIBase();
  26204. this._initToolbars();
  26205. var editor = this.editor,
  26206. me = this;
  26207. editor.addListener('ready', function () {
  26208. //提供getDialog方法
  26209. editor.getDialog = function (name) {
  26210. return editor.ui._dialogs[name + "Dialog"];
  26211. };
  26212. domUtils.on(editor.window, 'scroll', function (evt) {
  26213. baidu.editor.ui.Popup.postHide(evt);
  26214. });
  26215. //提供编辑器实时宽高(全屏时宽高不变化)
  26216. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26217. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26218. //display bottom-bar label based on config
  26219. if (editor.options.elementPathEnabled) {
  26220. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26221. }
  26222. if (editor.options.wordCount) {
  26223. function countFn() {
  26224. setCount(editor,me);
  26225. domUtils.un(editor.document, "click", arguments.callee);
  26226. }
  26227. domUtils.on(editor.document, "click", countFn);
  26228. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26229. }
  26230. editor.ui._scale();
  26231. if (editor.options.scaleEnabled) {
  26232. if (editor.autoHeightEnabled) {
  26233. editor.disableAutoHeight();
  26234. }
  26235. me.enableScale();
  26236. } else {
  26237. me.disableScale();
  26238. }
  26239. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26240. editor.ui.getDom('elementpath').style.display = "none";
  26241. editor.ui.getDom('wordcount').style.display = "none";
  26242. editor.ui.getDom('scale').style.display = "none";
  26243. }
  26244. if (!editor.selection.isFocus())return;
  26245. editor.fireEvent('selectionchange', false, true);
  26246. });
  26247. editor.addListener('mousedown', function (t, evt) {
  26248. var el = evt.target || evt.srcElement;
  26249. baidu.editor.ui.Popup.postHide(evt, el);
  26250. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26251. });
  26252. editor.addListener("delcells", function () {
  26253. if (UE.ui['edittip']) {
  26254. new UE.ui['edittip'](editor);
  26255. }
  26256. editor.getDialog('edittip').open();
  26257. });
  26258. var pastePop, isPaste = false, timer;
  26259. editor.addListener("afterpaste", function () {
  26260. if(editor.queryCommandState('pasteplain'))
  26261. return;
  26262. if(baidu.editor.ui.PastePicker){
  26263. pastePop = new baidu.editor.ui.Popup({
  26264. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26265. editor:editor,
  26266. className:'edui-wordpastepop'
  26267. });
  26268. pastePop.render();
  26269. }
  26270. isPaste = true;
  26271. });
  26272. editor.addListener("afterinserthtml", function () {
  26273. clearTimeout(timer);
  26274. timer = setTimeout(function () {
  26275. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26276. if(pastePop.isHidden()){
  26277. var span = domUtils.createElement(editor.document, 'span', {
  26278. 'style':"line-height:0px;",
  26279. 'innerHTML':'\ufeff'
  26280. }),
  26281. range = editor.selection.getRange();
  26282. range.insertNode(span);
  26283. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26284. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26285. domUtils.remove(span);
  26286. }else{
  26287. pastePop.show();
  26288. }
  26289. delete editor.ui._isTransfer;
  26290. isPaste = false;
  26291. }
  26292. }, 200)
  26293. });
  26294. editor.addListener('contextmenu', function (t, evt) {
  26295. baidu.editor.ui.Popup.postHide(evt);
  26296. });
  26297. editor.addListener('keydown', function (t, evt) {
  26298. if (pastePop) pastePop.dispose(evt);
  26299. var keyCode = evt.keyCode || evt.which;
  26300. if(evt.altKey&&keyCode==90){
  26301. UE.ui.buttons['fullscreen'].onclick();
  26302. }
  26303. });
  26304. editor.addListener('wordcount', function (type) {
  26305. setCount(this,me);
  26306. });
  26307. function setCount(editor,ui) {
  26308. editor.setOpt({
  26309. wordCount:true,
  26310. maximumWords:10000,
  26311. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26312. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26313. });
  26314. var opt = editor.options,
  26315. max = opt.maximumWords,
  26316. msg = opt.wordCountMsg ,
  26317. errMsg = opt.wordOverFlowMsg,
  26318. countDom = ui.getDom('wordcount');
  26319. if (!opt.wordCount) {
  26320. return;
  26321. }
  26322. var count = editor.getContentLength(true);
  26323. if (count > max) {
  26324. countDom.innerHTML = errMsg;
  26325. editor.fireEvent("wordcountoverflow");
  26326. } else {
  26327. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26328. }
  26329. }
  26330. editor.addListener('selectionchange', function () {
  26331. if (editor.options.elementPathEnabled) {
  26332. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26333. }
  26334. if (editor.options.scaleEnabled) {
  26335. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26336. }
  26337. });
  26338. var popup = new baidu.editor.ui.Popup({
  26339. editor:editor,
  26340. content:'',
  26341. className:'edui-bubble',
  26342. _onEditButtonClick:function () {
  26343. this.hide();
  26344. editor.ui._dialogs.linkDialog.open();
  26345. },
  26346. _onImgEditButtonClick:function (name) {
  26347. this.hide();
  26348. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26349. },
  26350. _onImgSetFloat:function (value) {
  26351. this.hide();
  26352. editor.execCommand("imagefloat", value);
  26353. },
  26354. _setIframeAlign:function (value) {
  26355. var frame = popup.anchorEl;
  26356. var newFrame = frame.cloneNode(true);
  26357. switch (value) {
  26358. case -2:
  26359. newFrame.setAttribute("align", "");
  26360. break;
  26361. case -1:
  26362. newFrame.setAttribute("align", "left");
  26363. break;
  26364. case 1:
  26365. newFrame.setAttribute("align", "right");
  26366. break;
  26367. }
  26368. frame.parentNode.insertBefore(newFrame, frame);
  26369. domUtils.remove(frame);
  26370. popup.anchorEl = newFrame;
  26371. popup.showAnchor(popup.anchorEl);
  26372. },
  26373. _updateIframe:function () {
  26374. var frame = editor._iframe = popup.anchorEl;
  26375. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26376. editor.selection.getRange().selectNode(frame).select();
  26377. editor.ui._dialogs.mapDialog.open();
  26378. popup.hide();
  26379. } else {
  26380. editor.ui._dialogs.insertframeDialog.open();
  26381. popup.hide();
  26382. }
  26383. },
  26384. _onRemoveButtonClick:function (cmdName) {
  26385. editor.execCommand(cmdName);
  26386. this.hide();
  26387. },
  26388. queryAutoHide:function (el) {
  26389. if (el && el.ownerDocument == editor.document) {
  26390. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26391. return el !== popup.anchorEl;
  26392. }
  26393. }
  26394. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26395. }
  26396. });
  26397. popup.render();
  26398. if (editor.options.imagePopup) {
  26399. editor.addListener('mouseover', function (t, evt) {
  26400. evt = evt || window.event;
  26401. var el = evt.target || evt.srcElement;
  26402. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26403. var html = popup.formatHtml(
  26404. '<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;' +
  26405. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26406. if (html) {
  26407. popup.getDom('content').innerHTML = html;
  26408. popup.anchorEl = el;
  26409. popup.showAnchor(popup.anchorEl);
  26410. } else {
  26411. popup.hide();
  26412. }
  26413. }
  26414. });
  26415. editor.addListener('selectionchange', function (t, causeByUi) {
  26416. if (!causeByUi) return;
  26417. var html = '', str = "",
  26418. img = editor.selection.getRange().getClosedNode(),
  26419. dialogs = editor.ui._dialogs;
  26420. if (img && img.tagName == 'IMG') {
  26421. var dialogName = 'insertimageDialog';
  26422. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26423. dialogName = "insertvideoDialog"
  26424. }
  26425. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26426. dialogName = "webappDialog"
  26427. }
  26428. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26429. dialogName = "mapDialog"
  26430. }
  26431. if (img.className.indexOf("edui-faked-music") != -1) {
  26432. dialogName = "musicDialog"
  26433. }
  26434. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26435. dialogName = "gmapDialog"
  26436. }
  26437. if (img.getAttribute("anchorname")) {
  26438. dialogName = "anchorDialog";
  26439. html = popup.formatHtml(
  26440. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26441. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26442. }
  26443. if (img.getAttribute("word_img")) {
  26444. //todo 放到dialog去做查询
  26445. editor.word_img = [img.getAttribute("word_img")];
  26446. dialogName = "wordimageDialog"
  26447. }
  26448. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26449. dialogName = "";
  26450. }
  26451. if (!dialogs[dialogName]) {
  26452. return;
  26453. }
  26454. str = '<nobr>' + editor.getLang("property") + ': '+
  26455. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26456. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26457. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26458. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26459. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26460. !html && (html = popup.formatHtml(str))
  26461. }
  26462. if (editor.ui._dialogs.linkDialog) {
  26463. var link = editor.queryCommandValue('link');
  26464. var url;
  26465. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26466. var txt = url;
  26467. if (url.length > 30) {
  26468. txt = url.substring(0, 20) + "...";
  26469. }
  26470. if (html) {
  26471. html += '<div style="height:5px;"></div>'
  26472. }
  26473. html += popup.formatHtml(
  26474. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26475. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26476. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26477. popup.showAnchor(link);
  26478. }
  26479. }
  26480. if (html) {
  26481. popup.getDom('content').innerHTML = html;
  26482. popup.anchorEl = img || link;
  26483. popup.showAnchor(popup.anchorEl);
  26484. } else {
  26485. popup.hide();
  26486. }
  26487. });
  26488. }
  26489. },
  26490. _initToolbars:function () {
  26491. var editor = this.editor;
  26492. var toolbars = this.toolbars || [];
  26493. var toolbarUis = [];
  26494. for (var i = 0; i < toolbars.length; i++) {
  26495. var toolbar = toolbars[i];
  26496. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26497. for (var j = 0; j < toolbar.length; j++) {
  26498. var toolbarItem = toolbar[j];
  26499. var toolbarItemUi = null;
  26500. if (typeof toolbarItem == 'string') {
  26501. toolbarItem = toolbarItem.toLowerCase();
  26502. if (toolbarItem == '|') {
  26503. toolbarItem = 'Separator';
  26504. }
  26505. if(toolbarItem == '||'){
  26506. toolbarItem = 'Breakline';
  26507. }
  26508. if (baidu.editor.ui[toolbarItem]) {
  26509. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26510. }
  26511. //fullscreen这里单独处理一下,放到首行去
  26512. if (toolbarItem == 'fullscreen') {
  26513. if (toolbarUis && toolbarUis[0]) {
  26514. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26515. } else {
  26516. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26517. }
  26518. continue;
  26519. }
  26520. } else {
  26521. toolbarItemUi = toolbarItem;
  26522. }
  26523. if (toolbarItemUi && toolbarItemUi.id) {
  26524. toolbarUi.add(toolbarItemUi);
  26525. }
  26526. }
  26527. toolbarUis[i] = toolbarUi;
  26528. }
  26529. //接受外部定制的UI(修复因 utils.each 无法准确的循环出对象的全部元素而导致的自定义 UI 不符合预期的 BUG by HaoChuan9421)
  26530. // utils.each(UE._customizeUI,function(obj,key){
  26531. // var itemUI,index;
  26532. // if(obj.id && obj.id != editor.key){
  26533. // return false;
  26534. // }
  26535. // itemUI = obj.execFn.call(editor,editor,key);
  26536. // if(itemUI){
  26537. // index = obj.index;
  26538. // if(index === undefined){
  26539. // index = toolbarUi.items.length;
  26540. // }
  26541. // toolbarUi.add(itemUI,index)
  26542. // }
  26543. // });
  26544. for(var key in UE._customizeUI){
  26545. var obj = UE._customizeUI[key]
  26546. var itemUI,index;
  26547. if(!obj.id || obj.id == editor.key){
  26548. itemUI = obj.execFn.call(editor,editor,key);
  26549. if(itemUI){
  26550. index = obj.index;
  26551. if(index === undefined){
  26552. index = toolbarUi.items.length;
  26553. }
  26554. toolbarUi.add(itemUI,index)
  26555. }
  26556. }
  26557. }
  26558. this.toolbars = toolbarUis;
  26559. },
  26560. getHtmlTpl:function () {
  26561. return '<div id="##" class="%%">' +
  26562. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26563. (this.toolbars.length ?
  26564. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26565. this.renderToolbarBoxHtml() +
  26566. '</div></div>' : '') +
  26567. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26568. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26569. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26570. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26571. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26572. '</div>' +
  26573. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26574. '</div>' +
  26575. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26576. '</div>' +
  26577. //modify wdcount by matao
  26578. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26579. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26580. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26581. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26582. '</tr></table></div>' +
  26583. '<div id="##_scalelayer"></div>' +
  26584. '</div>';
  26585. },
  26586. showWordImageDialog:function () {
  26587. this._dialogs['wordimageDialog'].open();
  26588. },
  26589. renderToolbarBoxHtml:function () {
  26590. var buff = [];
  26591. for (var i = 0; i < this.toolbars.length; i++) {
  26592. buff.push(this.toolbars[i].renderHtml());
  26593. }
  26594. return buff.join('');
  26595. },
  26596. setFullScreen:function (fullscreen) {
  26597. var editor = this.editor,
  26598. container = editor.container.parentNode.parentNode;
  26599. if (this._fullscreen != fullscreen) {
  26600. this._fullscreen = fullscreen;
  26601. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26602. if (baidu.editor.browser.gecko) {
  26603. var bk = editor.selection.getRange().createBookmark();
  26604. }
  26605. if (fullscreen) {
  26606. while (container.tagName != "BODY") {
  26607. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26608. nodeStack.push(position);
  26609. container.style.position = "static";
  26610. container = container.parentNode;
  26611. }
  26612. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26613. this._bakBodyOverflow = document.body.style.overflow;
  26614. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26615. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26616. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26617. if (this._bakAutoHeight) {
  26618. //当全屏时不能执行自动长高
  26619. editor.autoHeightEnabled = false;
  26620. this.editor.disableAutoHeight();
  26621. }
  26622. document.documentElement.style.overflow = 'hidden';
  26623. //修复,滚动条不收起的问题
  26624. window.scrollTo(0,window.scrollY);
  26625. this._bakCssText = this.getDom().style.cssText;
  26626. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26627. editor.iframe.parentNode.style.width = '';
  26628. this._updateFullScreen();
  26629. } else {
  26630. while (container.tagName != "BODY") {
  26631. container.style.position = nodeStack.shift();
  26632. container = container.parentNode;
  26633. }
  26634. this.getDom().style.cssText = this._bakCssText;
  26635. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26636. if (this._bakAutoHeight) {
  26637. editor.autoHeightEnabled = true;
  26638. this.editor.enableAutoHeight();
  26639. }
  26640. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26641. document.body.style.overflow = this._bakBodyOverflow;
  26642. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26643. window.scrollTo(0, this._bakScrollTop);
  26644. }
  26645. if (browser.gecko && editor.body.contentEditable === 'true') {
  26646. var input = document.createElement('input');
  26647. document.body.appendChild(input);
  26648. editor.body.contentEditable = false;
  26649. setTimeout(function () {
  26650. input.focus();
  26651. setTimeout(function () {
  26652. editor.body.contentEditable = true;
  26653. editor.fireEvent('fullscreenchanged', fullscreen);
  26654. editor.selection.getRange().moveToBookmark(bk).select(true);
  26655. baidu.editor.dom.domUtils.remove(input);
  26656. fullscreen && window.scroll(0, 0);
  26657. }, 0)
  26658. }, 0)
  26659. }
  26660. if(editor.body.contentEditable === 'true'){
  26661. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26662. this.triggerLayout();
  26663. }
  26664. }
  26665. },
  26666. _updateFullScreen:function () {
  26667. if (this._fullscreen) {
  26668. var vpRect = uiUtils.getViewportRect();
  26669. 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);
  26670. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26671. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26672. //不手动调一下,会导致全屏失效
  26673. if(browser.gecko){
  26674. try{
  26675. window.onresize();
  26676. }catch(e){
  26677. }
  26678. }
  26679. }
  26680. },
  26681. _updateElementPath:function () {
  26682. var bottom = this.getDom('elementpath'), list;
  26683. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26684. var buff = [];
  26685. for (var i = 0, ci; ci = list[i]; i++) {
  26686. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26687. }
  26688. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26689. } else {
  26690. bottom.style.display = 'none'
  26691. }
  26692. },
  26693. disableElementPath:function () {
  26694. var bottom = this.getDom('elementpath');
  26695. bottom.innerHTML = '';
  26696. bottom.style.display = 'none';
  26697. this.elementPathEnabled = false;
  26698. },
  26699. enableElementPath:function () {
  26700. var bottom = this.getDom('elementpath');
  26701. bottom.style.display = '';
  26702. this.elementPathEnabled = true;
  26703. this._updateElementPath();
  26704. },
  26705. _scale:function () {
  26706. var doc = document,
  26707. editor = this.editor,
  26708. editorHolder = editor.container,
  26709. editorDocument = editor.document,
  26710. toolbarBox = this.getDom("toolbarbox"),
  26711. bottombar = this.getDom("bottombar"),
  26712. scale = this.getDom("scale"),
  26713. scalelayer = this.getDom("scalelayer");
  26714. var isMouseMove = false,
  26715. position = null,
  26716. minEditorHeight = 0,
  26717. minEditorWidth = editor.options.minFrameWidth,
  26718. pageX = 0,
  26719. pageY = 0,
  26720. scaleWidth = 0,
  26721. scaleHeight = 0;
  26722. function down() {
  26723. position = domUtils.getXY(editorHolder);
  26724. if (!minEditorHeight) {
  26725. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26726. }
  26727. 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:"
  26728. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26729. domUtils.on(doc, "mousemove", move);
  26730. domUtils.on(editorDocument, "mouseup", up);
  26731. domUtils.on(doc, "mouseup", up);
  26732. }
  26733. var me = this;
  26734. //by xuheng 全屏时关掉缩放
  26735. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26736. if (fullScreen) {
  26737. me.disableScale();
  26738. } else {
  26739. if (me.editor.options.scaleEnabled) {
  26740. me.enableScale();
  26741. var tmpNode = me.editor.document.createElement('span');
  26742. me.editor.body.appendChild(tmpNode);
  26743. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26744. domUtils.remove(tmpNode)
  26745. }
  26746. }
  26747. });
  26748. function move(event) {
  26749. clearSelection();
  26750. var e = event || window.event;
  26751. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26752. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26753. scaleWidth = pageX - position.x;
  26754. scaleHeight = pageY - position.y;
  26755. if (scaleWidth >= minEditorWidth) {
  26756. isMouseMove = true;
  26757. scalelayer.style.width = scaleWidth + 'px';
  26758. }
  26759. if (scaleHeight >= minEditorHeight) {
  26760. isMouseMove = true;
  26761. scalelayer.style.height = scaleHeight + "px";
  26762. }
  26763. }
  26764. function up() {
  26765. if (isMouseMove) {
  26766. isMouseMove = false;
  26767. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26768. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26769. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26770. }
  26771. if (scalelayer) {
  26772. scalelayer.style.display = "none";
  26773. }
  26774. clearSelection();
  26775. domUtils.un(doc, "mousemove", move);
  26776. domUtils.un(editorDocument, "mouseup", up);
  26777. domUtils.un(doc, "mouseup", up);
  26778. }
  26779. function clearSelection() {
  26780. if (browser.ie)
  26781. doc.selection.clear();
  26782. else
  26783. window.getSelection().removeAllRanges();
  26784. }
  26785. this.enableScale = function () {
  26786. //trace:2868
  26787. if (editor.queryCommandState("source") == 1) return;
  26788. scale.style.display = "";
  26789. this.scaleEnabled = true;
  26790. domUtils.on(scale, "mousedown", down);
  26791. };
  26792. this.disableScale = function () {
  26793. scale.style.display = "none";
  26794. this.scaleEnabled = false;
  26795. domUtils.un(scale, "mousedown", down);
  26796. };
  26797. },
  26798. isFullScreen:function () {
  26799. return this._fullscreen;
  26800. },
  26801. postRender:function () {
  26802. UIBase.prototype.postRender.call(this);
  26803. for (var i = 0; i < this.toolbars.length; i++) {
  26804. this.toolbars[i].postRender();
  26805. }
  26806. var me = this;
  26807. var timerId,
  26808. domUtils = baidu.editor.dom.domUtils,
  26809. updateFullScreenTime = function () {
  26810. clearTimeout(timerId);
  26811. timerId = setTimeout(function () {
  26812. me._updateFullScreen();
  26813. });
  26814. };
  26815. domUtils.on(window, 'resize', updateFullScreenTime);
  26816. me.addListener('destroy', function () {
  26817. domUtils.un(window, 'resize', updateFullScreenTime);
  26818. clearTimeout(timerId);
  26819. })
  26820. },
  26821. showToolbarMsg:function (msg, flag) {
  26822. this.getDom('toolbarmsg_label').innerHTML = msg;
  26823. this.getDom('toolbarmsg').style.display = '';
  26824. //
  26825. if (!flag) {
  26826. var w = this.getDom('upload_dialog');
  26827. w.style.display = 'none';
  26828. }
  26829. },
  26830. hideToolbarMsg:function () {
  26831. this.getDom('toolbarmsg').style.display = 'none';
  26832. },
  26833. mapUrl:function (url) {
  26834. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26835. },
  26836. triggerLayout:function () {
  26837. var dom = this.getDom();
  26838. if (dom.style.zoom == '1') {
  26839. dom.style.zoom = '100%';
  26840. } else {
  26841. dom.style.zoom = '1';
  26842. }
  26843. }
  26844. };
  26845. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26846. var instances = {};
  26847. UE.ui.Editor = function (options) {
  26848. var editor = new UE.Editor(options);
  26849. editor.options.editor = editor;
  26850. utils.loadFile(document, {
  26851. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26852. tag:"link",
  26853. type:"text/css",
  26854. rel:"stylesheet"
  26855. });
  26856. var oldRender = editor.render;
  26857. editor.render = function (holder) {
  26858. if (holder.constructor === String) {
  26859. editor.key = holder;
  26860. instances[holder] = editor;
  26861. }
  26862. utils.domReady(function () {
  26863. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26864. function renderUI() {
  26865. editor.setOpt({
  26866. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26867. });
  26868. new EditorUI(editor.options);
  26869. if (holder) {
  26870. if (holder.constructor === String) {
  26871. holder = document.getElementById(holder);
  26872. }
  26873. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26874. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26875. var newDiv = document.createElement('div');
  26876. holder.parentNode.insertBefore(newDiv, holder);
  26877. var cont = holder.value || holder.innerHTML;
  26878. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26879. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26880. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26881. .replace(/>[\n\r\t]+</g, '><');
  26882. holder.className && (newDiv.className = holder.className);
  26883. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26884. if (/textarea/i.test(holder.tagName)) {
  26885. editor.textarea = holder;
  26886. editor.textarea.style.display = 'none';
  26887. } else {
  26888. holder.parentNode.removeChild(holder);
  26889. }
  26890. if(holder.id){
  26891. newDiv.id = holder.id;
  26892. domUtils.removeAttributes(holder,'id');
  26893. }
  26894. holder = newDiv;
  26895. holder.innerHTML = '';
  26896. }
  26897. }
  26898. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26899. editor.ui.render(holder);
  26900. var opt = editor.options;
  26901. //给实例添加一个编辑器的容器引用
  26902. editor.container = editor.ui.getDom();
  26903. var parents = domUtils.findParents(holder,true);
  26904. var displays = [];
  26905. for(var i = 0 ,ci;ci=parents[i];i++){
  26906. displays[i] = ci.style.display;
  26907. ci.style.display = 'block'
  26908. }
  26909. if (opt.initialFrameWidth) {
  26910. opt.minFrameWidth = opt.initialFrameWidth;
  26911. } else {
  26912. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  26913. var styleWidth = holder.style.width;
  26914. if(/%$/.test(styleWidth)) {
  26915. opt.initialFrameWidth = styleWidth;
  26916. }
  26917. }
  26918. if (opt.initialFrameHeight) {
  26919. opt.minFrameHeight = opt.initialFrameHeight;
  26920. } else {
  26921. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  26922. }
  26923. for(var i = 0 ,ci;ci=parents[i];i++){
  26924. ci.style.display = displays[i]
  26925. }
  26926. //编辑器最外容器设置了高度,会导致,编辑器不占位
  26927. //todo 先去掉,没有找到原因
  26928. if(holder.style.height){
  26929. holder.style.height = ''
  26930. }
  26931. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  26932. editor.container.style.zIndex = opt.zIndex;
  26933. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  26934. editor.fireEvent("afteruiready");
  26935. }
  26936. })
  26937. };
  26938. return editor;
  26939. };
  26940. /**
  26941. * @file
  26942. * @name UE
  26943. * @short UE
  26944. * @desc UEditor的顶部命名空间
  26945. */
  26946. /**
  26947. * @name getEditor
  26948. * @since 1.2.4+
  26949. * @grammar UE.getEditor(id,[opt]) => Editor实例
  26950. * @desc 提供一个全局的方法得到编辑器实例
  26951. *
  26952. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  26953. * * ''opt'' 编辑器的可选参数
  26954. * @example
  26955. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  26956. * this.setContent('hello')
  26957. * }});
  26958. * UE.getEditor('containerId'); //返回刚创建的实例
  26959. *
  26960. */
  26961. UE.getEditor = function (id, opt) {
  26962. var editor = instances[id];
  26963. if (!editor) {
  26964. editor = instances[id] = new UE.ui.Editor(opt);
  26965. editor.render(id);
  26966. }
  26967. return editor;
  26968. };
  26969. UE.delEditor = function (id) {
  26970. var editor;
  26971. if (editor = instances[id]) {
  26972. editor.key && editor.destroy();
  26973. delete instances[id]
  26974. }
  26975. };
  26976. UE.registerUI = function(uiName,fn,index,editorId){
  26977. utils.each(uiName.split(/\s+/), function (name) {
  26978. UE._customizeUI[name] = {
  26979. id : editorId,
  26980. execFn:fn,
  26981. index:index
  26982. };
  26983. })
  26984. }
  26985. })();
  26986. // adapter/message.js
  26987. UE.registerUI('message', function(editor) {
  26988. var editorui = baidu.editor.ui;
  26989. var Message = editorui.Message;
  26990. var holder;
  26991. var _messageItems = [];
  26992. var me = editor;
  26993. me.addListener('ready', function(){
  26994. holder = document.getElementById(me.ui.id + '_message_holder');
  26995. updateHolderPos();
  26996. // HaoChuan9421
  26997. // setTimeout(function(){
  26998. // updateHolderPos();
  26999. // }, 500);
  27000. });
  27001. me.addListener('showmessage', function(type, opt){
  27002. opt = utils.isString(opt) ? {
  27003. 'content': opt
  27004. } : opt;
  27005. var message = new Message({
  27006. 'timeout': opt.timeout,
  27007. 'type': opt.type,
  27008. 'content': opt.content,
  27009. 'keepshow': opt.keepshow,
  27010. 'editor': me
  27011. }),
  27012. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27013. message.render(holder);
  27014. _messageItems[mid] = message;
  27015. message.reset(opt);
  27016. updateHolderPos();
  27017. return mid;
  27018. });
  27019. me.addListener('updatemessage',function(type, id, opt){
  27020. opt = utils.isString(opt) ? {
  27021. 'content': opt
  27022. } : opt;
  27023. var message = _messageItems[id];
  27024. message.render(holder);
  27025. message && message.reset(opt);
  27026. });
  27027. me.addListener('hidemessage',function(type, id){
  27028. var message = _messageItems[id];
  27029. message && message.hide();
  27030. });
  27031. function updateHolderPos(){
  27032. var toolbarbox = me.ui.getDom('toolbarbox');
  27033. if (toolbarbox) {
  27034. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27035. }
  27036. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27037. }
  27038. });
  27039. // adapter/autosave.js
  27040. UE.registerUI('autosave', function(editor) {
  27041. var timer = null,uid = null;
  27042. editor.on('afterautosave',function(){
  27043. clearTimeout(timer);
  27044. timer = setTimeout(function(){
  27045. if(uid){
  27046. editor.trigger('hidemessage',uid);
  27047. }
  27048. uid = editor.trigger('showmessage',{
  27049. content : editor.getLang('autosave.success'),
  27050. timeout : 2000
  27051. });
  27052. },2000)
  27053. })
  27054. });
  27055. })();