ueditor.all.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Wed Dec 26 2018 17:25:05 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. geckoRelease = geckoRelease[1].split('.');
  177. version = geckoRelease[0] * 10000 + (geckoRelease[1] || 0) * 100 + (geckoRelease[2] || 0) * 1;
  178. }
  179. }
  180. /**
  181. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  182. * @warning 如果浏览器不是chrome, 则该值为undefined
  183. * @example
  184. * ```javascript
  185. * if ( UE.browser.chrome ) {
  186. * console.log( '当前浏览器是Chrome' );
  187. * }
  188. * ```
  189. */
  190. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  191. browser.chrome = +RegExp['\x241'];
  192. }
  193. /**
  194. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  195. * @warning 如果浏览器不是safari, 则该值为undefined
  196. * @example
  197. * ```javascript
  198. * if ( UE.browser.safari ) {
  199. * console.log( '当前浏览器是Safari' );
  200. * }
  201. * ```
  202. */
  203. if (/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)) {
  204. browser.safari = +(RegExp['\x241'] || RegExp['\x242']);
  205. }
  206. // Opera 9.50+
  207. if (browser.opera)
  208. version = parseFloat(opera.version());
  209. // WebKit 522+ (Safari 3+)
  210. if (browser.webkit)
  211. version = parseFloat(agent.match(/ applewebkit\/(\d+)/)[1]);
  212. /**
  213. * @property { Number } version 检测当前浏览器版本号
  214. * @remind
  215. * <ul>
  216. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  217. * <li>gecko系列会返回10900,158900等</li>
  218. * <li>webkit系列会返回其build号 (如 522等)</li>
  219. * </ul>
  220. * @example
  221. * ```javascript
  222. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  223. * ```
  224. */
  225. browser.version = version;
  226. /**
  227. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  228. * @example
  229. * ```javascript
  230. * if ( UE.browser.isCompatible ) {
  231. * console.log( '浏览器与UEditor能够良好兼容' );
  232. * }
  233. * ```
  234. */
  235. browser.isCompatible =
  236. !browser.mobile && (
  237. (browser.ie && version >= 6) ||
  238. (browser.gecko && version >= 10801) ||
  239. (browser.opera && version >= 9.5) ||
  240. (browser.air && version >= 1) ||
  241. (browser.webkit && version >= 522) ||
  242. false);
  243. return browser;
  244. }();
  245. //快捷方式
  246. var ie = browser.ie,
  247. webkit = browser.webkit,
  248. gecko = browser.gecko,
  249. opera = browser.opera;
  250. // core/utils.js
  251. /**
  252. * 工具函数包
  253. * @file
  254. * @module UE.utils
  255. * @since 1.2.6.1
  256. */
  257. /**
  258. * UEditor封装使用的静态工具函数
  259. * @module UE.utils
  260. * @unfile
  261. */
  262. var utils = UE.utils = {
  263. /**
  264. * 用给定的迭代器遍历对象
  265. * @method each
  266. * @param { Object } obj 需要遍历的对象
  267. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  268. * @example
  269. * ```javascript
  270. * var demoObj = {
  271. * key1: 1,
  272. * key2: 2
  273. * };
  274. *
  275. * //output: key1: 1, key2: 2
  276. * UE.utils.each( demoObj, funciton ( value, key ) {
  277. *
  278. * console.log( key + ":" + value );
  279. *
  280. * } );
  281. * ```
  282. */
  283. /**
  284. * 用给定的迭代器遍历数组或类数组对象
  285. * @method each
  286. * @param { Array } array 需要遍历的数组或者类数组
  287. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  288. * @example
  289. * ```javascript
  290. * var divs = document.getElmentByTagNames( "div" );
  291. *
  292. * //output: 0: DIV, 1: DIV ...
  293. * UE.utils.each( divs, funciton ( value, key ) {
  294. *
  295. * console.log( key + ":" + value.tagName );
  296. *
  297. * } );
  298. * ```
  299. */
  300. each: function (obj, iterator, context) {
  301. if (obj == null) return;
  302. if (obj.length === +obj.length) {
  303. for (var i = 0, l = obj.length; i < l; i++) {
  304. if (iterator.call(context, obj[i], i, obj) === false)
  305. return false;
  306. }
  307. } else {
  308. for (var key in obj) {
  309. if (obj.hasOwnProperty(key)) {
  310. if (iterator.call(context, obj[key], key, obj) === false)
  311. return false;
  312. }
  313. }
  314. }
  315. },
  316. /**
  317. * 以给定对象作为原型创建一个新对象
  318. * @method makeInstance
  319. * @param { Object } protoObject 该对象将作为新创建对象的原型
  320. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  321. * @example
  322. * ```javascript
  323. *
  324. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  325. *
  326. * var newObject = UE.utils.makeInstance( protoObject );
  327. * //output: Hello UEditor!
  328. * newObject.sayHello();
  329. * ```
  330. */
  331. makeInstance: function (obj) {
  332. var noop = new Function();
  333. noop.prototype = obj;
  334. obj = new noop;
  335. noop.prototype = null;
  336. return obj;
  337. },
  338. /**
  339. * 将source对象中的属性扩展到target对象上
  340. * @method extend
  341. * @remind 该方法将强制把source对象上的属性复制到target对象上
  342. * @see UE.utils.extend(Object,Object,Boolean)
  343. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  344. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  345. * @return { Object } 返回target对象
  346. * @example
  347. * ```javascript
  348. *
  349. * var target = { name: 'target', sex: 1 },
  350. * source = { name: 'source', age: 17 };
  351. *
  352. * UE.utils.extend( target, source );
  353. *
  354. * //output: { name: 'source', sex: 1, age: 17 }
  355. * console.log( target );
  356. *
  357. * ```
  358. */
  359. /**
  360. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  361. * 源对象属性名相同的属性值。
  362. * @method extend
  363. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  364. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  365. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  366. * @return { Object } 返回target对象
  367. * @example
  368. * ```javascript
  369. *
  370. * var target = { name: 'target', sex: 1 },
  371. * source = { name: 'source', age: 17 };
  372. *
  373. * UE.utils.extend( target, source, true );
  374. *
  375. * //output: { name: 'target', sex: 1, age: 17 }
  376. * console.log( target );
  377. *
  378. * ```
  379. */
  380. extend: function (t, s, b) {
  381. if (s) {
  382. for (var k in s) {
  383. if (!b || !t.hasOwnProperty(k)) {
  384. t[k] = s[k];
  385. }
  386. }
  387. }
  388. return t;
  389. },
  390. /**
  391. * 将给定的多个对象的属性复制到目标对象target上
  392. * @method extend2
  393. * @remind 该方法将强制把源对象上的属性复制到target对象上
  394. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  395. * 将会覆盖掉之前的值。
  396. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  397. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  398. * @return { Object } 返回target对象
  399. * @example
  400. * ```javascript
  401. *
  402. * var target = {},
  403. * source1 = { name: 'source', age: 17 },
  404. * source2 = { title: 'dev' };
  405. *
  406. * UE.utils.extend2( target, source1, source2 );
  407. *
  408. * //output: { name: 'source', age: 17, title: 'dev' }
  409. * console.log( target );
  410. *
  411. * ```
  412. */
  413. extend2: function (t) {
  414. var a = arguments;
  415. for (var i = 1; i < a.length; i++) {
  416. var x = a[i];
  417. for (var k in x) {
  418. if (!t.hasOwnProperty(k)) {
  419. t[k] = x[k];
  420. }
  421. }
  422. }
  423. return t;
  424. },
  425. /**
  426. * 模拟继承机制, 使得subClass继承自superClass
  427. * @method inherits
  428. * @param { Object } subClass 子类对象
  429. * @param { Object } superClass 超类对象
  430. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  431. * @return { Object } 继承superClass后的子类对象
  432. * @example
  433. * ```javascript
  434. * function SuperClass(){
  435. * this.name = "小李";
  436. * }
  437. *
  438. * SuperClass.prototype = {
  439. * hello:function(str){
  440. * console.log(this.name + str);
  441. * }
  442. * }
  443. *
  444. * function SubClass(){
  445. * this.name = "小张";
  446. * }
  447. *
  448. * UE.utils.inherits(SubClass,SuperClass);
  449. *
  450. * var sub = new SubClass();
  451. * //output: '小张早上好!
  452. * sub.hello("早上好!");
  453. * ```
  454. */
  455. inherits: function (subClass, superClass) {
  456. var oldP = subClass.prototype,
  457. newP = utils.makeInstance(superClass.prototype);
  458. utils.extend(newP, oldP, true);
  459. subClass.prototype = newP;
  460. return (newP.constructor = subClass);
  461. },
  462. /**
  463. * 用指定的context对象作为函数fn的上下文
  464. * @method bind
  465. * @param { Function } fn 需要绑定上下文的函数对象
  466. * @param { Object } content 函数fn新的上下文对象
  467. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  468. * @example
  469. * ```javascript
  470. *
  471. * var name = 'window',
  472. * newTest = null;
  473. *
  474. * function test () {
  475. * console.log( this.name );
  476. * }
  477. *
  478. * newTest = UE.utils.bind( test, { name: 'object' } );
  479. *
  480. * //output: object
  481. * newTest();
  482. *
  483. * //output: window
  484. * test();
  485. *
  486. * ```
  487. */
  488. bind: function (fn, context) {
  489. return function () {
  490. return fn.apply(context, arguments);
  491. };
  492. },
  493. /**
  494. * 创建延迟指定时间后执行的函数fn
  495. * @method defer
  496. * @param { Function } fn 需要延迟执行的函数对象
  497. * @param { int } delay 延迟的时间, 单位是毫秒
  498. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  499. * 而不能保证刚好到达延迟时间时执行。
  500. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  501. * @example
  502. * ```javascript
  503. * var start = 0;
  504. *
  505. * function test(){
  506. * console.log( new Date() - start );
  507. * }
  508. *
  509. * var testDefer = UE.utils.defer( test, 1000 );
  510. * //
  511. * start = new Date();
  512. * //output: (大约在1000毫秒之后输出) 1000
  513. * testDefer();
  514. * ```
  515. */
  516. /**
  517. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  518. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  519. * @method defer
  520. * @param { Function } fn 需要延迟执行的函数对象
  521. * @param { int } delay 延迟的时间, 单位是毫秒
  522. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  523. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  524. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  525. * 而不能保证刚好到达延迟时间时执行。
  526. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  527. * @example
  528. * ```javascript
  529. *
  530. * function test(){
  531. * console.log(1);
  532. * }
  533. *
  534. * var testDefer = UE.utils.defer( test, 1000, true );
  535. *
  536. * //output: (两次调用仅有一次输出) 1
  537. * testDefer();
  538. * testDefer();
  539. * ```
  540. */
  541. defer: function (fn, delay, exclusion) {
  542. var timerID;
  543. return function () {
  544. if (exclusion) {
  545. clearTimeout(timerID);
  546. }
  547. timerID = setTimeout(fn, delay);
  548. };
  549. },
  550. /**
  551. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  552. * @method indexOf
  553. * @remind 该方法的匹配过程使用的是恒等“===”
  554. * @param { Array } array 需要查找的数组对象
  555. * @param { * } item 需要在目标数组中查找的值
  556. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  557. * @example
  558. * ```javascript
  559. * var item = 1,
  560. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  561. *
  562. * //output: 4
  563. * console.log( UE.utils.indexOf( arr, item ) );
  564. * ```
  565. */
  566. /**
  567. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  568. * @method indexOf
  569. * @remind 该方法的匹配过程使用的是恒等“===”
  570. * @param { Array } array 需要查找的数组对象
  571. * @param { * } item 需要在目标数组中查找的值
  572. * @param { int } start 搜索的起始位置
  573. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  574. * @example
  575. * ```javascript
  576. * var item = 1,
  577. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  578. *
  579. * //output: 9
  580. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  581. * ```
  582. */
  583. indexOf: function (array, item, start) {
  584. var index = -1;
  585. start = this.isNumber(start) ? start : 0;
  586. this.each(array, function (v, i) {
  587. if (i >= start && v === item) {
  588. index = i;
  589. return false;
  590. }
  591. });
  592. return index;
  593. },
  594. /**
  595. * 移除数组array中所有的元素item
  596. * @method removeItem
  597. * @param { Array } array 要移除元素的目标数组
  598. * @param { * } item 将要被移除的元素
  599. * @remind 该方法的匹配过程使用的是恒等“===”
  600. * @example
  601. * ```javascript
  602. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  603. *
  604. * UE.utils.removeItem( arr, 4 );
  605. * //output: [ 5, 7, 1, 3, 6 ]
  606. * console.log( arr );
  607. *
  608. * ```
  609. */
  610. removeItem: function (array, item) {
  611. for (var i = 0, l = array.length; i < l; i++) {
  612. if (array[i] === item) {
  613. array.splice(i, 1);
  614. i--;
  615. }
  616. }
  617. },
  618. /**
  619. * 删除字符串str的首尾空格
  620. * @method trim
  621. * @param { String } str 需要删除首尾空格的字符串
  622. * @return { String } 删除了首尾的空格后的字符串
  623. * @example
  624. * ```javascript
  625. *
  626. * var str = " UEdtior ";
  627. *
  628. * //output: 9
  629. * console.log( str.length );
  630. *
  631. * //output: 7
  632. * console.log( UE.utils.trim( " UEdtior " ).length );
  633. *
  634. * //output: 9
  635. * console.log( str.length );
  636. *
  637. * ```
  638. */
  639. trim: function (str) {
  640. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  641. },
  642. /**
  643. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  644. * @method listToMap
  645. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  646. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  647. * @return { Object } 转化之后的hash对象
  648. * @example
  649. * ```javascript
  650. *
  651. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  652. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  653. *
  654. * ```
  655. */
  656. /**
  657. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  658. * @method listToMap
  659. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  660. * @param { Array } arr 字符串数组
  661. * @return { Object } 转化之后的hash对象
  662. * @example
  663. * ```javascript
  664. *
  665. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  666. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  667. *
  668. * ```
  669. */
  670. listToMap: function (list) {
  671. if (!list) return {};
  672. list = utils.isArray(list) ? list : list.split(',');
  673. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  674. obj[ci.toUpperCase()] = obj[ci] = 1;
  675. }
  676. return obj;
  677. },
  678. /**
  679. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  680. * @method unhtml
  681. * @param { String } str 需要转义的字符串
  682. * @return { String } 转义后的字符串
  683. * @example
  684. * ```javascript
  685. * var html = '<body>&</body>';
  686. *
  687. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  688. * console.log( UE.utils.unhtml( html ) );
  689. *
  690. * ```
  691. */
  692. unhtml: function (str, reg) {
  693. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  694. if (b) {
  695. return a;
  696. } else {
  697. return {
  698. '<': '&lt;',
  699. '&': '&amp;',
  700. '"': '&quot;',
  701. '>': '&gt;',
  702. '\'': '&#39;',
  703. }[a]
  704. }
  705. }) : '';
  706. },
  707. /**
  708. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  709. * @param { String } str 需要转义的字符串
  710. * @param { RegExp } reg 自定义的正则
  711. * @return { String } 转义后的字符串
  712. */
  713. unhtmlForUrl: function (str, reg) {
  714. return str ? str.replace(reg || /[<">']/g, function (a) {
  715. return {
  716. '<': '&lt;',
  717. '&': '&amp;',
  718. '"': '&quot;',
  719. '>': '&gt;',
  720. '\'': '&#39;',
  721. }[a]
  722. }) : '';
  723. },
  724. /**
  725. * 将str中的转义字符还原成html字符
  726. * @see UE.utils.unhtml(String);
  727. * @method html
  728. * @param { String } str 需要逆转义的字符串
  729. * @return { String } 逆转义后的字符串
  730. * @example
  731. * ```javascript
  732. *
  733. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  734. *
  735. * //output: <body>&</body>
  736. * console.log( UE.utils.html( str ) );
  737. *
  738. * ```
  739. */
  740. html: function (str) {
  741. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  742. return {
  743. '&lt;': '<',
  744. '&amp;': '&',
  745. '&quot;': '"',
  746. '&gt;': '>',
  747. '&#39;': '\'',
  748. '&nbsp;': ' '
  749. }[m]
  750. }) : '';
  751. },
  752. /**
  753. * 将css样式转换为驼峰的形式
  754. * @method cssStyleToDomStyle
  755. * @param { String } cssName 需要转换的css样式名
  756. * @return { String } 转换成驼峰形式后的css样式名
  757. * @example
  758. * ```javascript
  759. *
  760. * var str = 'border-top';
  761. *
  762. * //output: borderTop
  763. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  764. *
  765. * ```
  766. */
  767. cssStyleToDomStyle: function () {
  768. var test = document.createElement('div').style,
  769. cache = {
  770. 'float': test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  771. };
  772. return function (cssName) {
  773. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  774. return match.charAt(1).toUpperCase();
  775. }));
  776. };
  777. }(),
  778. /**
  779. * 动态加载文件到doc中
  780. * @method loadFile
  781. * @param { DomDocument } document 需要加载资源文件的文档对象
  782. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  783. * @example
  784. * ```javascript
  785. *
  786. * UE.utils.loadFile( document, {
  787. * src:"test.js",
  788. * tag:"script",
  789. * type:"text/javascript",
  790. * defer:"defer"
  791. * } );
  792. *
  793. * ```
  794. */
  795. /**
  796. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  797. * @method loadFile
  798. * @param { DomDocument } document 需要加载资源文件的文档对象
  799. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  800. * @param { Function } fn 资源文件加载成功之后执行的回调
  801. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  802. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  803. * @example
  804. * ```javascript
  805. *
  806. * UE.utils.loadFile( document, {
  807. * src:"test.js",
  808. * tag:"script",
  809. * type:"text/javascript",
  810. * defer:"defer"
  811. * }, function () {
  812. * console.log('加载成功');
  813. * } );
  814. *
  815. * ```
  816. */
  817. loadFile: function () {
  818. var tmpList = [];
  819. function getItem(doc, obj) {
  820. try {
  821. for (var i = 0, ci; ci = tmpList[i++];) {
  822. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  823. return ci;
  824. }
  825. }
  826. } catch (e) {
  827. return null;
  828. }
  829. }
  830. return function (doc, obj, fn) {
  831. var item = getItem(doc, obj);
  832. if (item) {
  833. if (item.ready) {
  834. fn && fn();
  835. } else {
  836. item.funs.push(fn)
  837. }
  838. return;
  839. }
  840. tmpList.push({
  841. doc: doc,
  842. url: obj.src || obj.href,
  843. funs: [fn]
  844. });
  845. if (!doc.body) {
  846. var html = [];
  847. for (var p in obj) {
  848. if (p == 'tag') continue;
  849. html.push(p + '="' + obj[p] + '"')
  850. }
  851. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  852. return;
  853. }
  854. if (obj.id && doc.getElementById(obj.id)) {
  855. return;
  856. }
  857. var element = doc.createElement(obj.tag);
  858. delete obj.tag;
  859. for (var p in obj) {
  860. element.setAttribute(p, obj[p]);
  861. }
  862. element.onload = element.onreadystatechange = function () {
  863. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  864. item = getItem(doc, obj);
  865. if (item.funs.length > 0) {
  866. item.ready = 1;
  867. for (var fi; fi = item.funs.pop();) {
  868. fi();
  869. }
  870. }
  871. element.onload = element.onreadystatechange = null;
  872. }
  873. };
  874. element.onerror = function () {
  875. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  876. };
  877. doc.getElementsByTagName("head")[0].appendChild(element);
  878. }
  879. }(),
  880. /**
  881. * 判断obj对象是否为空
  882. * @method isEmptyObject
  883. * @param { * } obj 需要判断的对象
  884. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  885. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  886. * @return { Boolean } 对象是否为空
  887. * @example
  888. * ```javascript
  889. *
  890. * //output: true
  891. * console.log( UE.utils.isEmptyObject( {} ) );
  892. *
  893. * //output: true
  894. * console.log( UE.utils.isEmptyObject( [] ) );
  895. *
  896. * //output: true
  897. * console.log( UE.utils.isEmptyObject( "" ) );
  898. *
  899. * //output: false
  900. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  901. *
  902. * //output: false
  903. * console.log( UE.utils.isEmptyObject( [1] ) );
  904. *
  905. * //output: false
  906. * console.log( UE.utils.isEmptyObject( "1" ) );
  907. *
  908. * ```
  909. */
  910. isEmptyObject: function (obj) {
  911. if (obj == null) return true;
  912. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  913. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  914. return true;
  915. },
  916. /**
  917. * 把rgb格式的颜色值转换成16进制格式
  918. * @method fixColor
  919. * @param { String } rgb格式的颜色值
  920. * @param { String }
  921. * @example
  922. * rgb(255,255,255) => "#ffffff"
  923. */
  924. fixColor: function (name, value) {
  925. if (/color/i.test(name) && /rgba?/.test(value)) {
  926. var array = value.split(",");
  927. if (array.length > 3)
  928. return "";
  929. value = "#";
  930. for (var i = 0, color; color = array[i++];) {
  931. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  932. value += color.length == 1 ? "0" + color : color;
  933. }
  934. value = value.toUpperCase();
  935. }
  936. return value;
  937. },
  938. /**
  939. * 只针对border,padding,margin做了处理,因为性能问题
  940. * @public
  941. * @function
  942. * @param {String} val style字符串
  943. */
  944. optCss: function (val) {
  945. var padding, margin, border;
  946. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  947. if (val.split(' ').length == 1) {
  948. switch (key) {
  949. case 'padding':
  950. !padding && (padding = {});
  951. padding[name] = val;
  952. return '';
  953. case 'margin':
  954. !margin && (margin = {});
  955. margin[name] = val;
  956. return '';
  957. case 'border':
  958. return val == 'initial' ? '' : str;
  959. }
  960. }
  961. return str;
  962. });
  963. function opt(obj, name) {
  964. if (!obj) {
  965. return '';
  966. }
  967. var t = obj.top, b = obj.bottom, l = obj.left, r = obj.right, val = '';
  968. if (!t || !l || !b || !r) {
  969. for (var p in obj) {
  970. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  971. }
  972. } else {
  973. val += ';' + name + ':' +
  974. (t == b && b == l && l == r ? t :
  975. t == b && l == r ? (t + ' ' + l) :
  976. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  977. }
  978. return val;
  979. }
  980. val += opt(padding, 'padding') + opt(margin, 'margin');
  981. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  982. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  983. return b ? b + ";;" : ';'
  984. });
  985. },
  986. /**
  987. * 克隆对象
  988. * @method clone
  989. * @param { Object } source 源对象
  990. * @return { Object } source的一个副本
  991. */
  992. /**
  993. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  994. * @method clone
  995. * @param { Object } source 源对象
  996. * @param { Object } target 目标对象
  997. * @return { Object } 附加了source对象所有属性的target对象
  998. */
  999. clone: function (source, target) {
  1000. var tmp;
  1001. target = target || {};
  1002. for (var i in source) {
  1003. if (source.hasOwnProperty(i)) {
  1004. tmp = source[i];
  1005. if (typeof tmp == 'object') {
  1006. target[i] = utils.isArray(tmp) ? [] : {};
  1007. utils.clone(source[i], target[i])
  1008. } else {
  1009. target[i] = tmp;
  1010. }
  1011. }
  1012. }
  1013. return target;
  1014. },
  1015. /**
  1016. * 把cm/pt为单位的值转换为px为单位的值
  1017. * @method transUnitToPx
  1018. * @param { String } 待转换的带单位的字符串
  1019. * @return { String } 转换为px为计量单位的值的字符串
  1020. * @example
  1021. * ```javascript
  1022. *
  1023. * //output: 500px
  1024. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1025. *
  1026. * //output: 27px
  1027. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1028. *
  1029. * ```
  1030. */
  1031. transUnitToPx: function (val) {
  1032. if (!/(pt|cm)/.test(val)) {
  1033. return val
  1034. }
  1035. var unit;
  1036. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1037. val = v;
  1038. unit = u;
  1039. });
  1040. switch (unit) {
  1041. case 'cm':
  1042. val = parseFloat(val) * 25;
  1043. break;
  1044. case 'pt':
  1045. val = Math.round(parseFloat(val) * 96 / 72);
  1046. }
  1047. return val + (val ? 'px' : '');
  1048. },
  1049. /**
  1050. * 在dom树ready之后执行给定的回调函数
  1051. * @method domReady
  1052. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1053. * @param { Function } fn dom树ready之后的回调函数
  1054. * @example
  1055. * ```javascript
  1056. *
  1057. * UE.utils.domReady( function () {
  1058. *
  1059. * console.log('123');
  1060. *
  1061. * } );
  1062. *
  1063. * ```
  1064. */
  1065. domReady: function () {
  1066. var fnArr = [];
  1067. function doReady(doc) {
  1068. //确保onready只执行一次
  1069. doc.isReady = true;
  1070. for (var ci; ci = fnArr.pop(); ci()) {
  1071. }
  1072. }
  1073. return function (onready, win) {
  1074. win = win || window;
  1075. var doc = win.document;
  1076. onready && fnArr.push(onready);
  1077. if (doc.readyState === "complete") {
  1078. doReady(doc);
  1079. } else {
  1080. doc.isReady && doReady(doc);
  1081. if (browser.ie && browser.version != 11) {
  1082. (function () {
  1083. if (doc.isReady) return;
  1084. try {
  1085. doc.documentElement.doScroll("left");
  1086. } catch (error) {
  1087. setTimeout(arguments.callee, 0);
  1088. return;
  1089. }
  1090. doReady(doc);
  1091. })();
  1092. win.attachEvent('onload', function () {
  1093. doReady(doc)
  1094. });
  1095. } else {
  1096. doc.addEventListener("DOMContentLoaded", function () {
  1097. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1098. doReady(doc);
  1099. }, false);
  1100. win.addEventListener('load', function () {
  1101. doReady(doc)
  1102. }, false);
  1103. }
  1104. }
  1105. }
  1106. }(),
  1107. /**
  1108. * 动态添加css样式
  1109. * @method cssRule
  1110. * @param { String } 节点名称
  1111. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1112. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1113. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1114. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1115. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1116. */
  1117. cssRule: browser.ie && browser.version != 11 ? function (key, style, doc) {
  1118. var indexList, index;
  1119. if (style === undefined || style && style.nodeType && style.nodeType == 9) {
  1120. //获取样式
  1121. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1122. indexList = doc.indexList || (doc.indexList = {});
  1123. index = indexList[key];
  1124. if (index !== undefined) {
  1125. return doc.styleSheets[index].cssText
  1126. }
  1127. return undefined;
  1128. }
  1129. doc = doc || document;
  1130. indexList = doc.indexList || (doc.indexList = {});
  1131. index = indexList[key];
  1132. //清除样式
  1133. if (style === '') {
  1134. if (index !== undefined) {
  1135. doc.styleSheets[index].cssText = '';
  1136. delete indexList[key];
  1137. return true
  1138. }
  1139. return false;
  1140. }
  1141. //添加样式
  1142. if (index !== undefined) {
  1143. sheetStyle = doc.styleSheets[index];
  1144. } else {
  1145. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1146. indexList[key] = index;
  1147. }
  1148. sheetStyle.cssText = style;
  1149. } : function (key, style, doc) {
  1150. var head, node;
  1151. if (style === undefined || style && style.nodeType && style.nodeType == 9) {
  1152. //获取样式
  1153. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1154. node = doc.getElementById(key);
  1155. return node ? node.innerHTML : undefined;
  1156. }
  1157. doc = doc || document;
  1158. node = doc.getElementById(key);
  1159. //清除样式
  1160. if (style === '') {
  1161. if (node) {
  1162. node.parentNode.removeChild(node);
  1163. return true
  1164. }
  1165. return false;
  1166. }
  1167. //添加样式
  1168. if (node) {
  1169. node.innerHTML = style;
  1170. } else {
  1171. node = doc.createElement('style');
  1172. node.id = key;
  1173. node.innerHTML = style;
  1174. doc.getElementsByTagName('head')[0].appendChild(node);
  1175. }
  1176. },
  1177. sort: function (array, compareFn) {
  1178. compareFn = compareFn || function (item1, item2) {
  1179. return item1.localeCompare(item2);
  1180. };
  1181. for (var i = 0, len = array.length; i < len; i++) {
  1182. for (var j = i, length = array.length; j < length; j++) {
  1183. if (compareFn(array[i], array[j]) > 0) {
  1184. var t = array[i];
  1185. array[i] = array[j];
  1186. array[j] = t;
  1187. }
  1188. }
  1189. }
  1190. return array;
  1191. },
  1192. serializeParam: function (json) {
  1193. var strArr = [];
  1194. for (var i in json) {
  1195. //忽略默认的几个参数
  1196. if (i == "method" || i == "timeout" || i == "async") continue;
  1197. //传递过来的对象和函数不在提交之列
  1198. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1199. strArr.push(encodeURIComponent(i) + "=" + encodeURIComponent(json[i]));
  1200. } else if (utils.isArray(json[i])) {
  1201. //支持传数组内容
  1202. for (var j = 0; j < json[i].length; j++) {
  1203. strArr.push(encodeURIComponent(i) + "[]=" + encodeURIComponent(json[i][j]));
  1204. }
  1205. }
  1206. }
  1207. return strArr.join("&");
  1208. },
  1209. formatUrl: function (url) {
  1210. var u = url.replace(/&&/g, '&');
  1211. u = u.replace(/\?&/g, '?');
  1212. u = u.replace(/&$/g, '');
  1213. u = u.replace(/&#/g, '#');
  1214. u = u.replace(/&+/g, '&');
  1215. return u;
  1216. },
  1217. isCrossDomainUrl: function (url) {
  1218. var a = document.createElement('a');
  1219. a.href = url;
  1220. if (browser.ie) {
  1221. a.href = a.href;
  1222. }
  1223. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1224. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1225. },
  1226. clearEmptyAttrs: function (obj) {
  1227. for (var p in obj) {
  1228. if (obj[p] === '') {
  1229. delete obj[p]
  1230. }
  1231. }
  1232. return obj;
  1233. },
  1234. str2json: function (s) {
  1235. if (!utils.isString(s)) return null;
  1236. if (window.JSON) {
  1237. return JSON.parse(s);
  1238. } else {
  1239. return (new Function("return " + utils.trim(s || '')))();
  1240. }
  1241. },
  1242. json2str: (function () {
  1243. if (window.JSON) {
  1244. return JSON.stringify;
  1245. } else {
  1246. var escapeMap = {
  1247. "\b": '\\b',
  1248. "\t": '\\t',
  1249. "\n": '\\n',
  1250. "\f": '\\f',
  1251. "\r": '\\r',
  1252. '"': '\\"',
  1253. "\\": '\\\\'
  1254. };
  1255. function encodeString(source) {
  1256. if (/["\\\x00-\x1f]/.test(source)) {
  1257. source = source.replace(
  1258. /["\\\x00-\x1f]/g,
  1259. function (match) {
  1260. var c = escapeMap[match];
  1261. if (c) {
  1262. return c;
  1263. }
  1264. c = match.charCodeAt();
  1265. return "\\u00"
  1266. + Math.floor(c / 16).toString(16)
  1267. + (c % 16).toString(16);
  1268. });
  1269. }
  1270. return '"' + source + '"';
  1271. }
  1272. function encodeArray(source) {
  1273. var result = ["["],
  1274. l = source.length,
  1275. preComma, i, item;
  1276. for (i = 0; i < l; i++) {
  1277. item = source[i];
  1278. switch (typeof item) {
  1279. case "undefined":
  1280. case "function":
  1281. case "unknown":
  1282. break;
  1283. default:
  1284. if (preComma) {
  1285. result.push(',');
  1286. }
  1287. result.push(utils.json2str(item));
  1288. preComma = 1;
  1289. }
  1290. }
  1291. result.push("]");
  1292. return result.join("");
  1293. }
  1294. function pad(source) {
  1295. return source < 10 ? '0' + source : source;
  1296. }
  1297. function encodeDate(source) {
  1298. return '"' + source.getFullYear() + "-"
  1299. + pad(source.getMonth() + 1) + "-"
  1300. + pad(source.getDate()) + "T"
  1301. + pad(source.getHours()) + ":"
  1302. + pad(source.getMinutes()) + ":"
  1303. + pad(source.getSeconds()) + '"';
  1304. }
  1305. return function (value) {
  1306. switch (typeof value) {
  1307. case 'undefined':
  1308. return 'undefined';
  1309. case 'number':
  1310. return isFinite(value) ? String(value) : "null";
  1311. case 'string':
  1312. return encodeString(value);
  1313. case 'boolean':
  1314. return String(value);
  1315. default:
  1316. if (value === null) {
  1317. return 'null';
  1318. } else if (utils.isArray(value)) {
  1319. return encodeArray(value);
  1320. } else if (utils.isDate(value)) {
  1321. return encodeDate(value);
  1322. } else {
  1323. var result = ['{'],
  1324. encode = utils.json2str,
  1325. preComma,
  1326. item;
  1327. for (var key in value) {
  1328. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1329. item = value[key];
  1330. switch (typeof item) {
  1331. case 'undefined':
  1332. case 'unknown':
  1333. case 'function':
  1334. break;
  1335. default:
  1336. if (preComma) {
  1337. result.push(',');
  1338. }
  1339. preComma = 1;
  1340. result.push(encode(key) + ':' + encode(item));
  1341. }
  1342. }
  1343. }
  1344. result.push('}');
  1345. return result.join('');
  1346. }
  1347. }
  1348. };
  1349. }
  1350. })()
  1351. };
  1352. /**
  1353. * 判断给定的对象是否是字符串
  1354. * @method isString
  1355. * @param { * } object 需要判断的对象
  1356. * @return { Boolean } 给定的对象是否是字符串
  1357. */
  1358. /**
  1359. * 判断给定的对象是否是数组
  1360. * @method isArray
  1361. * @param { * } object 需要判断的对象
  1362. * @return { Boolean } 给定的对象是否是数组
  1363. */
  1364. /**
  1365. * 判断给定的对象是否是一个Function
  1366. * @method isFunction
  1367. * @param { * } object 需要判断的对象
  1368. * @return { Boolean } 给定的对象是否是Function
  1369. */
  1370. /**
  1371. * 判断给定的对象是否是Number
  1372. * @method isNumber
  1373. * @param { * } object 需要判断的对象
  1374. * @return { Boolean } 给定的对象是否是Number
  1375. */
  1376. /**
  1377. * 判断给定的对象是否是一个正则表达式
  1378. * @method isRegExp
  1379. * @param { * } object 需要判断的对象
  1380. * @return { Boolean } 给定的对象是否是正则表达式
  1381. */
  1382. /**
  1383. * 判断给定的对象是否是一个普通对象
  1384. * @method isObject
  1385. * @param { * } object 需要判断的对象
  1386. * @return { Boolean } 给定的对象是否是普通对象
  1387. */
  1388. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1389. UE.utils['is' + v] = function (obj) {
  1390. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1391. }
  1392. });
  1393. // core/EventBase.js
  1394. /**
  1395. * UE采用的事件基类
  1396. * @file
  1397. * @module UE
  1398. * @class EventBase
  1399. * @since 1.2.6.1
  1400. */
  1401. /**
  1402. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1403. * @unfile
  1404. * @module UE
  1405. */
  1406. /**
  1407. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1408. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1409. * @unfile
  1410. * @module UE
  1411. * @class EventBase
  1412. */
  1413. /**
  1414. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1415. * @constructor
  1416. * @example
  1417. * ```javascript
  1418. * UE.EventBase.call(editor);
  1419. * ```
  1420. */
  1421. var EventBase = UE.EventBase = function () {
  1422. };
  1423. EventBase.prototype = {
  1424. /**
  1425. * 注册事件监听器
  1426. * @method addListener
  1427. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1428. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1429. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1430. * @example
  1431. * ```javascript
  1432. * editor.addListener('selectionchange',function(){
  1433. * console.log("选区已经变化!");
  1434. * })
  1435. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1436. * if(type == 'beforegetcontent'){
  1437. * //do something
  1438. * }else{
  1439. * //do something
  1440. * }
  1441. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1442. * })
  1443. * ```
  1444. * @see UE.EventBase:fireEvent(String)
  1445. */
  1446. addListener: function (types, listener) {
  1447. types = utils.trim(types).split(/\s+/);
  1448. for (var i = 0, ti; ti = types[i++];) {
  1449. getListener(this, ti, true).push(listener);
  1450. }
  1451. },
  1452. on: function (types, listener) {
  1453. return this.addListener(types, listener);
  1454. },
  1455. off: function (types, listener) {
  1456. return this.removeListener(types, listener)
  1457. },
  1458. trigger: function () {
  1459. return this.fireEvent.apply(this, arguments);
  1460. },
  1461. /**
  1462. * 移除事件监听器
  1463. * @method removeListener
  1464. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1465. * @param { Function } fn 移除监听事件的函数引用
  1466. * @example
  1467. * ```javascript
  1468. * //changeCallback为方法体
  1469. * editor.removeListener("selectionchange",changeCallback);
  1470. * ```
  1471. */
  1472. removeListener: function (types, listener) {
  1473. types = utils.trim(types).split(/\s+/);
  1474. for (var i = 0, ti; ti = types[i++];) {
  1475. utils.removeItem(getListener(this, ti) || [], listener);
  1476. }
  1477. },
  1478. /**
  1479. * 触发事件
  1480. * @method fireEvent
  1481. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1482. * @remind 该方法会触发addListener
  1483. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1484. * @example
  1485. * ```javascript
  1486. * editor.fireEvent("selectionchange");
  1487. * ```
  1488. */
  1489. /**
  1490. * 触发事件
  1491. * @method fireEvent
  1492. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1493. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1494. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1495. * @example
  1496. * ```javascript
  1497. *
  1498. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1499. *
  1500. * console.log( arg1 + " " + arg2 );
  1501. *
  1502. * } );
  1503. *
  1504. * //触发selectionchange事件, 会执行上面的事件监听器
  1505. * //output: Hello World
  1506. * editor.fireEvent("selectionchange", "Hello", "World");
  1507. * ```
  1508. */
  1509. fireEvent: function () {
  1510. var types = arguments[0];
  1511. types = utils.trim(types).split(' ');
  1512. for (var i = 0, ti; ti = types[i++];) {
  1513. var listeners = getListener(this, ti),
  1514. r, t, k;
  1515. if (listeners) {
  1516. k = listeners.length;
  1517. while (k--) {
  1518. if (!listeners[k]) continue;
  1519. t = listeners[k].apply(this, arguments);
  1520. if (t === true) {
  1521. return t;
  1522. }
  1523. if (t !== undefined) {
  1524. r = t;
  1525. }
  1526. }
  1527. }
  1528. if (t = this['on' + ti.toLowerCase()]) {
  1529. r = t.apply(this, arguments);
  1530. }
  1531. }
  1532. return r;
  1533. }
  1534. };
  1535. /**
  1536. * 获得对象所拥有监听类型的所有监听器
  1537. * @unfile
  1538. * @module UE
  1539. * @since 1.2.6.1
  1540. * @method getListener
  1541. * @public
  1542. * @param { Object } obj 查询监听器的对象
  1543. * @param { String } type 事件类型
  1544. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1545. * @return { Array } 监听器数组
  1546. */
  1547. function getListener(obj, type, force) {
  1548. var allListeners;
  1549. type = type.toLowerCase();
  1550. return ((allListeners = (obj.__allListeners || force && (obj.__allListeners = {})))
  1551. && (allListeners[type] || force && (allListeners[type] = [])));
  1552. }
  1553. // core/dtd.js
  1554. ///import editor.js
  1555. ///import core/dom/dom.js
  1556. ///import core/utils.js
  1557. /**
  1558. * dtd html语义化的体现类
  1559. * @constructor
  1560. * @namespace dtd
  1561. */
  1562. var dtd = dom.dtd = (function () {
  1563. function _(s) {
  1564. for (var k in s) {
  1565. s[k.toUpperCase()] = s[k];
  1566. }
  1567. return s;
  1568. }
  1569. var X = utils.extend2;
  1570. var A = _({isindex: 1, fieldset: 1}),
  1571. B = _({input: 1, button: 1, select: 1, textarea: 1, label: 1}),
  1572. C = X(_({a: 1}), B),
  1573. D = X({iframe: 1}, C),
  1574. E = _({
  1575. hr: 1,
  1576. ul: 1,
  1577. menu: 1,
  1578. div: 1,
  1579. blockquote: 1,
  1580. noscript: 1,
  1581. table: 1,
  1582. center: 1,
  1583. address: 1,
  1584. dir: 1,
  1585. pre: 1,
  1586. h5: 1,
  1587. dl: 1,
  1588. h4: 1,
  1589. noframes: 1,
  1590. h6: 1,
  1591. ol: 1,
  1592. h1: 1,
  1593. h3: 1,
  1594. h2: 1
  1595. }),
  1596. F = _({ins: 1, del: 1, script: 1, style: 1}),
  1597. G = X(_({
  1598. b: 1,
  1599. acronym: 1,
  1600. bdo: 1,
  1601. 'var': 1,
  1602. '#': 1,
  1603. abbr: 1,
  1604. code: 1,
  1605. br: 1,
  1606. i: 1,
  1607. cite: 1,
  1608. kbd: 1,
  1609. u: 1,
  1610. strike: 1,
  1611. s: 1,
  1612. tt: 1,
  1613. strong: 1,
  1614. q: 1,
  1615. samp: 1,
  1616. em: 1,
  1617. dfn: 1,
  1618. span: 1
  1619. }), F),
  1620. H = X(_({
  1621. sub: 1,
  1622. img: 1,
  1623. embed: 1,
  1624. object: 1,
  1625. sup: 1,
  1626. basefont: 1,
  1627. map: 1,
  1628. applet: 1,
  1629. font: 1,
  1630. big: 1,
  1631. small: 1
  1632. }), G),
  1633. I = X(_({p: 1}), H),
  1634. J = X(_({iframe: 1}), H, B),
  1635. K = _({
  1636. img: 1,
  1637. embed: 1,
  1638. noscript: 1,
  1639. br: 1,
  1640. kbd: 1,
  1641. center: 1,
  1642. button: 1,
  1643. basefont: 1,
  1644. h5: 1,
  1645. h4: 1,
  1646. samp: 1,
  1647. h6: 1,
  1648. ol: 1,
  1649. h1: 1,
  1650. h3: 1,
  1651. h2: 1,
  1652. form: 1,
  1653. font: 1,
  1654. '#': 1,
  1655. select: 1,
  1656. menu: 1,
  1657. ins: 1,
  1658. abbr: 1,
  1659. label: 1,
  1660. code: 1,
  1661. table: 1,
  1662. script: 1,
  1663. cite: 1,
  1664. input: 1,
  1665. iframe: 1,
  1666. strong: 1,
  1667. textarea: 1,
  1668. noframes: 1,
  1669. big: 1,
  1670. small: 1,
  1671. span: 1,
  1672. hr: 1,
  1673. sub: 1,
  1674. bdo: 1,
  1675. 'var': 1,
  1676. div: 1,
  1677. object: 1,
  1678. sup: 1,
  1679. strike: 1,
  1680. dir: 1,
  1681. map: 1,
  1682. dl: 1,
  1683. applet: 1,
  1684. del: 1,
  1685. isindex: 1,
  1686. fieldset: 1,
  1687. ul: 1,
  1688. b: 1,
  1689. acronym: 1,
  1690. a: 1,
  1691. blockquote: 1,
  1692. i: 1,
  1693. u: 1,
  1694. s: 1,
  1695. tt: 1,
  1696. address: 1,
  1697. q: 1,
  1698. pre: 1,
  1699. p: 1,
  1700. em: 1,
  1701. dfn: 1
  1702. }),
  1703. L = X(_({a: 0}), J),//a不能被切开,所以把他
  1704. M = _({tr: 1}),
  1705. N = _({'#': 1}),
  1706. O = X(_({param: 1}), K),
  1707. P = X(_({form: 1}), A, D, E, I),
  1708. Q = _({li: 1, ol: 1, ul: 1}),
  1709. R = _({style: 1, script: 1}),
  1710. S = _({base: 1, link: 1, meta: 1, title: 1}),
  1711. T = X(S, R),
  1712. U = _({head: 1, body: 1}),
  1713. V = _({html: 1});
  1714. var block = _({
  1715. address: 1,
  1716. blockquote: 1,
  1717. center: 1,
  1718. dir: 1,
  1719. div: 1,
  1720. dl: 1,
  1721. fieldset: 1,
  1722. form: 1,
  1723. h1: 1,
  1724. h2: 1,
  1725. h3: 1,
  1726. h4: 1,
  1727. h5: 1,
  1728. h6: 1,
  1729. hr: 1,
  1730. isindex: 1,
  1731. menu: 1,
  1732. noframes: 1,
  1733. ol: 1,
  1734. p: 1,
  1735. pre: 1,
  1736. table: 1,
  1737. ul: 1
  1738. }),
  1739. empty = _({
  1740. area: 1,
  1741. base: 1,
  1742. basefont: 1,
  1743. br: 1,
  1744. col: 1,
  1745. command: 1,
  1746. dialog: 1,
  1747. embed: 1,
  1748. hr: 1,
  1749. img: 1,
  1750. input: 1,
  1751. isindex: 1,
  1752. keygen: 1,
  1753. link: 1,
  1754. meta: 1,
  1755. param: 1,
  1756. source: 1,
  1757. track: 1,
  1758. wbr: 1
  1759. });
  1760. return _({
  1761. // $ 表示自定的属性
  1762. // body外的元素列表.
  1763. $nonBodyContent: X(V, U, S),
  1764. //块结构元素列表
  1765. $block: block,
  1766. //内联元素列表
  1767. $inline: L,
  1768. $inlineWithA: X(_({a: 1}), L),
  1769. $body: X(_({script: 1, style: 1}), block),
  1770. $cdata: _({script: 1, style: 1}),
  1771. //自闭和元素
  1772. $empty: empty,
  1773. //不是自闭合,但不能让range选中里边
  1774. $nonChild: _({iframe: 1, textarea: 1}),
  1775. //列表元素列表
  1776. $listItem: _({dd: 1, dt: 1, li: 1}),
  1777. //列表根元素列表
  1778. $list: _({ul: 1, ol: 1, dl: 1}),
  1779. //不能认为是空的元素
  1780. $isNotEmpty: _({
  1781. table: 1,
  1782. ul: 1,
  1783. ol: 1,
  1784. dl: 1,
  1785. iframe: 1,
  1786. area: 1,
  1787. base: 1,
  1788. col: 1,
  1789. hr: 1,
  1790. img: 1,
  1791. embed: 1,
  1792. input: 1,
  1793. link: 1,
  1794. meta: 1,
  1795. param: 1,
  1796. h1: 1,
  1797. h2: 1,
  1798. h3: 1,
  1799. h4: 1,
  1800. h5: 1,
  1801. h6: 1
  1802. }),
  1803. //如果没有子节点就可以删除的元素列表,像span,a
  1804. $removeEmpty: _({
  1805. a: 1,
  1806. abbr: 1,
  1807. acronym: 1,
  1808. address: 1,
  1809. b: 1,
  1810. bdo: 1,
  1811. big: 1,
  1812. cite: 1,
  1813. code: 1,
  1814. del: 1,
  1815. dfn: 1,
  1816. em: 1,
  1817. font: 1,
  1818. i: 1,
  1819. ins: 1,
  1820. label: 1,
  1821. kbd: 1,
  1822. q: 1,
  1823. s: 1,
  1824. samp: 1,
  1825. small: 1,
  1826. span: 1,
  1827. strike: 1,
  1828. strong: 1,
  1829. sub: 1,
  1830. sup: 1,
  1831. tt: 1,
  1832. u: 1,
  1833. 'var': 1
  1834. }),
  1835. $removeEmptyBlock: _({'p': 1, 'div': 1}),
  1836. //在table元素里的元素列表
  1837. $tableContent: _({
  1838. caption: 1,
  1839. col: 1,
  1840. colgroup: 1,
  1841. tbody: 1,
  1842. td: 1,
  1843. tfoot: 1,
  1844. th: 1,
  1845. thead: 1,
  1846. tr: 1,
  1847. table: 1
  1848. }),
  1849. //不转换的标签
  1850. $notTransContent: _({pre: 1, script: 1, style: 1, textarea: 1}),
  1851. html: U,
  1852. head: T,
  1853. style: N,
  1854. script: N,
  1855. body: P,
  1856. base: {},
  1857. link: {},
  1858. meta: {},
  1859. title: N,
  1860. col: {},
  1861. tr: _({td: 1, th: 1}),
  1862. img: {},
  1863. embed: {},
  1864. colgroup: _({thead: 1, col: 1, tbody: 1, tr: 1, tfoot: 1}),
  1865. noscript: P,
  1866. td: P,
  1867. br: {},
  1868. th: P,
  1869. center: P,
  1870. kbd: L,
  1871. button: X(I, E),
  1872. basefont: {},
  1873. h5: L,
  1874. h4: L,
  1875. samp: L,
  1876. h6: L,
  1877. ol: Q,
  1878. h1: L,
  1879. h3: L,
  1880. option: N,
  1881. h2: L,
  1882. form: X(A, D, E, I),
  1883. select: _({optgroup: 1, option: 1}),
  1884. font: L,
  1885. ins: L,
  1886. menu: Q,
  1887. abbr: L,
  1888. label: L,
  1889. table: _({thead: 1, col: 1, tbody: 1, tr: 1, colgroup: 1, caption: 1, tfoot: 1}),
  1890. code: L,
  1891. tfoot: M,
  1892. cite: L,
  1893. li: P,
  1894. input: {},
  1895. iframe: P,
  1896. strong: L,
  1897. textarea: N,
  1898. noframes: P,
  1899. big: L,
  1900. small: L,
  1901. //trace:
  1902. span: _({'#': 1, br: 1, b: 1, strong: 1, u: 1, i: 1, em: 1, sub: 1, sup: 1, strike: 1, span: 1}),
  1903. hr: L,
  1904. dt: L,
  1905. sub: L,
  1906. optgroup: _({option: 1}),
  1907. param: {},
  1908. bdo: L,
  1909. 'var': L,
  1910. div: P,
  1911. object: O,
  1912. sup: L,
  1913. dd: P,
  1914. strike: L,
  1915. area: {},
  1916. dir: Q,
  1917. map: X(_({area: 1, form: 1, p: 1}), A, F, E),
  1918. applet: O,
  1919. dl: _({dt: 1, dd: 1}),
  1920. del: L,
  1921. isindex: {},
  1922. fieldset: X(_({legend: 1}), K),
  1923. thead: M,
  1924. ul: Q,
  1925. acronym: L,
  1926. b: L,
  1927. a: X(_({a: 1}), J),
  1928. blockquote: X(_({td: 1, tr: 1, tbody: 1, li: 1}), P),
  1929. caption: L,
  1930. i: L,
  1931. u: L,
  1932. tbody: M,
  1933. s: L,
  1934. address: X(D, I),
  1935. tt: L,
  1936. legend: L,
  1937. q: L,
  1938. pre: X(G, C),
  1939. p: X(_({'a': 1}), L),
  1940. em: L,
  1941. dfn: L
  1942. });
  1943. })();
  1944. // core/domUtils.js
  1945. /**
  1946. * Dom操作工具包
  1947. * @file
  1948. * @module UE.dom.domUtils
  1949. * @since 1.2.6.1
  1950. */
  1951. /**
  1952. * Dom操作工具包
  1953. * @unfile
  1954. * @module UE.dom.domUtils
  1955. */
  1956. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1957. var tmpNode = startFromChild && node[start],
  1958. parent;
  1959. !tmpNode && (tmpNode = node[ltr]);
  1960. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1961. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1962. return null;
  1963. }
  1964. tmpNode = parent[ltr];
  1965. }
  1966. if (tmpNode && fn && !fn(tmpNode)) {
  1967. return getDomNode(tmpNode, start, ltr, false, fn);
  1968. }
  1969. return tmpNode;
  1970. }
  1971. var attrFix = ie && browser.version < 9 ? {
  1972. tabindex: "tabIndex",
  1973. readonly: "readOnly",
  1974. "for": "htmlFor",
  1975. "class": "className",
  1976. maxlength: "maxLength",
  1977. cellspacing: "cellSpacing",
  1978. cellpadding: "cellPadding",
  1979. rowspan: "rowSpan",
  1980. colspan: "colSpan",
  1981. usemap: "useMap",
  1982. frameborder: "frameBorder"
  1983. } : {
  1984. tabindex: "tabIndex",
  1985. readonly: "readOnly"
  1986. },
  1987. styleBlock = utils.listToMap([
  1988. '-webkit-box', '-moz-box', 'block',
  1989. 'list-item', 'table', 'table-row-group',
  1990. 'table-header-group', 'table-footer-group',
  1991. 'table-row', 'table-column-group', 'table-column',
  1992. 'table-cell', 'table-caption'
  1993. ]);
  1994. var domUtils = dom.domUtils = {
  1995. //节点常量
  1996. NODE_ELEMENT: 1,
  1997. NODE_DOCUMENT: 9,
  1998. NODE_TEXT: 3,
  1999. NODE_COMMENT: 8,
  2000. NODE_DOCUMENT_FRAGMENT: 11,
  2001. //位置关系
  2002. POSITION_IDENTICAL: 0,
  2003. POSITION_DISCONNECTED: 1,
  2004. POSITION_FOLLOWING: 2,
  2005. POSITION_PRECEDING: 4,
  2006. POSITION_IS_CONTAINED: 8,
  2007. POSITION_CONTAINS: 16,
  2008. //ie6使用其他的会有一段空白出现
  2009. fillChar: ie && browser.version == '6' ? '\ufeff' : '\u200B',
  2010. //-------------------------Node部分--------------------------------
  2011. keys: {
  2012. /*Backspace*/ 8: 1, /*Delete*/ 46: 1,
  2013. /*Shift*/ 16: 1, /*Ctrl*/ 17: 1, /*Alt*/ 18: 1,
  2014. 37: 1, 38: 1, 39: 1, 40: 1,
  2015. 13: 1 /*enter*/
  2016. },
  2017. /**
  2018. * 获取节点A相对于节点B的位置关系
  2019. * @method getPosition
  2020. * @param { Node } nodeA 需要查询位置关系的节点A
  2021. * @param { Node } nodeB 需要查询位置关系的节点B
  2022. * @return { Number } 节点A与节点B的关系
  2023. * @example
  2024. * ```javascript
  2025. * //output: 20
  2026. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  2027. *
  2028. * switch ( position ) {
  2029. *
  2030. * //0
  2031. * case UE.dom.domUtils.POSITION_IDENTICAL:
  2032. * console.log('元素相同');
  2033. * break;
  2034. * //1
  2035. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  2036. * console.log('两个节点在不同的文档中');
  2037. * break;
  2038. * //2
  2039. * case UE.dom.domUtils.POSITION_FOLLOWING:
  2040. * console.log('节点A在节点B之后');
  2041. * break;
  2042. * //4
  2043. * case UE.dom.domUtils.POSITION_PRECEDING;
  2044. * console.log('节点A在节点B之前');
  2045. * break;
  2046. * //8
  2047. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  2048. * console.log('节点A被节点B包含');
  2049. * break;
  2050. * case 10:
  2051. * console.log('节点A被节点B包含且节点A在节点B之后');
  2052. * break;
  2053. * //16
  2054. * case UE.dom.domUtils.POSITION_CONTAINS:
  2055. * console.log('节点A包含节点B');
  2056. * break;
  2057. * case 20:
  2058. * console.log('节点A包含节点B且节点A在节点B之前');
  2059. * break;
  2060. *
  2061. * }
  2062. * ```
  2063. */
  2064. getPosition: function (nodeA, nodeB) {
  2065. // 如果两个节点是同一个节点
  2066. if (nodeA === nodeB) {
  2067. // domUtils.POSITION_IDENTICAL
  2068. return 0;
  2069. }
  2070. var node,
  2071. parentsA = [nodeA],
  2072. parentsB = [nodeB];
  2073. node = nodeA;
  2074. while (node = node.parentNode) {
  2075. // 如果nodeB是nodeA的祖先节点
  2076. if (node === nodeB) {
  2077. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  2078. return 10;
  2079. }
  2080. parentsA.push(node);
  2081. }
  2082. node = nodeB;
  2083. while (node = node.parentNode) {
  2084. // 如果nodeA是nodeB的祖先节点
  2085. if (node === nodeA) {
  2086. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  2087. return 20;
  2088. }
  2089. parentsB.push(node);
  2090. }
  2091. parentsA.reverse();
  2092. parentsB.reverse();
  2093. if (parentsA[0] !== parentsB[0]) {
  2094. // domUtils.POSITION_DISCONNECTED
  2095. return 1;
  2096. }
  2097. var i = -1;
  2098. while (i++, parentsA[i] === parentsB[i]) {
  2099. }
  2100. nodeA = parentsA[i];
  2101. nodeB = parentsB[i];
  2102. while (nodeA = nodeA.nextSibling) {
  2103. if (nodeA === nodeB) {
  2104. // domUtils.POSITION_PRECEDING
  2105. return 4
  2106. }
  2107. }
  2108. // domUtils.POSITION_FOLLOWING
  2109. return 2;
  2110. },
  2111. /**
  2112. * 检测节点node在父节点中的索引位置
  2113. * @method getNodeIndex
  2114. * @param { Node } node 需要检测的节点对象
  2115. * @return { Number } 该节点在父节点中的位置
  2116. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  2117. */
  2118. /**
  2119. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  2120. * @method getNodeIndex
  2121. * @param { Node } node 需要检测的节点对象
  2122. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  2123. * @return { Number } 该节点在父节点中的位置
  2124. * @example
  2125. * ```javascript
  2126. *
  2127. * var node = document.createElement("div");
  2128. *
  2129. * node.appendChild( document.createTextNode( "hello" ) );
  2130. * node.appendChild( document.createTextNode( "world" ) );
  2131. * node.appendChild( node = document.createElement( "div" ) );
  2132. *
  2133. * //output: 2
  2134. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  2135. *
  2136. * //output: 1
  2137. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  2138. *
  2139. * ```
  2140. */
  2141. getNodeIndex: function (node, ignoreTextNode) {
  2142. var preNode = node,
  2143. i = 0;
  2144. while (preNode = preNode.previousSibling) {
  2145. if (ignoreTextNode && preNode.nodeType == 3) {
  2146. if (preNode.nodeType != preNode.nextSibling.nodeType) {
  2147. i++;
  2148. }
  2149. continue;
  2150. }
  2151. i++;
  2152. }
  2153. return i;
  2154. },
  2155. /**
  2156. * 检测节点node是否在给定的document对象上
  2157. * @method inDoc
  2158. * @param { Node } node 需要检测的节点对象
  2159. * @param { DomDocument } doc 需要检测的document对象
  2160. * @return { Boolean } 该节点node是否在给定的document的dom树上
  2161. * @example
  2162. * ```javascript
  2163. *
  2164. * var node = document.createElement("div");
  2165. *
  2166. * //output: false
  2167. * console.log( UE.do.domUtils.inDoc( node, document ) );
  2168. *
  2169. * document.body.appendChild( node );
  2170. *
  2171. * //output: true
  2172. * console.log( UE.do.domUtils.inDoc( node, document ) );
  2173. *
  2174. * ```
  2175. */
  2176. inDoc: function (node, doc) {
  2177. return domUtils.getPosition(node, doc) == 10;
  2178. },
  2179. /**
  2180. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  2181. * 查找的起点是给定node节点的父节点。
  2182. * @method findParent
  2183. * @param { Node } node 需要查找的节点
  2184. * @param { Function } filterFn 自定义的过滤方法。
  2185. * @warning 查找的终点是到body节点为止
  2186. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  2187. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  2188. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  2189. * @example
  2190. * ```javascript
  2191. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  2192. *
  2193. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  2194. * return node.tagName === "HTML";
  2195. *
  2196. * } );
  2197. *
  2198. * //output: true
  2199. * console.log( filterNode === null );
  2200. * ```
  2201. */
  2202. /**
  2203. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  2204. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  2205. * @method findParent
  2206. * @param { Node } node 需要查找的节点
  2207. * @param { Function } filterFn 自定义的过滤方法。
  2208. * @param { Boolean } includeSelf 查找过程是否包含自身
  2209. * @warning 查找的终点是到body节点为止
  2210. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  2211. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  2212. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  2213. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  2214. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  2215. * @example
  2216. * ```html
  2217. * <body>
  2218. *
  2219. * <div id="test">
  2220. * </div>
  2221. *
  2222. * <script type="text/javascript">
  2223. *
  2224. * //output: DIV, BODY
  2225. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  2226. *
  2227. * console.log( node.tagName );
  2228. * return false;
  2229. *
  2230. * }, true );
  2231. *
  2232. * </script>
  2233. * </body>
  2234. * ```
  2235. */
  2236. findParent: function (node, filterFn, includeSelf) {
  2237. if (node && !domUtils.isBody(node)) {
  2238. node = includeSelf ? node : node.parentNode;
  2239. while (node) {
  2240. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2241. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2242. }
  2243. node = node.parentNode;
  2244. }
  2245. }
  2246. return null;
  2247. },
  2248. /**
  2249. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2250. * @method findParentByTagName
  2251. * @param { Node } node 需要查找的节点对象
  2252. * @param { Array } tagNames 需要查找的父节点的名称数组
  2253. * @warning 查找的终点是到body节点为止
  2254. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2255. * @example
  2256. * ```javascript
  2257. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2258. * //output: BODY
  2259. * console.log( node.tagName );
  2260. * ```
  2261. */
  2262. /**
  2263. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2264. * 否则, 起点是node的父节点。
  2265. * @method findParentByTagName
  2266. * @param { Node } node 需要查找的节点对象
  2267. * @param { Array } tagNames 需要查找的父节点的名称数组
  2268. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2269. * @warning 查找的终点是到body节点为止
  2270. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2271. * @example
  2272. * ```javascript
  2273. * var queryTarget = document.getElementsByTagName("div")[0];
  2274. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2275. * //output: true
  2276. * console.log( queryTarget === node );
  2277. * ```
  2278. */
  2279. findParentByTagName: function (node, tagNames, includeSelf, excludeFn) {
  2280. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2281. return domUtils.findParent(node, function (node) {
  2282. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2283. }, includeSelf);
  2284. },
  2285. /**
  2286. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2287. * @method findParents
  2288. * @param { Node } node 需要查找的节点对象
  2289. * @return { Array } 给定节点的祖先节点数组
  2290. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2291. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2292. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2293. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2294. */
  2295. /**
  2296. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2297. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2298. * @method findParents
  2299. * @param { Node } node 需要查找的节点对象
  2300. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2301. * @return { Array } 给定节点的祖先节点数组
  2302. */
  2303. findParents: function (node, includeSelf, filterFn, closerFirst) {
  2304. var parents = includeSelf && (filterFn && filterFn(node) || !filterFn) ? [node] : [];
  2305. while (node = domUtils.findParent(node, filterFn)) {
  2306. parents.push(node);
  2307. }
  2308. return closerFirst ? parents : parents.reverse();
  2309. },
  2310. /**
  2311. * 在节点node后面插入新节点newNode
  2312. * @method insertAfter
  2313. * @param { Node } node 目标节点
  2314. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2315. * @return { Node } 新插入的节点
  2316. */
  2317. insertAfter: function (node, newNode) {
  2318. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling) :
  2319. node.parentNode.appendChild(newNode);
  2320. },
  2321. /**
  2322. * 删除节点node及其下属的所有节点
  2323. * @method remove
  2324. * @param { Node } node 需要删除的节点对象
  2325. * @return { Node } 返回刚删除的节点对象
  2326. * @example
  2327. * ```html
  2328. * <div id="test">
  2329. * <div id="child">你好</div>
  2330. * </div>
  2331. * <script>
  2332. * UE.dom.domUtils.remove( document.body, false );
  2333. * //output: false
  2334. * console.log( document.getElementById( "child" ) !== null );
  2335. * </script>
  2336. * ```
  2337. */
  2338. /**
  2339. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2340. * @method remove
  2341. * @param { Node } node 需要删除的节点对象
  2342. * @param { Boolean } keepChildren 是否需要保留子节点
  2343. * @return { Node } 返回刚删除的节点对象
  2344. * @example
  2345. * ```html
  2346. * <div id="test">
  2347. * <div id="child">你好</div>
  2348. * </div>
  2349. * <script>
  2350. * UE.dom.domUtils.remove( document.body, true );
  2351. * //output: true
  2352. * console.log( document.getElementById( "child" ) !== null );
  2353. * </script>
  2354. * ```
  2355. */
  2356. remove: function (node, keepChildren, range) {
  2357. var parent = node.parentNode,
  2358. child;
  2359. if (parent) {
  2360. if (keepChildren && node.hasChildNodes()) {
  2361. while (child = node.firstChild) {
  2362. // parent.insertBefore(child, node);
  2363. /**
  2364. * 0603
  2365. * add:如果是去掉加效果,但节点又有加粗效果时,去不成功
  2366. */
  2367. if (child.nodeType == 3 && node.tagName && node.tagName.toLowerCase() == 'strong') {
  2368. if (range.ueStyleUtils.isParentHasFontWeightStyle(node.parentNode)) {
  2369. var span = ue.document.createElement('span');
  2370. span.style.fontWeight = 'normal';
  2371. span.appendChild(child)
  2372. parent.insertBefore(span, node);
  2373. } else {
  2374. parent.insertBefore(child, node);
  2375. }
  2376. } else {
  2377. parent.insertBefore(child, node);
  2378. }
  2379. /************************** */
  2380. }
  2381. }
  2382. parent.removeChild(node);
  2383. }
  2384. return node;
  2385. },
  2386. /**
  2387. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2388. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2389. * @method getNextDomNode
  2390. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2391. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2392. * @example
  2393. * ```html
  2394. * <body>
  2395. * <div id="test">
  2396. * <span></span>
  2397. * </div>
  2398. * <i>xxx</i>
  2399. * </body>
  2400. * <script>
  2401. *
  2402. * //output: i节点
  2403. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2404. *
  2405. * </script>
  2406. * ```
  2407. * @example
  2408. * ```html
  2409. * <body>
  2410. * <div>
  2411. * <span></span>
  2412. * <i id="test">xxx</i>
  2413. * </div>
  2414. * <b>xxx</b>
  2415. * </body>
  2416. * <script>
  2417. *
  2418. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2419. * //output: b节点
  2420. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2421. *
  2422. * </script>
  2423. * ```
  2424. */
  2425. /**
  2426. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2427. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2428. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2429. * @method getNextDomNode
  2430. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2431. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2432. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2433. * @see UE.dom.domUtils.getNextDomNode(Node)
  2434. */
  2435. getNextDomNode: function (node, startFromChild, filterFn, guard) {
  2436. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2437. },
  2438. getPreDomNode: function (node, startFromChild, filterFn, guard) {
  2439. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2440. },
  2441. /**
  2442. * 检测节点node是否属是UEditor定义的bookmark节点
  2443. * @method isBookmarkNode
  2444. * @private
  2445. * @param { Node } node 需要检测的节点对象
  2446. * @return { Boolean } 是否是bookmark节点
  2447. * @example
  2448. * ```html
  2449. * <span id="_baidu_bookmark_1"></span>
  2450. * <script>
  2451. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2452. * //output: true
  2453. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2454. * </script>
  2455. * ```
  2456. */
  2457. isBookmarkNode: function (node) {
  2458. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2459. },
  2460. /**
  2461. * 获取节点node所属的window对象
  2462. * @method getWindow
  2463. * @param { Node } node 节点对象
  2464. * @return { Window } 当前节点所属的window对象
  2465. * @example
  2466. * ```javascript
  2467. * //output: true
  2468. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2469. * ```
  2470. */
  2471. getWindow: function (node) {
  2472. var doc = node.ownerDocument || node;
  2473. return doc.defaultView || doc.parentWindow;
  2474. },
  2475. /**
  2476. * 获取离nodeA与nodeB最近的公共的祖先节点
  2477. * @method getCommonAncestor
  2478. * @param { Node } nodeA 第一个节点
  2479. * @param { Node } nodeB 第二个节点
  2480. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2481. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2482. * @example
  2483. * ```javascript
  2484. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2485. * //output: true
  2486. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2487. * ```
  2488. */
  2489. getCommonAncestor: function (nodeA, nodeB) {
  2490. if (nodeA === nodeB)
  2491. return nodeA;
  2492. var parentsA = [nodeA], parentsB = [nodeB], parent = nodeA, i = -1;
  2493. while (parent = parent.parentNode) {
  2494. if (parent === nodeB) {
  2495. return parent;
  2496. }
  2497. parentsA.push(parent);
  2498. }
  2499. parent = nodeB;
  2500. while (parent = parent.parentNode) {
  2501. if (parent === nodeA)
  2502. return parent;
  2503. parentsB.push(parent);
  2504. }
  2505. parentsA.reverse();
  2506. parentsB.reverse();
  2507. while (i++, parentsA[i] === parentsB[i]) {
  2508. }
  2509. return i == 0 ? null : parentsA[i - 1];
  2510. },
  2511. /**
  2512. * 清除node节点左右连续为空的兄弟inline节点
  2513. * @method clearEmptySibling
  2514. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2515. * 则这些兄弟节点将被删除
  2516. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2517. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2518. * @example
  2519. * ```html
  2520. * <body>
  2521. * <div></div>
  2522. * <span id="test"></span>
  2523. * <i></i>
  2524. * <b></b>
  2525. * <em>xxx</em>
  2526. * <span></span>
  2527. * </body>
  2528. * <script>
  2529. *
  2530. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2531. *
  2532. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2533. * console.log( document.body.innerHTML );
  2534. *
  2535. * </script>
  2536. * ```
  2537. */
  2538. /**
  2539. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2540. * 则忽略对右边兄弟节点的操作。
  2541. * @method clearEmptySibling
  2542. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2543. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2544. * 则这些兄弟节点将被删除
  2545. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2546. */
  2547. /**
  2548. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2549. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2550. * @method clearEmptySibling
  2551. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2552. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2553. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2554. * 则这些兄弟节点将被删除
  2555. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2556. */
  2557. clearEmptySibling: function (node, ignoreNext, ignorePre) {
  2558. function clear(next, dir) {
  2559. var tmpNode;
  2560. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2561. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2562. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue))) {
  2563. tmpNode = next[dir];
  2564. domUtils.remove(next);
  2565. next = tmpNode;
  2566. }
  2567. }
  2568. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2569. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2570. },
  2571. /**
  2572. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2573. * @method split
  2574. * @param { Node } textNode 需要拆分的文本节点对象
  2575. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2576. * @return { Node } 拆分后形成的新节点
  2577. * @example
  2578. * ```html
  2579. * <div id="test">abcdef</div>
  2580. * <script>
  2581. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2582. * //output: def
  2583. * console.log( newNode.nodeValue );
  2584. * </script>
  2585. * ```
  2586. */
  2587. split: function (node, offset) {
  2588. var doc = node.ownerDocument;
  2589. if (browser.ie && offset == node.nodeValue.length) {
  2590. var next = doc.createTextNode('');
  2591. return domUtils.insertAfter(node, next);
  2592. }
  2593. var retval = node.splitText(offset);
  2594. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2595. if (browser.ie8) {
  2596. var tmpNode = doc.createTextNode('');
  2597. domUtils.insertAfter(retval, tmpNode);
  2598. domUtils.remove(tmpNode);
  2599. }
  2600. return retval;
  2601. },
  2602. /**
  2603. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2604. * @method isWhitespace
  2605. * @param { Node } node 需要检测的节点对象
  2606. * @return { Boolean } 检测的节点是否为空
  2607. * @example
  2608. * ```html
  2609. * <div id="test">
  2610. *
  2611. * </div>
  2612. * <script>
  2613. * //output: true
  2614. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2615. * </script>
  2616. * ```
  2617. */
  2618. isWhitespace: function (node) {
  2619. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2620. },
  2621. /**
  2622. * 获取元素element相对于viewport的位置坐标
  2623. * @method getXY
  2624. * @param { Node } element 需要计算位置的节点对象
  2625. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2626. * y代表垂直偏移距离。
  2627. *
  2628. * @example
  2629. * ```javascript
  2630. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2631. * //output: test的坐标为: 12, 24
  2632. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2633. * ```
  2634. */
  2635. getXY: function (element) {
  2636. var x = 0, y = 0;
  2637. while (element.offsetParent) {
  2638. y += element.offsetTop;
  2639. x += element.offsetLeft;
  2640. element = element.offsetParent;
  2641. }
  2642. return {'x': x, 'y': y};
  2643. },
  2644. /**
  2645. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2646. * @method on
  2647. * @param { Node } element 需要绑定事件的节点对象
  2648. * @param { String } type 绑定的事件类型
  2649. * @param { Function } handler 事件处理器
  2650. * @example
  2651. * ```javascript
  2652. * UE.dom.domUtils.on(document.body,"click",function(e){
  2653. * //e为事件对象,this为被点击元素对戏那个
  2654. * });
  2655. * ```
  2656. */
  2657. /**
  2658. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2659. * @method on
  2660. * @param { Node } element 需要绑定事件的节点对象
  2661. * @param { Array } type 绑定的事件类型数组
  2662. * @param { Function } handler 事件处理器
  2663. * @example
  2664. * ```javascript
  2665. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2666. * //evt为事件对象,this为被点击元素对象
  2667. * });
  2668. * ```
  2669. */
  2670. on: function (element, type, handler) {
  2671. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2672. k = types.length;
  2673. if (k) while (k--) {
  2674. type = types[k];
  2675. if (element.addEventListener) {
  2676. element.addEventListener(type, handler, false);
  2677. } else {
  2678. if (!handler._d) {
  2679. handler._d = {
  2680. els: []
  2681. };
  2682. }
  2683. var key = type + handler.toString(), index = utils.indexOf(handler._d.els, element);
  2684. if (!handler._d[key] || index == -1) {
  2685. if (index == -1) {
  2686. handler._d.els.push(element);
  2687. }
  2688. if (!handler._d[key]) {
  2689. handler._d[key] = function (evt) {
  2690. return handler.call(evt.srcElement, evt || window.event);
  2691. };
  2692. }
  2693. element.attachEvent('on' + type, handler._d[key]);
  2694. }
  2695. }
  2696. }
  2697. element = null;
  2698. },
  2699. /**
  2700. * 解除DOM事件绑定
  2701. * @method un
  2702. * @param { Node } element 需要解除事件绑定的节点对象
  2703. * @param { String } type 需要接触绑定的事件类型
  2704. * @param { Function } handler 对应的事件处理器
  2705. * @example
  2706. * ```javascript
  2707. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2708. * //evt为事件对象,this为被点击元素对象
  2709. * });
  2710. * ```
  2711. */
  2712. /**
  2713. * 解除DOM事件绑定
  2714. * @method un
  2715. * @param { Node } element 需要解除事件绑定的节点对象
  2716. * @param { Array } type 需要接触绑定的事件类型数组
  2717. * @param { Function } handler 对应的事件处理器
  2718. * @example
  2719. * ```javascript
  2720. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2721. * //evt为事件对象,this为被点击元素对象
  2722. * });
  2723. * ```
  2724. */
  2725. un: function (element, type, handler) {
  2726. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2727. k = types.length;
  2728. if (k) while (k--) {
  2729. type = types[k];
  2730. if (element.removeEventListener) {
  2731. element.removeEventListener(type, handler, false);
  2732. } else {
  2733. var key = type + handler.toString();
  2734. try {
  2735. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2736. } catch (e) {
  2737. }
  2738. if (handler._d && handler._d[key]) {
  2739. var index = utils.indexOf(handler._d.els, element);
  2740. if (index != -1) {
  2741. handler._d.els.splice(index, 1);
  2742. }
  2743. handler._d.els.length == 0 && delete handler._d[key];
  2744. }
  2745. }
  2746. }
  2747. },
  2748. /**
  2749. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2750. * @method isSameElement
  2751. * @param { Node } nodeA 需要比较的节点
  2752. * @param { Node } nodeB 需要比较的节点
  2753. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2754. * @example
  2755. * ```html
  2756. * <span style="font-size:12px">ssss</span>
  2757. * <span style="font-size:12px">bbbbb</span>
  2758. * <span style="font-size:13px">ssss</span>
  2759. * <span style="font-size:14px">bbbbb</span>
  2760. *
  2761. * <script>
  2762. *
  2763. * var nodes = document.getElementsByTagName( "span" );
  2764. *
  2765. * //output: true
  2766. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2767. *
  2768. * //output: false
  2769. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2770. *
  2771. * </script>
  2772. * ```
  2773. */
  2774. isSameElement: function (nodeA, nodeB) {
  2775. if (nodeA.tagName != nodeB.tagName) {
  2776. return false;
  2777. }
  2778. var thisAttrs = nodeA.attributes,
  2779. otherAttrs = nodeB.attributes;
  2780. if (!ie && thisAttrs.length != otherAttrs.length) {
  2781. return false;
  2782. }
  2783. var attrA, attrB, al = 0, bl = 0;
  2784. for (var i = 0; attrA = thisAttrs[i++];) {
  2785. if (attrA.nodeName == 'style') {
  2786. if (attrA.specified) {
  2787. al++;
  2788. }
  2789. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2790. continue;
  2791. } else {
  2792. return false;
  2793. }
  2794. }
  2795. if (ie) {
  2796. if (attrA.specified) {
  2797. al++;
  2798. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2799. } else {
  2800. continue;
  2801. }
  2802. } else {
  2803. attrB = nodeB.attributes[attrA.nodeName];
  2804. }
  2805. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2806. return false;
  2807. }
  2808. }
  2809. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2810. if (ie) {
  2811. for (i = 0; attrB = otherAttrs[i++];) {
  2812. if (attrB.specified) {
  2813. bl++;
  2814. }
  2815. }
  2816. if (al != bl) {
  2817. return false;
  2818. }
  2819. }
  2820. return true;
  2821. },
  2822. /**
  2823. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2824. * @method isSameStyle
  2825. * @param { Node } nodeA 需要比较的节点
  2826. * @param { Node } nodeB 需要比较的节点
  2827. * @return { Boolean } 两个节点是否具有相同的style属性值
  2828. * @example
  2829. * ```html
  2830. * <span style="font-size:12px">ssss</span>
  2831. * <span style="font-size:12px">bbbbb</span>
  2832. * <span style="font-size:13px">ssss</span>
  2833. * <span style="font-size:14px">bbbbb</span>
  2834. *
  2835. * <script>
  2836. *
  2837. * var nodes = document.getElementsByTagName( "span" );
  2838. *
  2839. * //output: true
  2840. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2841. *
  2842. * //output: false
  2843. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2844. *
  2845. * </script>
  2846. * ```
  2847. */
  2848. isSameStyle: function (nodeA, nodeB) {
  2849. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2850. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2851. if (browser.opera) {
  2852. styleA = nodeA.style;
  2853. styleB = nodeB.style;
  2854. if (styleA.length != styleB.length)
  2855. return false;
  2856. for (var p in styleA) {
  2857. if (/^(\d+|csstext)$/i.test(p)) {
  2858. continue;
  2859. }
  2860. if (styleA[p] != styleB[p]) {
  2861. return false;
  2862. }
  2863. }
  2864. return true;
  2865. }
  2866. if (!styleA || !styleB) {
  2867. return styleA == styleB;
  2868. }
  2869. styleA = styleA.split(';');
  2870. styleB = styleB.split(';');
  2871. if (styleA.length != styleB.length) {
  2872. return false;
  2873. }
  2874. for (var i = 0, ci; ci = styleA[i++];) {
  2875. if (utils.indexOf(styleB, ci) == -1) {
  2876. return false;
  2877. }
  2878. }
  2879. return true;
  2880. },
  2881. /**
  2882. * 检查节点node是否为block元素
  2883. * @method isBlockElm
  2884. * @param { Node } node 需要检测的节点对象
  2885. * @return { Boolean } 是否是block元素节点
  2886. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2887. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2888. * @example
  2889. * ```html
  2890. * <span id="test1" style="display: block"></span>
  2891. * <span id="test2"></span>
  2892. * <div id="test3" style="display: inline"></div>
  2893. *
  2894. * <script>
  2895. *
  2896. * //output: true
  2897. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2898. *
  2899. * //output: false
  2900. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2901. *
  2902. * //output: true
  2903. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2904. *
  2905. * </script>
  2906. * ```
  2907. */
  2908. isBlockElm: function (node) {
  2909. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2910. },
  2911. /**
  2912. * 检测node节点是否为body节点
  2913. * @method isBody
  2914. * @param { Element } node 需要检测的dom元素
  2915. * @return { Boolean } 给定的元素是否是body元素
  2916. * @example
  2917. * ```javascript
  2918. * //output: true
  2919. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2920. * ```
  2921. */
  2922. isBody: function (node) {
  2923. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2924. },
  2925. /**
  2926. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2927. * 拆分形成的两个节点之间是node节点
  2928. * @method breakParent
  2929. * @param { Node } node 作为分界的节点对象
  2930. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2931. * @return { Node } 给定的node分界节点
  2932. * @example
  2933. * ```javascript
  2934. *
  2935. * var node = document.createElement("span"),
  2936. * wrapNode = document.createElement( "div" ),
  2937. * parent = document.createElement("p");
  2938. *
  2939. * parent.appendChild( node );
  2940. * wrapNode.appendChild( parent );
  2941. *
  2942. * //拆分前
  2943. * //output: <p><span></span></p>
  2944. * console.log( wrapNode.innerHTML );
  2945. *
  2946. *
  2947. * UE.dom.domUtils.breakParent( node, parent );
  2948. * //拆分后
  2949. * //output: <p></p><span></span><p></p>
  2950. * console.log( wrapNode.innerHTML );
  2951. *
  2952. * ```
  2953. */
  2954. breakParent: function (node, parent) {
  2955. var tmpNode,
  2956. parentClone = node,
  2957. clone = node,
  2958. leftNodes,
  2959. rightNodes;
  2960. do {
  2961. parentClone = parentClone.parentNode;
  2962. if (leftNodes) {
  2963. tmpNode = parentClone.cloneNode(false);
  2964. tmpNode.appendChild(leftNodes);
  2965. leftNodes = tmpNode;
  2966. tmpNode = parentClone.cloneNode(false);
  2967. tmpNode.appendChild(rightNodes);
  2968. rightNodes = tmpNode;
  2969. } else {
  2970. leftNodes = parentClone.cloneNode(false);
  2971. rightNodes = leftNodes.cloneNode(false);
  2972. }
  2973. while (tmpNode = clone.previousSibling) {
  2974. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2975. }
  2976. while (tmpNode = clone.nextSibling) {
  2977. rightNodes.appendChild(tmpNode);
  2978. }
  2979. clone = parentClone;
  2980. } while (parent !== parentClone);
  2981. tmpNode = parent.parentNode;
  2982. tmpNode.insertBefore(leftNodes, parent);
  2983. tmpNode.insertBefore(rightNodes, parent);
  2984. tmpNode.insertBefore(node, rightNodes);
  2985. domUtils.remove(parent);
  2986. return node;
  2987. },
  2988. /**
  2989. * 检查节点node是否是空inline节点
  2990. * @method isEmptyInlineElement
  2991. * @param { Node } node 需要检测的节点对象
  2992. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2993. * @example
  2994. * ```html
  2995. * <b><i></i></b> => 1
  2996. * <b><i></i><u></u></b> => 1
  2997. * <b></b> => 1
  2998. * <b>xx<i></i></b> => 0
  2999. * ```
  3000. */
  3001. isEmptyInlineElement: function (node) {
  3002. if (node.nodeType != 1 || !dtd.$removeEmpty[node.tagName]) {
  3003. return 0;
  3004. }
  3005. node = node.firstChild;
  3006. while (node) {
  3007. //如果是创建的bookmark就跳过
  3008. if (domUtils.isBookmarkNode(node)) {
  3009. return 0;
  3010. }
  3011. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  3012. node.nodeType == 3 && !domUtils.isWhitespace(node)
  3013. ) {
  3014. return 0;
  3015. }
  3016. node = node.nextSibling;
  3017. }
  3018. return 1;
  3019. },
  3020. /**
  3021. * 删除node节点下首尾两端的空白文本子节点
  3022. * @method trimWhiteTextNode
  3023. * @param { Element } node 需要执行删除操作的元素对象
  3024. * @example
  3025. * ```javascript
  3026. * var node = document.createElement("div");
  3027. *
  3028. * node.appendChild( document.createTextNode( "" ) );
  3029. *
  3030. * node.appendChild( document.createElement("div") );
  3031. *
  3032. * node.appendChild( document.createTextNode( "" ) );
  3033. *
  3034. * //3
  3035. * console.log( node.childNodes.length );
  3036. *
  3037. * UE.dom.domUtils.trimWhiteTextNode( node );
  3038. *
  3039. * //1
  3040. * console.log( node.childNodes.length );
  3041. * ```
  3042. */
  3043. trimWhiteTextNode: function (node) {
  3044. function remove(dir) {
  3045. var child;
  3046. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  3047. node.removeChild(child);
  3048. }
  3049. }
  3050. remove('firstChild');
  3051. remove('lastChild');
  3052. },
  3053. /**
  3054. * 合并node节点下相同的子节点
  3055. * @name mergeChild
  3056. * @desc
  3057. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  3058. * @example
  3059. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  3060. * ==> UE.dom.domUtils.mergeChild(node,'span')
  3061. * <p><span style="font-size:12px;">xxaaxx</span></p>
  3062. */
  3063. mergeChild: function (node, tagName, attrs) {
  3064. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  3065. for (var i = 0, ci; ci = list[i++];) {
  3066. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  3067. continue;
  3068. }
  3069. //span单独处理
  3070. if (ci.tagName.toLowerCase() == 'span') {
  3071. if (node === ci.parentNode) {
  3072. domUtils.trimWhiteTextNode(node);
  3073. if (node.childNodes.length == 1) {
  3074. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  3075. domUtils.remove(ci, true);
  3076. continue;
  3077. }
  3078. }
  3079. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  3080. if (attrs) {
  3081. var style = attrs.style;
  3082. if (style) {
  3083. style = style.split(';');
  3084. for (var j = 0, s; s = style[j++];) {
  3085. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  3086. }
  3087. }
  3088. }
  3089. if (domUtils.isSameStyle(ci, node)) {
  3090. domUtils.remove(ci, true);
  3091. }
  3092. continue;
  3093. }
  3094. if (domUtils.isSameElement(node, ci)) {
  3095. domUtils.remove(ci, true);
  3096. }
  3097. }
  3098. },
  3099. /**
  3100. * 原生方法getElementsByTagName的封装
  3101. * @method getElementsByTagName
  3102. * @param { Node } node 目标节点对象
  3103. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  3104. * @return { Array } 符合条件的节点集合
  3105. */
  3106. getElementsByTagName: function (node, name, filter) {
  3107. if (filter && utils.isString(filter)) {
  3108. var className = filter;
  3109. filter = function (node) {
  3110. return domUtils.hasClass(node, className)
  3111. }
  3112. }
  3113. name = utils.trim(name).replace(/[ ]{2,}/g, ' ').split(' ');
  3114. var arr = [];
  3115. for (var n = 0, ni; ni = name[n++];) {
  3116. var list = node.getElementsByTagName(ni);
  3117. for (var i = 0, ci; ci = list[i++];) {
  3118. if (!filter || filter(ci))
  3119. arr.push(ci);
  3120. }
  3121. }
  3122. return arr;
  3123. },
  3124. /**
  3125. * 将节点node提取到父节点上
  3126. * @method mergeToParent
  3127. * @param { Element } node 需要提取的元素对象
  3128. * @example
  3129. * ```html
  3130. * <div id="parent">
  3131. * <div id="sub">
  3132. * <span id="child"></span>
  3133. * </div>
  3134. * </div>
  3135. *
  3136. * <script>
  3137. *
  3138. * var child = document.getElementById( "child" );
  3139. *
  3140. * //output: sub
  3141. * console.log( child.parentNode.id );
  3142. *
  3143. * UE.dom.domUtils.mergeToParent( child );
  3144. *
  3145. * //output: parent
  3146. * console.log( child.parentNode.id );
  3147. *
  3148. * </script>
  3149. * ```
  3150. */
  3151. mergeToParent: function (node) {
  3152. var parent = node.parentNode;
  3153. while (parent && dtd.$removeEmpty[parent.tagName]) {
  3154. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  3155. domUtils.trimWhiteTextNode(parent);
  3156. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  3157. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  3158. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  3159. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  3160. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  3161. parent = parent.parentNode;
  3162. continue;
  3163. } else {
  3164. parent.style.cssText += ";" + node.style.cssText;
  3165. //trace:952 a标签要保持下划线
  3166. if (parent.tagName == 'A') {
  3167. parent.style.textDecoration = 'underline';
  3168. }
  3169. }
  3170. }
  3171. if (parent.tagName != 'A') {
  3172. parent === node.parentNode && domUtils.remove(node, true);
  3173. break;
  3174. }
  3175. }
  3176. parent = parent.parentNode;
  3177. }
  3178. },
  3179. /**
  3180. * 合并节点node的左右兄弟节点
  3181. * @method mergeSibling
  3182. * @param { Element } node 需要合并的目标节点
  3183. * @example
  3184. * ```html
  3185. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  3186. *
  3187. * <script>
  3188. * var demoNode = document.getElementById("test");
  3189. * UE.dom.domUtils.mergeSibling( demoNode );
  3190. * //output: xxxxoooxxxx
  3191. * console.log( demoNode.innerHTML );
  3192. * </script>
  3193. * ```
  3194. */
  3195. /**
  3196. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  3197. * @method mergeSibling
  3198. * @param { Element } node 需要合并的目标节点
  3199. * @param { Boolean } ignorePre 是否忽略合并左节点
  3200. * @example
  3201. * ```html
  3202. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  3203. *
  3204. * <script>
  3205. * var demoNode = document.getElementById("test");
  3206. * UE.dom.domUtils.mergeSibling( demoNode, true );
  3207. * //output: oooxxxx
  3208. * console.log( demoNode.innerHTML );
  3209. * </script>
  3210. * ```
  3211. */
  3212. /**
  3213. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  3214. * @method mergeSibling
  3215. * @param { Element } node 需要合并的目标节点
  3216. * @param { Boolean } ignorePre 是否忽略合并左节点
  3217. * @param { Boolean } ignoreNext 是否忽略合并右节点
  3218. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  3219. * @example
  3220. * ```html
  3221. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  3222. *
  3223. * <script>
  3224. * var demoNode = document.getElementById("test");
  3225. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  3226. * //output: xxxxooo
  3227. * console.log( demoNode.innerHTML );
  3228. * </script>
  3229. * ```
  3230. */
  3231. mergeSibling: function (node, ignorePre, ignoreNext) {
  3232. function merge(rtl, start, node) {
  3233. var next;
  3234. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  3235. while (next.firstChild) {
  3236. if (start == 'firstChild') {
  3237. node.insertBefore(next.lastChild, node.firstChild);
  3238. } else {
  3239. node.appendChild(next.firstChild);
  3240. }
  3241. }
  3242. domUtils.remove(next);
  3243. }
  3244. }
  3245. !ignorePre && merge('previousSibling', 'firstChild', node);
  3246. !ignoreNext && merge('nextSibling', 'lastChild', node);
  3247. },
  3248. /**
  3249. * 设置节点node及其子节点不会被选中
  3250. * @method unSelectable
  3251. * @param { Element } node 需要执行操作的dom元素
  3252. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3253. * @example
  3254. * ```javascript
  3255. * UE.dom.domUtils.unSelectable( document.body );
  3256. * ```
  3257. */
  3258. unSelectable: ie && browser.ie9below || browser.opera ? function (node) {
  3259. //for ie9
  3260. node.onselectstart = function () {
  3261. return false;
  3262. };
  3263. node.onclick = node.onkeyup = node.onkeydown = function () {
  3264. return false;
  3265. };
  3266. node.unselectable = 'on';
  3267. node.setAttribute("unselectable", "on");
  3268. for (var i = 0, ci; ci = node.all[i++];) {
  3269. switch (ci.tagName.toLowerCase()) {
  3270. case 'iframe':
  3271. case 'textarea':
  3272. case 'input':
  3273. case 'select':
  3274. break;
  3275. default:
  3276. ci.unselectable = 'on';
  3277. node.setAttribute("unselectable", "on");
  3278. }
  3279. }
  3280. } : function (node) {
  3281. node.style.MozUserSelect =
  3282. node.style.webkitUserSelect =
  3283. node.style.msUserSelect =
  3284. node.style.KhtmlUserSelect = 'none';
  3285. },
  3286. /**
  3287. * 删除节点node上的指定属性名称的属性
  3288. * @method removeAttributes
  3289. * @param { Node } node 需要删除属性的节点对象
  3290. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3291. * @example
  3292. * ```html
  3293. * <div id="wrap">
  3294. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3295. * </div>
  3296. *
  3297. * <script>
  3298. *
  3299. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3300. *
  3301. * //output: <span style="font-size:14px;">xxxxx</span>
  3302. * console.log( document.getElementById("wrap").innerHTML );
  3303. *
  3304. * </script>
  3305. * ```
  3306. */
  3307. /**
  3308. * 删除节点node上的指定属性名称的属性
  3309. * @method removeAttributes
  3310. * @param { Node } node 需要删除属性的节点对象
  3311. * @param { Array } attrNames 需要删除的属性名数组
  3312. * @example
  3313. * ```html
  3314. * <div id="wrap">
  3315. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3316. * </div>
  3317. *
  3318. * <script>
  3319. *
  3320. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3321. *
  3322. * //output: <span style="font-size:14px;">xxxxx</span>
  3323. * console.log( document.getElementById("wrap").innerHTML );
  3324. *
  3325. * </script>
  3326. * ```
  3327. */
  3328. removeAttributes: function (node, attrNames) {
  3329. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3330. for (var i = 0, ci; ci = attrNames[i++];) {
  3331. ci = attrFix[ci] || ci;
  3332. switch (ci) {
  3333. case 'className':
  3334. node[ci] = '';
  3335. break;
  3336. case 'style':
  3337. node.style.cssText = '';
  3338. var val = node.getAttributeNode('style');
  3339. !browser.ie && val && node.removeAttributeNode(val);
  3340. }
  3341. node.removeAttribute(ci);
  3342. }
  3343. },
  3344. /**
  3345. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3346. * @method createElement
  3347. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3348. * @param { String } tagName 需要创建的元素的标签名
  3349. * @param { Object } attrs 新创建的元素的属性key-value集合
  3350. * @return { Element } 新创建的元素对象
  3351. * @example
  3352. * ```javascript
  3353. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3354. * id: 'test'
  3355. * } );
  3356. *
  3357. * //output: DIV
  3358. * console.log( ele.tagName );
  3359. *
  3360. * //output: test
  3361. * console.log( ele.id );
  3362. *
  3363. * ```
  3364. */
  3365. createElement: function (doc, tag, attrs) {
  3366. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3367. },
  3368. /**
  3369. * 为节点node添加属性attrs,attrs为属性键值对
  3370. * @method setAttributes
  3371. * @param { Element } node 需要设置属性的元素对象
  3372. * @param { Object } attrs 需要设置的属性名-值对
  3373. * @return { Element } 设置属性的元素对象
  3374. * @example
  3375. * ```html
  3376. * <span id="test"></span>
  3377. *
  3378. * <script>
  3379. *
  3380. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3381. * id: 'demo'
  3382. * } );
  3383. *
  3384. * //output: demo
  3385. * console.log( testNode.id );
  3386. *
  3387. * </script>
  3388. *
  3389. */
  3390. setAttributes: function (node, attrs) {
  3391. for (var attr in attrs) {
  3392. if (attrs.hasOwnProperty(attr)) {
  3393. var value = attrs[attr];
  3394. switch (attr) {
  3395. case 'class':
  3396. //ie下要这样赋值,setAttribute不起作用
  3397. node.className = value;
  3398. break;
  3399. case 'style':
  3400. node.style.cssText = node.style.cssText + ";" + value;
  3401. break;
  3402. case 'innerHTML':
  3403. node[attr] = value;
  3404. break;
  3405. case 'value':
  3406. node.value = value;
  3407. break;
  3408. default:
  3409. /**
  3410. * 0617
  3411. * add:针对单元格的对齐处理
  3412. */
  3413. if (attr == 'align' || attr == 'vAlign') {
  3414. var styleText = node.style.cssText;
  3415. if (styleText.indexOf('text-align') > -1) {
  3416. node.style.textAlign = '';
  3417. } else if (styleText.indexOf('vertical-align') > -1) {
  3418. node.style.verticalAlign = '';
  3419. }
  3420. }
  3421. /********************* */
  3422. node.setAttribute(attrFix[attr] || attr, value);
  3423. }
  3424. }
  3425. }
  3426. return node;
  3427. },
  3428. /**
  3429. * 获取元素element经过计算后的样式值
  3430. * @method getComputedStyle
  3431. * @param { Element } element 需要获取样式的元素对象
  3432. * @param { String } styleName 需要获取的样式名
  3433. * @return { String } 获取到的样式值
  3434. * @example
  3435. * ```html
  3436. * <style type="text/css">
  3437. * #test {
  3438. * font-size: 15px;
  3439. * }
  3440. * </style>
  3441. *
  3442. * <span id="test"></span>
  3443. *
  3444. * <script>
  3445. * //output: 15px
  3446. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3447. * </script>
  3448. * ```
  3449. */
  3450. getComputedStyle: function (element, styleName) {
  3451. //一下的属性单独处理
  3452. var pros = 'width height top left';
  3453. if (pros.indexOf(styleName) > -1) {
  3454. return element['offset' + styleName.replace(/^\w/, function (s) {
  3455. return s.toUpperCase()
  3456. })] + 'px';
  3457. }
  3458. //忽略文本节点
  3459. if (element.nodeType == 3) {
  3460. element = element.parentNode;
  3461. }
  3462. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3463. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3464. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3465. var span = element.ownerDocument.createElement('span');
  3466. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3467. span.innerHTML = '.';
  3468. element.appendChild(span);
  3469. var result = span.offsetHeight;
  3470. element.removeChild(span);
  3471. span = null;
  3472. return result + 'px';
  3473. }
  3474. try {
  3475. var value = domUtils.getStyle(element, styleName) ||
  3476. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3477. (element.currentStyle || element.style)[utils.cssStyleToDomStyle(styleName)]);
  3478. } catch (e) {
  3479. return "";
  3480. }
  3481. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3482. },
  3483. /**
  3484. * 删除元素element指定的className
  3485. * @method removeClasses
  3486. * @param { Element } ele 需要删除class的元素节点
  3487. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3488. * @example
  3489. * ```html
  3490. * <span id="test" class="test1 test2 test3">xxx</span>
  3491. *
  3492. * <script>
  3493. *
  3494. * var testNode = document.getElementById( "test" );
  3495. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3496. *
  3497. * //output: test3
  3498. * console.log( testNode.className );
  3499. *
  3500. * </script>
  3501. * ```
  3502. */
  3503. /**
  3504. * 删除元素element指定的className
  3505. * @method removeClasses
  3506. * @param { Element } ele 需要删除class的元素节点
  3507. * @param { Array } classNames 需要删除的className数组
  3508. * @example
  3509. * ```html
  3510. * <span id="test" class="test1 test2 test3">xxx</span>
  3511. *
  3512. * <script>
  3513. *
  3514. * var testNode = document.getElementById( "test" );
  3515. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3516. *
  3517. * //output: test3
  3518. * console.log( testNode.className );
  3519. *
  3520. * </script>
  3521. * ```
  3522. */
  3523. removeClasses: function (elm, classNames) {
  3524. classNames = utils.isArray(classNames) ? classNames :
  3525. utils.trim(classNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3526. for (var i = 0, ci, cls = elm.className; ci = classNames[i++];) {
  3527. cls = cls.replace(new RegExp('\\b' + ci + '\\b'), '')
  3528. }
  3529. cls = utils.trim(cls).replace(/[ ]{2,}/g, ' ');
  3530. if (cls) {
  3531. elm.className = cls;
  3532. } else {
  3533. domUtils.removeAttributes(elm, ['class']);
  3534. }
  3535. },
  3536. /**
  3537. * 给元素element添加className
  3538. * @method addClass
  3539. * @param { Node } ele 需要增加className的元素
  3540. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3541. * @remind 相同的类名不会被重复添加
  3542. * @example
  3543. * ```html
  3544. * <span id="test" class="cls1 cls2"></span>
  3545. *
  3546. * <script>
  3547. * var testNode = document.getElementById("test");
  3548. *
  3549. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3550. *
  3551. * //output: cl1 cls2 cls3 cls4
  3552. * console.log( testNode.className );
  3553. *
  3554. * <script>
  3555. * ```
  3556. */
  3557. /**
  3558. * 给元素element添加className
  3559. * @method addClass
  3560. * @param { Node } ele 需要增加className的元素
  3561. * @param { Array } classNames 需要添加的className的数组
  3562. * @remind 相同的类名不会被重复添加
  3563. * @example
  3564. * ```html
  3565. * <span id="test" class="cls1 cls2"></span>
  3566. *
  3567. * <script>
  3568. * var testNode = document.getElementById("test");
  3569. *
  3570. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3571. *
  3572. * //output: cl1 cls2 cls3 cls4
  3573. * console.log( testNode.className );
  3574. *
  3575. * <script>
  3576. * ```
  3577. */
  3578. addClass: function (elm, classNames) {
  3579. if (!elm) return;
  3580. classNames = utils.trim(classNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3581. for (var i = 0, ci, cls = elm.className; ci = classNames[i++];) {
  3582. if (!new RegExp('\\b' + ci + '\\b').test(cls)) {
  3583. cls += ' ' + ci;
  3584. }
  3585. }
  3586. elm.className = utils.trim(cls);
  3587. },
  3588. /**
  3589. * 判断元素element是否包含给定的样式类名className
  3590. * @method hasClass
  3591. * @param { Node } ele 需要检测的元素
  3592. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3593. * @return { Boolean } 元素是否包含所有给定的className
  3594. * @example
  3595. * ```html
  3596. * <span id="test1" class="cls1 cls2"></span>
  3597. *
  3598. * <script>
  3599. * var test1 = document.getElementById("test1");
  3600. *
  3601. * //output: false
  3602. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3603. *
  3604. * //output: true
  3605. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3606. * </script>
  3607. * ```
  3608. */
  3609. /**
  3610. * 判断元素element是否包含给定的样式类名className
  3611. * @method hasClass
  3612. * @param { Node } ele 需要检测的元素
  3613. * @param { Array } classNames 需要检测的className数组
  3614. * @return { Boolean } 元素是否包含所有给定的className
  3615. * @example
  3616. * ```html
  3617. * <span id="test1" class="cls1 cls2"></span>
  3618. *
  3619. * <script>
  3620. * var test1 = document.getElementById("test1");
  3621. *
  3622. * //output: false
  3623. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3624. *
  3625. * //output: true
  3626. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3627. * </script>
  3628. * ```
  3629. */
  3630. hasClass: function (element, className) {
  3631. if (utils.isRegExp(className)) {
  3632. return className.test(element.className)
  3633. }
  3634. className = utils.trim(className).replace(/[ ]{2,}/g, ' ').split(' ');
  3635. for (var i = 0, ci, cls = element.className; ci = className[i++];) {
  3636. if (!new RegExp('\\b' + ci + '\\b', 'i').test(cls)) {
  3637. return false;
  3638. }
  3639. }
  3640. return i - 1 == className.length;
  3641. },
  3642. /**
  3643. * 阻止事件默认行为
  3644. * @method preventDefault
  3645. * @param { Event } evt 需要阻止默认行为的事件对象
  3646. * @example
  3647. * ```javascript
  3648. * UE.dom.domUtils.preventDefault( evt );
  3649. * ```
  3650. */
  3651. preventDefault: function (evt) {
  3652. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3653. },
  3654. /**
  3655. * 删除元素element指定的样式
  3656. * @method removeStyle
  3657. * @param { Element } element 需要删除样式的元素
  3658. * @param { String } styleName 需要删除的样式名
  3659. * @example
  3660. * ```html
  3661. * <span id="test" style="color: red; background: blue;"></span>
  3662. *
  3663. * <script>
  3664. *
  3665. * var testNode = document.getElementById("test");
  3666. *
  3667. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3668. *
  3669. * //output: background: blue;
  3670. * console.log( testNode.style.cssText );
  3671. *
  3672. * </script>
  3673. * ```
  3674. */
  3675. removeStyle: function (element, name) {
  3676. if (browser.ie) {
  3677. //针对color先单独处理一下
  3678. if (name == 'color') {
  3679. name = '(^|;)' + name;
  3680. }
  3681. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?', 'ig'), '')
  3682. } else {
  3683. if (element.style.removeProperty) {
  3684. element.style.removeProperty(name);
  3685. } else {
  3686. element.style.removeAttribute(utils.cssStyleToDomStyle(name));
  3687. }
  3688. }
  3689. if (!element.style.cssText) {
  3690. domUtils.removeAttributes(element, ['style']);
  3691. }
  3692. },
  3693. /**
  3694. * 获取元素element的style属性的指定值
  3695. * @method getStyle
  3696. * @param { Element } element 需要获取属性值的元素
  3697. * @param { String } styleName 需要获取的style的名称
  3698. * @warning 该方法仅获取元素style属性中所标明的值
  3699. * @return { String } 该元素包含指定的style属性值
  3700. * @example
  3701. * ```html
  3702. * <div id="test" style="color: red;"></div>
  3703. *
  3704. * <script>
  3705. *
  3706. * var testNode = document.getElementById( "test" );
  3707. *
  3708. * //output: red
  3709. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3710. *
  3711. * //output: ""
  3712. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3713. *
  3714. * </script>
  3715. * ```
  3716. */
  3717. getStyle: function (element, name) {
  3718. var value = element.style[utils.cssStyleToDomStyle(name)];
  3719. return utils.fixColor(name, value);
  3720. },
  3721. /**
  3722. * 为元素element设置样式属性值
  3723. * @method setStyle
  3724. * @param { Element } element 需要设置样式的元素
  3725. * @param { String } styleName 样式名
  3726. * @param { String } styleValue 样式值
  3727. * @example
  3728. * ```html
  3729. * <div id="test"></div>
  3730. *
  3731. * <script>
  3732. *
  3733. * var testNode = document.getElementById( "test" );
  3734. *
  3735. * //output: ""
  3736. * console.log( testNode.style.color );
  3737. *
  3738. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3739. * //output: "red"
  3740. * console.log( testNode.style.color );
  3741. *
  3742. * </script>
  3743. * ```
  3744. */
  3745. setStyle: function (element, name, value) {
  3746. element.style[utils.cssStyleToDomStyle(name)] = value;
  3747. if (!utils.trim(element.style.cssText)) {
  3748. this.removeAttributes(element, 'style')
  3749. }
  3750. },
  3751. /**
  3752. * 为元素element设置多个样式属性值
  3753. * @method setStyles
  3754. * @param { Element } element 需要设置样式的元素
  3755. * @param { Object } styles 样式名值对
  3756. * @example
  3757. * ```html
  3758. * <div id="test"></div>
  3759. *
  3760. * <script>
  3761. *
  3762. * var testNode = document.getElementById( "test" );
  3763. *
  3764. * //output: ""
  3765. * console.log( testNode.style.color );
  3766. *
  3767. * UE.dom.domUtils.setStyles( testNode, {
  3768. * 'color': 'red'
  3769. * } );
  3770. * //output: "red"
  3771. * console.log( testNode.style.color );
  3772. *
  3773. * </script>
  3774. * ```
  3775. */
  3776. setStyles: function (element, styles) {
  3777. for (var name in styles) {
  3778. if (styles.hasOwnProperty(name)) {
  3779. domUtils.setStyle(element, name, styles[name]);
  3780. }
  3781. }
  3782. },
  3783. /**
  3784. * 删除_moz_dirty属性
  3785. * @private
  3786. * @method removeDirtyAttr
  3787. */
  3788. removeDirtyAttr: function (node) {
  3789. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3790. ci.removeAttribute('_moz_dirty');
  3791. }
  3792. node.removeAttribute('_moz_dirty');
  3793. },
  3794. /**
  3795. * 获取子节点的数量
  3796. * @method getChildCount
  3797. * @param { Element } node 需要检测的元素
  3798. * @return { Number } 给定的node元素的子节点数量
  3799. * @example
  3800. * ```html
  3801. * <div id="test">
  3802. * <span></span>
  3803. * </div>
  3804. *
  3805. * <script>
  3806. *
  3807. * //output: 3
  3808. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3809. *
  3810. * </script>
  3811. * ```
  3812. */
  3813. /**
  3814. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3815. * @method getChildCount
  3816. * @param { Element } node 需要检测的元素
  3817. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3818. * @return { Number } 符合过滤条件的node元素的子节点数量
  3819. * @example
  3820. * ```html
  3821. * <div id="test">
  3822. * <span></span>
  3823. * </div>
  3824. *
  3825. * <script>
  3826. *
  3827. * //output: 1
  3828. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3829. *
  3830. * return node.nodeType === 1;
  3831. *
  3832. * } ) );
  3833. *
  3834. * </script>
  3835. * ```
  3836. */
  3837. getChildCount: function (node, fn) {
  3838. var count = 0, first = node.firstChild;
  3839. fn = fn || function () {
  3840. return 1;
  3841. };
  3842. while (first) {
  3843. if (fn(first)) {
  3844. count++;
  3845. }
  3846. first = first.nextSibling;
  3847. }
  3848. return count;
  3849. },
  3850. /**
  3851. * 判断给定节点是否为空节点
  3852. * @method isEmptyNode
  3853. * @param { Node } node 需要检测的节点对象
  3854. * @return { Boolean } 节点是否为空
  3855. * @example
  3856. * ```javascript
  3857. * UE.dom.domUtils.isEmptyNode( document.body );
  3858. * ```
  3859. */
  3860. isEmptyNode: function (node) {
  3861. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3862. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3863. }) == 0
  3864. },
  3865. clearSelectedArr: function (nodes) {
  3866. var node;
  3867. while (node = nodes.pop()) {
  3868. domUtils.removeAttributes(node, ['class']);
  3869. }
  3870. },
  3871. /**
  3872. * 将显示区域滚动到指定节点的位置
  3873. * @method scrollToView
  3874. * @param {Node} node 节点
  3875. * @param {window} win window对象
  3876. * @param {Number} offsetTop 距离上方的偏移量
  3877. */
  3878. scrollToView: function (node, win, offsetTop) {
  3879. var getViewPaneSize = function () {
  3880. var doc = win.document,
  3881. mode = doc.compatMode == 'CSS1Compat';
  3882. return {
  3883. width: (mode ? doc.documentElement.clientWidth : doc.body.clientWidth) || 0,
  3884. height: (mode ? doc.documentElement.clientHeight : doc.body.clientHeight) || 0
  3885. };
  3886. },
  3887. getScrollPosition = function (win) {
  3888. if ('pageXOffset' in win) {
  3889. return {
  3890. x: win.pageXOffset || 0,
  3891. y: win.pageYOffset || 0
  3892. };
  3893. } else {
  3894. var doc = win.document;
  3895. return {
  3896. x: doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3897. y: doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3898. };
  3899. }
  3900. };
  3901. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3902. offset += (node.offsetHeight || 0);
  3903. var elementPosition = domUtils.getXY(node);
  3904. offset += elementPosition.y;
  3905. var currentScroll = getScrollPosition(win).y;
  3906. // offset += 50;
  3907. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3908. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3909. }
  3910. },
  3911. /**
  3912. * 判断给定节点是否为br
  3913. * @method isBr
  3914. * @param { Node } node 需要判断的节点对象
  3915. * @return { Boolean } 给定的节点是否是br节点
  3916. */
  3917. isBr: function (node) {
  3918. return node.nodeType == 1 && node.tagName == 'BR';
  3919. },
  3920. /**
  3921. * 判断给定的节点是否是一个“填充”节点
  3922. * @private
  3923. * @method isFillChar
  3924. * @param { Node } node 需要判断的节点
  3925. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3926. * @returns { Boolean } 节点是否是填充节点
  3927. */
  3928. isFillChar: function (node, isInStart) {
  3929. if (node.nodeType != 3)
  3930. return false;
  3931. var text = node.nodeValue;
  3932. if (isInStart) {
  3933. return new RegExp('^' + domUtils.fillChar).test(text)
  3934. }
  3935. return !text.replace(new RegExp(domUtils.fillChar, 'g'), '').length
  3936. },
  3937. isStartInblock: function (range) {
  3938. var tmpRange = range.cloneRange(),
  3939. flag = 0,
  3940. start = tmpRange.startContainer,
  3941. tmp;
  3942. if (start.nodeType == 1 && start.childNodes[tmpRange.startOffset]) {
  3943. start = start.childNodes[tmpRange.startOffset];
  3944. var pre = start.previousSibling;
  3945. while (pre && domUtils.isFillChar(pre)) {
  3946. start = pre;
  3947. pre = pre.previousSibling;
  3948. }
  3949. }
  3950. if (this.isFillChar(start, true) && tmpRange.startOffset == 1) {
  3951. tmpRange.setStartBefore(start);
  3952. start = tmpRange.startContainer;
  3953. }
  3954. while (start && domUtils.isFillChar(start)) {
  3955. tmp = start;
  3956. start = start.previousSibling
  3957. }
  3958. if (tmp) {
  3959. tmpRange.setStartBefore(tmp);
  3960. start = tmpRange.startContainer;
  3961. }
  3962. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3963. tmpRange.setStart(start, 0).collapse(true);
  3964. }
  3965. while (!tmpRange.startOffset) {
  3966. start = tmpRange.startContainer;
  3967. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3968. flag = 1;
  3969. break;
  3970. }
  3971. var pre = tmpRange.startContainer.previousSibling,
  3972. tmpNode;
  3973. if (!pre) {
  3974. tmpRange.setStartBefore(tmpRange.startContainer);
  3975. } else {
  3976. while (pre && domUtils.isFillChar(pre)) {
  3977. tmpNode = pre;
  3978. pre = pre.previousSibling;
  3979. }
  3980. if (tmpNode) {
  3981. tmpRange.setStartBefore(tmpNode);
  3982. } else {
  3983. tmpRange.setStartBefore(tmpRange.startContainer);
  3984. }
  3985. }
  3986. }
  3987. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3988. },
  3989. /**
  3990. * 判断给定的元素是否是一个空元素
  3991. * @method isEmptyBlock
  3992. * @param { Element } node 需要判断的元素
  3993. * @return { Boolean } 是否是空元素
  3994. * @example
  3995. * ```html
  3996. * <div id="test"></div>
  3997. *
  3998. * <script>
  3999. * //output: true
  4000. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  4001. * </script>
  4002. * ```
  4003. */
  4004. /**
  4005. * 根据指定的判断规则判断给定的元素是否是一个空元素
  4006. * @method isEmptyBlock
  4007. * @param { Element } node 需要判断的元素
  4008. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  4009. * @return { Boolean } 是否是空元素
  4010. */
  4011. isEmptyBlock: function (node, reg) {
  4012. // HaoChuan9421
  4013. if (!node) {
  4014. return;
  4015. }
  4016. if (node.nodeType != 1)
  4017. return 0;
  4018. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  4019. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  4020. return 0;
  4021. }
  4022. for (var n in dtd.$isNotEmpty) {
  4023. if (node.getElementsByTagName(n).length) {
  4024. return 0;
  4025. }
  4026. }
  4027. return 1;
  4028. },
  4029. /**
  4030. * 移动元素使得该元素的位置移动指定的偏移量的距离
  4031. * @method setViewportOffset
  4032. * @param { Element } element 需要设置偏移量的元素
  4033. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  4034. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  4035. * offset.top的距离
  4036. * @example
  4037. * ```html
  4038. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  4039. *
  4040. * <script>
  4041. *
  4042. * var testNode = document.getElementById("test");
  4043. *
  4044. * UE.dom.domUtils.setViewportOffset( testNode, {
  4045. * left: 200,
  4046. * top: 50
  4047. * } );
  4048. *
  4049. * //output: top: 300px; left: 100px; position: absolute;
  4050. * console.log( testNode.style.cssText );
  4051. *
  4052. * </script>
  4053. * ```
  4054. */
  4055. setViewportOffset: function (element, offset) {
  4056. var left = parseInt(element.style.left) | 0;
  4057. var top = parseInt(element.style.top) | 0;
  4058. var rect = element.getBoundingClientRect();
  4059. var offsetLeft = offset.left - rect.left;
  4060. var offsetTop = offset.top - rect.top;
  4061. if (offsetLeft) {
  4062. element.style.left = left + offsetLeft + 'px';
  4063. }
  4064. if (offsetTop) {
  4065. element.style.top = top + offsetTop + 'px';
  4066. }
  4067. },
  4068. /**
  4069. * 用“填充字符”填充节点
  4070. * @method fillNode
  4071. * @private
  4072. * @param { DomDocument } doc 填充的节点所在的docment对象
  4073. * @param { Node } node 需要填充的节点对象
  4074. * @example
  4075. * ```html
  4076. * <div id="test"></div>
  4077. *
  4078. * <script>
  4079. * var testNode = document.getElementById("test");
  4080. *
  4081. * //output: 0
  4082. * console.log( testNode.childNodes.length );
  4083. *
  4084. * UE.dom.domUtils.fillNode( document, testNode );
  4085. *
  4086. * //output: 1
  4087. * console.log( testNode.childNodes.length );
  4088. *
  4089. * </script>
  4090. * ```
  4091. */
  4092. fillNode: function (doc, node) {
  4093. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  4094. node.innerHTML = '';
  4095. node.appendChild(tmpNode);
  4096. },
  4097. /**
  4098. * 把节点src的所有子节点追加到另一个节点tag上去
  4099. * @method moveChild
  4100. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  4101. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  4102. * @example
  4103. * ```html
  4104. * <div id="test1">
  4105. * <span></span>
  4106. * </div>
  4107. * <div id="test2">
  4108. * <div></div>
  4109. * </div>
  4110. *
  4111. * <script>
  4112. *
  4113. * var test1 = document.getElementById("test1"),
  4114. * test2 = document.getElementById("test2");
  4115. *
  4116. * UE.dom.domUtils.moveChild( test1, test2 );
  4117. *
  4118. * //output: ""(空字符串)
  4119. * console.log( test1.innerHTML );
  4120. *
  4121. * //output: "<div></div><span></span>"
  4122. * console.log( test2.innerHTML );
  4123. *
  4124. * </script>
  4125. * ```
  4126. */
  4127. /**
  4128. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  4129. * @method moveChild
  4130. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  4131. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  4132. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  4133. * @example
  4134. * ```html
  4135. * <div id="test1">
  4136. * <span></span>
  4137. * </div>
  4138. * <div id="test2">
  4139. * <div></div>
  4140. * </div>
  4141. *
  4142. * <script>
  4143. *
  4144. * var test1 = document.getElementById("test1"),
  4145. * test2 = document.getElementById("test2");
  4146. *
  4147. * UE.dom.domUtils.moveChild( test1, test2, true );
  4148. *
  4149. * //output: ""(空字符串)
  4150. * console.log( test1.innerHTML );
  4151. *
  4152. * //output: "<span></span><div></div>"
  4153. * console.log( test2.innerHTML );
  4154. *
  4155. * </script>
  4156. * ```
  4157. */
  4158. moveChild: function (src, tag, dir) {
  4159. while (src.firstChild) {
  4160. if (dir && tag.firstChild) {
  4161. tag.insertBefore(src.lastChild, tag.firstChild);
  4162. } else {
  4163. tag.appendChild(src.firstChild);
  4164. }
  4165. }
  4166. },
  4167. /**
  4168. * 判断节点的标签上是否不存在任何属性
  4169. * @method hasNoAttributes
  4170. * @private
  4171. * @param { Node } node 需要检测的节点对象
  4172. * @return { Boolean } 节点是否不包含任何属性
  4173. * @example
  4174. * ```html
  4175. * <div id="test"><span>xxxx</span></div>
  4176. *
  4177. * <script>
  4178. *
  4179. * //output: false
  4180. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  4181. *
  4182. * //output: true
  4183. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  4184. *
  4185. * </script>
  4186. * ```
  4187. */
  4188. hasNoAttributes: function (node) {
  4189. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  4190. },
  4191. /**
  4192. * 检测节点是否是UEditor所使用的辅助节点
  4193. * @method isCustomeNode
  4194. * @private
  4195. * @param { Node } node 需要检测的节点
  4196. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  4197. * @return { Boolean } 给定的节点是否是一个辅助节点
  4198. */
  4199. isCustomeNode: function (node) {
  4200. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  4201. },
  4202. /**
  4203. * 检测节点的标签是否是给定的标签
  4204. * @method isTagNode
  4205. * @param { Node } node 需要检测的节点对象
  4206. * @param { String } tagName 标签
  4207. * @return { Boolean } 节点的标签是否是给定的标签
  4208. * @example
  4209. * ```html
  4210. * <div id="test"></div>
  4211. *
  4212. * <script>
  4213. *
  4214. * //output: true
  4215. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  4216. *
  4217. * </script>
  4218. * ```
  4219. */
  4220. isTagNode: function (node, tagNames) {
  4221. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b', 'i').test(tagNames)
  4222. },
  4223. /**
  4224. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  4225. * @method filterNodeList
  4226. * @param { Array } nodeList 需要过滤的节点数组
  4227. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  4228. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  4229. * @example
  4230. * ```javascript
  4231. * var divNodes = document.getElementsByTagName("div");
  4232. * divNodes = [].slice.call( divNodes, 0 );
  4233. *
  4234. * //output: null
  4235. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4236. * return node.tagName.toLowerCase() !== 'div';
  4237. * } ) );
  4238. * ```
  4239. */
  4240. /**
  4241. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  4242. * @method filterNodeList
  4243. * @param { Array } nodeList 需要过滤的节点数组
  4244. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  4245. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  4246. * @example
  4247. * ```javascript
  4248. * var divNodes = document.getElementsByTagName("div");
  4249. * divNodes = [].slice.call( divNodes, 0 );
  4250. *
  4251. * //output: null
  4252. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  4253. * ```
  4254. */
  4255. /**
  4256. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  4257. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  4258. * @method filterNodeList
  4259. * @param { Array } nodeList 需要过滤的节点数组
  4260. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  4261. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  4262. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  4263. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  4264. * @example
  4265. * ```javascript
  4266. * var divNodes = document.getElementsByTagName("div");
  4267. * divNodes = [].slice.call( divNodes, 0 );
  4268. *
  4269. * //output: 3(假定有3个div)
  4270. * console.log( divNodes.length );
  4271. *
  4272. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4273. * return node.tagName.toLowerCase() === 'div';
  4274. * }, true );
  4275. *
  4276. * //output: 3
  4277. * console.log( nodes.length );
  4278. *
  4279. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4280. * return node.tagName.toLowerCase() === 'div';
  4281. * }, false );
  4282. *
  4283. * //output: div
  4284. * console.log( node.nodeName );
  4285. * ```
  4286. */
  4287. filterNodeList: function (nodelist, filter, forAll) {
  4288. var results = [];
  4289. if (!utils.isFunction(filter)) {
  4290. var str = filter;
  4291. filter = function (n) {
  4292. return utils.indexOf(utils.isArray(str) ? str : str.split(' '), n.tagName.toLowerCase()) != -1
  4293. };
  4294. }
  4295. utils.each(nodelist, function (n) {
  4296. filter(n) && results.push(n)
  4297. });
  4298. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4299. },
  4300. /**
  4301. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4302. * @method isInNodeEndBoundary
  4303. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4304. * @param node 需要检测的节点对象
  4305. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4306. */
  4307. isInNodeEndBoundary: function (rng, node) {
  4308. var start = rng.startContainer;
  4309. if (start.nodeType == 3 && rng.startOffset != start.nodeValue.length) {
  4310. return 0;
  4311. }
  4312. if (start.nodeType == 1 && rng.startOffset != start.childNodes.length) {
  4313. return 0;
  4314. }
  4315. while (start !== node) {
  4316. if (start.nextSibling) {
  4317. return 0
  4318. }
  4319. ;
  4320. start = start.parentNode;
  4321. }
  4322. return 1;
  4323. },
  4324. isBoundaryNode: function (node, dir) {
  4325. var tmp;
  4326. while (!domUtils.isBody(node)) {
  4327. tmp = node;
  4328. node = node.parentNode;
  4329. if (tmp !== node[dir]) {
  4330. return false;
  4331. }
  4332. }
  4333. return true;
  4334. },
  4335. fillHtml: browser.ie11below ? '&nbsp;' : '<br/>'
  4336. };
  4337. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4338. // core/Range.js
  4339. /**
  4340. * Range封装
  4341. * @file
  4342. * @module UE.dom
  4343. * @class Range
  4344. * @since 1.2.6.1
  4345. */
  4346. /**
  4347. * dom操作封装
  4348. * @unfile
  4349. * @module UE.dom
  4350. */
  4351. /**
  4352. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4353. * @unfile
  4354. * @module UE.dom
  4355. * @class Range
  4356. */
  4357. (function () {
  4358. var guid = 0,
  4359. fillChar = domUtils.fillChar,
  4360. fillData;
  4361. /**
  4362. * 更新range的collapse状态
  4363. * @param {Range} range range对象
  4364. */
  4365. function updateCollapse(range) {
  4366. range.collapsed =
  4367. range.startContainer && range.endContainer &&
  4368. range.startContainer === range.endContainer &&
  4369. range.startOffset == range.endOffset;
  4370. }
  4371. function selectOneNode(rng) {
  4372. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4373. }
  4374. function setEndPoint(toStart, node, offset, range) {
  4375. //如果node是自闭合标签要处理
  4376. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4377. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4378. node = node.parentNode;
  4379. }
  4380. if (toStart) {
  4381. range.startContainer = node;
  4382. range.startOffset = offset;
  4383. if (!range.endContainer) {
  4384. range.collapse(true);
  4385. }
  4386. } else {
  4387. range.endContainer = node;
  4388. range.endOffset = offset;
  4389. if (!range.startContainer) {
  4390. range.collapse(false);
  4391. }
  4392. }
  4393. updateCollapse(range);
  4394. return range;
  4395. }
  4396. function execContentsAction(range, action) {
  4397. //调整边界
  4398. //range.includeBookmark();
  4399. var start = range.startContainer,
  4400. end = range.endContainer,
  4401. startOffset = range.startOffset,
  4402. endOffset = range.endOffset,
  4403. doc = range.document,
  4404. frag = doc.createDocumentFragment(),
  4405. tmpStart, tmpEnd;
  4406. if (start.nodeType == 1) {
  4407. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4408. }
  4409. if (end.nodeType == 1) {
  4410. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4411. }
  4412. if (start === end && start.nodeType == 3) {
  4413. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4414. //is not clone
  4415. if (action) {
  4416. start.deleteData(startOffset, endOffset - startOffset);
  4417. range.collapse(true);
  4418. }
  4419. return frag;
  4420. }
  4421. var current, currentLevel, clone = frag,
  4422. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4423. for (var i = 0; startParents[i] == endParents[i];) {
  4424. i++;
  4425. }
  4426. for (var j = i, si; si = startParents[j]; j++) {
  4427. current = si.nextSibling;
  4428. if (si == start) {
  4429. if (!tmpStart) {
  4430. if (range.startContainer.nodeType == 3) {
  4431. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4432. //is not clone
  4433. if (action) {
  4434. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4435. }
  4436. } else {
  4437. clone.appendChild(!action ? start.cloneNode(true) : start);
  4438. }
  4439. }
  4440. } else {
  4441. currentLevel = si.cloneNode(false);
  4442. clone.appendChild(currentLevel);
  4443. }
  4444. while (current) {
  4445. if (current === end || current === endParents[j]) {
  4446. break;
  4447. }
  4448. si = current.nextSibling;
  4449. clone.appendChild(!action ? current.cloneNode(true) : current);
  4450. current = si;
  4451. }
  4452. clone = currentLevel;
  4453. }
  4454. clone = frag;
  4455. if (!startParents[i]) {
  4456. clone.appendChild(startParents[i - 1].cloneNode(false));
  4457. clone = clone.firstChild;
  4458. }
  4459. for (var j = i, ei; ei = endParents[j]; j++) {
  4460. current = ei.previousSibling;
  4461. if (ei == end) {
  4462. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4463. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4464. //is not clone
  4465. if (action) {
  4466. end.deleteData(0, endOffset);
  4467. }
  4468. }
  4469. } else {
  4470. currentLevel = ei.cloneNode(false);
  4471. clone.appendChild(currentLevel);
  4472. }
  4473. //如果两端同级,右边第一次已经被开始做了
  4474. if (j != i || !startParents[i]) {
  4475. while (current) {
  4476. if (current === start) {
  4477. break;
  4478. }
  4479. ei = current.previousSibling;
  4480. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4481. current = ei;
  4482. }
  4483. }
  4484. clone = currentLevel;
  4485. }
  4486. if (action) {
  4487. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4488. }
  4489. tmpStart && domUtils.remove(tmpStart);
  4490. tmpEnd && domUtils.remove(tmpEnd);
  4491. return frag;
  4492. }
  4493. /**
  4494. * 创建一个跟document绑定的空的Range实例
  4495. * @constructor
  4496. * @param { Document } document 新建的选区所属的文档对象
  4497. */
  4498. /**
  4499. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4500. */
  4501. /**
  4502. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4503. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4504. */
  4505. /**
  4506. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4507. */
  4508. /**
  4509. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4510. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4511. */
  4512. /**
  4513. * @property { Boolean } collapsed 当前Range是否闭合
  4514. * @default true
  4515. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4516. */
  4517. /**
  4518. * @property { Document } document 当前Range所属的Document对象
  4519. * @remind 不同range的的document属性可以是不同的
  4520. */
  4521. var Range = dom.Range = function (document) {
  4522. var me = this;
  4523. me.startContainer =
  4524. me.startOffset =
  4525. me.endContainer =
  4526. me.endOffset = null;
  4527. me.document = document;
  4528. me.collapsed = true;
  4529. };
  4530. /**
  4531. * 删除fillData
  4532. * @param doc
  4533. * @param excludeNode
  4534. */
  4535. function removeFillData(doc, excludeNode) {
  4536. try {
  4537. if (fillData && domUtils.inDoc(fillData, doc)) {
  4538. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4539. var tmpNode = fillData.parentNode;
  4540. domUtils.remove(fillData);
  4541. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4542. //safari的contains有bug
  4543. (browser.safari ? !(domUtils.getPosition(tmpNode, excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4544. ) {
  4545. fillData = tmpNode.parentNode;
  4546. domUtils.remove(tmpNode);
  4547. tmpNode = fillData;
  4548. }
  4549. } else {
  4550. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4551. }
  4552. }
  4553. } catch (e) {
  4554. }
  4555. }
  4556. /**
  4557. * @param node
  4558. * @param dir
  4559. */
  4560. function mergeSibling(node, dir) {
  4561. var tmpNode;
  4562. node = node[dir];
  4563. while (node && domUtils.isFillChar(node)) {
  4564. tmpNode = node[dir];
  4565. domUtils.remove(node);
  4566. node = tmpNode;
  4567. }
  4568. }
  4569. Range.prototype = {
  4570. /**
  4571. * 克隆选区的内容到一个DocumentFragment里
  4572. * @method cloneContents
  4573. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4574. * @example
  4575. * ```html
  4576. * <body>
  4577. * <!-- 中括号表示选区 -->
  4578. * <b>x<i>x[x</i>xx]x</b>
  4579. *
  4580. * <script>
  4581. * //range是已选中的选区
  4582. * var fragment = range.cloneContents(),
  4583. * node = document.createElement("div");
  4584. *
  4585. * node.appendChild( fragment );
  4586. *
  4587. * //output: <i>x</i>xx
  4588. * console.log( node.innerHTML );
  4589. *
  4590. * </script>
  4591. * </body>
  4592. * ```
  4593. */
  4594. cloneContents: function () {
  4595. return this.collapsed ? null : execContentsAction(this, 0);
  4596. },
  4597. /**
  4598. * 删除当前选区范围中的所有内容
  4599. * @method deleteContents
  4600. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4601. * @return { UE.dom.Range } 当前操作的Range对象
  4602. * @example
  4603. * ```html
  4604. * <body>
  4605. * <!-- 中括号表示选区 -->
  4606. * <b>x<i>x[x</i>xx]x</b>
  4607. *
  4608. * <script>
  4609. * //range是已选中的选区
  4610. * range.deleteContents();
  4611. *
  4612. * //竖线表示闭合后的选区位置
  4613. * //output: <b>x<i>x</i>|x</b>
  4614. * console.log( document.body.innerHTML );
  4615. *
  4616. * //此时, range的各项属性为
  4617. * //output: B
  4618. * console.log( range.startContainer.tagName );
  4619. * //output: 2
  4620. * console.log( range.startOffset );
  4621. * //output: B
  4622. * console.log( range.endContainer.tagName );
  4623. * //output: 2
  4624. * console.log( range.endOffset );
  4625. * //output: true
  4626. * console.log( range.collapsed );
  4627. *
  4628. * </script>
  4629. * </body>
  4630. * ```
  4631. */
  4632. deleteContents: function () {
  4633. var txt;
  4634. if (!this.collapsed) {
  4635. execContentsAction(this, 1);
  4636. }
  4637. if (browser.webkit) {
  4638. txt = this.startContainer;
  4639. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4640. this.setStartBefore(txt).collapse(true);
  4641. domUtils.remove(txt);
  4642. }
  4643. }
  4644. return this;
  4645. },
  4646. /**
  4647. * 将当前选区的内容提取到一个DocumentFragment里
  4648. * @method extractContents
  4649. * @remind 执行该操作后, 选区将变成闭合状态
  4650. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4651. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4652. * @example
  4653. * ```html
  4654. * <body>
  4655. * <!-- 中括号表示选区 -->
  4656. * <b>x<i>x[x</i>xx]x</b>
  4657. *
  4658. * <script>
  4659. * //range是已选中的选区
  4660. * var fragment = range.extractContents(),
  4661. * node = document.createElement( "div" );
  4662. *
  4663. * node.appendChild( fragment );
  4664. *
  4665. * //竖线表示闭合后的选区位置
  4666. *
  4667. * //output: <b>x<i>x</i>|x</b>
  4668. * console.log( document.body.innerHTML );
  4669. * //output: <i>x</i>xx
  4670. * console.log( node.innerHTML );
  4671. *
  4672. * //此时, range的各项属性为
  4673. * //output: B
  4674. * console.log( range.startContainer.tagName );
  4675. * //output: 2
  4676. * console.log( range.startOffset );
  4677. * //output: B
  4678. * console.log( range.endContainer.tagName );
  4679. * //output: 2
  4680. * console.log( range.endOffset );
  4681. * //output: true
  4682. * console.log( range.collapsed );
  4683. *
  4684. * </script>
  4685. * </body>
  4686. */
  4687. extractContents: function () {
  4688. return this.collapsed ? null : execContentsAction(this, 2);
  4689. },
  4690. /**
  4691. * 设置Range的开始容器节点和偏移量
  4692. * @method setStart
  4693. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4694. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4695. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4696. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4697. * 中的索引
  4698. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4699. * @param { int } offset 选区的开始位置偏移量
  4700. * @return { UE.dom.Range } 当前range对象
  4701. * @example
  4702. * ```html
  4703. * <!-- 选区 -->
  4704. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4705. *
  4706. * <script>
  4707. *
  4708. * //执行操作
  4709. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4710. *
  4711. * //此时, 选区变成了
  4712. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4713. *
  4714. * </script>
  4715. * ```
  4716. * @example
  4717. * ```html
  4718. * <!-- 选区 -->
  4719. * <b>xxx<img>[xx]x</b>
  4720. *
  4721. * <script>
  4722. *
  4723. * //执行操作
  4724. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4725. *
  4726. * //此时, 选区变成了
  4727. * //<b>xxx[<img>xx]x</b>
  4728. *
  4729. * </script>
  4730. * ```
  4731. */
  4732. setStart: function (node, offset) {
  4733. return setEndPoint(true, node, offset, this);
  4734. },
  4735. /**
  4736. * 设置Range的结束容器和偏移量
  4737. * @method setEnd
  4738. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4739. * @param { int } offset 结束边界的偏移量
  4740. * @see UE.dom.Range:setStart(Node,int)
  4741. * @return { UE.dom.Range } 当前range对象
  4742. */
  4743. setEnd: function (node, offset) {
  4744. return setEndPoint(false, node, offset, this);
  4745. },
  4746. /**
  4747. * 将Range开始位置设置到node节点之后
  4748. * @method setStartAfter
  4749. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4750. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4751. * @return { UE.dom.Range } 当前range对象
  4752. * @example
  4753. * ```html
  4754. * <!-- 选区示例 -->
  4755. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4756. *
  4757. * <script>
  4758. *
  4759. * //执行操作
  4760. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4761. *
  4762. * //结果选区
  4763. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4764. *
  4765. * </script>
  4766. * ```
  4767. */
  4768. setStartAfter: function (node) {
  4769. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4770. },
  4771. /**
  4772. * 将Range开始位置设置到node节点之前
  4773. * @method setStartBefore
  4774. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4775. * @param { Node } node 新的选区开始位置在该节点之前
  4776. * @see UE.dom.Range:setStartAfter(Node)
  4777. * @return { UE.dom.Range } 当前range对象
  4778. */
  4779. setStartBefore: function (node) {
  4780. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4781. },
  4782. /**
  4783. * 将Range结束位置设置到node节点之后
  4784. * @method setEndAfter
  4785. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4786. * @param { Node } node 目标节点
  4787. * @see UE.dom.Range:setStartAfter(Node)
  4788. * @return { UE.dom.Range } 当前range对象
  4789. * @example
  4790. * ```html
  4791. * <!-- 选区示例 -->
  4792. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4793. *
  4794. * <script>
  4795. *
  4796. * //执行操作
  4797. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4798. *
  4799. * //结果选区
  4800. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4801. *
  4802. * </script>
  4803. * ```
  4804. */
  4805. setEndAfter: function (node) {
  4806. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4807. },
  4808. /**
  4809. * 将Range结束位置设置到node节点之前
  4810. * @method setEndBefore
  4811. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4812. * @param { Node } node 目标节点
  4813. * @see UE.dom.Range:setEndAfter(Node)
  4814. * @return { UE.dom.Range } 当前range对象
  4815. */
  4816. setEndBefore: function (node) {
  4817. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4818. },
  4819. /**
  4820. * 设置Range的开始位置到node节点内的第一个子节点之前
  4821. * @method setStartAtFirst
  4822. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4823. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4824. * @param { Node } node 目标节点
  4825. * @see UE.dom.Range:setStartBefore(Node)
  4826. * @return { UE.dom.Range } 当前range对象
  4827. * @example
  4828. * ```html
  4829. * <!-- 选区示例 -->
  4830. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4831. *
  4832. * <script>
  4833. *
  4834. * //执行操作
  4835. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4836. *
  4837. * //结果选区
  4838. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4839. *
  4840. * </script>
  4841. * ```
  4842. */
  4843. setStartAtFirst: function (node) {
  4844. return this.setStart(node, 0);
  4845. },
  4846. /**
  4847. * 设置Range的开始位置到node节点内的最后一个节点之后
  4848. * @method setStartAtLast
  4849. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4850. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4851. * @param { Node } node 目标节点
  4852. * @see UE.dom.Range:setStartAtFirst(Node)
  4853. * @return { UE.dom.Range } 当前range对象
  4854. */
  4855. setStartAtLast: function (node) {
  4856. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4857. },
  4858. /**
  4859. * 设置Range的结束位置到node节点内的第一个节点之前
  4860. * @method setEndAtFirst
  4861. * @param { Node } node 目标节点
  4862. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4863. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4864. * @see UE.dom.Range:setStartAtFirst(Node)
  4865. * @return { UE.dom.Range } 当前range对象
  4866. */
  4867. setEndAtFirst: function (node) {
  4868. return this.setEnd(node, 0);
  4869. },
  4870. /**
  4871. * 设置Range的结束位置到node节点内的最后一个节点之后
  4872. * @method setEndAtLast
  4873. * @param { Node } node 目标节点
  4874. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4875. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4876. * @see UE.dom.Range:setStartAtFirst(Node)
  4877. * @return { UE.dom.Range } 当前range对象
  4878. */
  4879. setEndAtLast: function (node) {
  4880. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4881. },
  4882. /**
  4883. * 选中给定节点
  4884. * @method selectNode
  4885. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4886. * 而endOffset为startOffset+1
  4887. * @param { Node } node 需要选中的节点
  4888. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4889. * @example
  4890. * ```html
  4891. * <!-- 选区示例 -->
  4892. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4893. *
  4894. * <script>
  4895. *
  4896. * //执行操作
  4897. * range.selectNode( document.getElementsByTagName("i")[0] );
  4898. *
  4899. * //结果选区
  4900. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4901. *
  4902. * </script>
  4903. * ```
  4904. */
  4905. selectNode: function (node) {
  4906. return this.setStartBefore(node).setEndAfter(node);
  4907. },
  4908. /**
  4909. * 选中给定节点内部的所有节点
  4910. * @method selectNodeContents
  4911. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4912. * 而endOffset是该节点的子节点数。
  4913. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4914. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4915. * @example
  4916. * ```html
  4917. * <!-- 选区示例 -->
  4918. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4919. *
  4920. * <script>
  4921. *
  4922. * //执行操作
  4923. * range.selectNode( document.getElementsByTagName("b")[0] );
  4924. *
  4925. * //结果选区
  4926. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4927. *
  4928. * </script>
  4929. * ```
  4930. */
  4931. selectNodeContents: function (node) {
  4932. return this.setStart(node, 0).setEndAtLast(node);
  4933. },
  4934. /**
  4935. * clone当前Range对象
  4936. * @method cloneRange
  4937. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4938. * @return { UE.dom.Range } 当前range对象的一个副本
  4939. */
  4940. cloneRange: function () {
  4941. var me = this;
  4942. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4943. },
  4944. /**
  4945. * 向当前选区的结束处闭合选区
  4946. * @method collapse
  4947. * @return { UE.dom.Range } 当前range对象
  4948. * @example
  4949. * ```html
  4950. * <!-- 选区示例 -->
  4951. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4952. *
  4953. * <script>
  4954. *
  4955. * //执行操作
  4956. * range.collapse();
  4957. *
  4958. * //结果选区
  4959. * //“|”表示选区已闭合
  4960. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4961. *
  4962. * </script>
  4963. * ```
  4964. */
  4965. /**
  4966. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4967. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4968. * @method collapse
  4969. * @param { Boolean } toStart 是否向选区开始处闭合
  4970. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4971. * @see UE.dom.Range:collapse()
  4972. * @example
  4973. * ```html
  4974. * <!-- 选区示例 -->
  4975. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4976. *
  4977. * <script>
  4978. *
  4979. * //执行操作
  4980. * range.collapse( true );
  4981. *
  4982. * //结果选区
  4983. * //“|”表示选区已闭合
  4984. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4985. *
  4986. * </script>
  4987. * ```
  4988. */
  4989. collapse: function (toStart) {
  4990. var me = this;
  4991. if (toStart) {
  4992. me.endContainer = me.startContainer;
  4993. me.endOffset = me.startOffset;
  4994. } else {
  4995. me.startContainer = me.endContainer;
  4996. me.startOffset = me.endOffset;
  4997. }
  4998. me.collapsed = true;
  4999. return me;
  5000. },
  5001. /**
  5002. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  5003. * @method shrinkBoundary
  5004. * @return { UE.dom.Range } 当前range对象
  5005. * @example
  5006. * ```html
  5007. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  5008. * ```
  5009. *
  5010. * @example
  5011. * ```html
  5012. * <!-- 选区示例 -->
  5013. * <b>x[xx</b><i>]xxx</i>
  5014. *
  5015. * <script>
  5016. *
  5017. * //执行收缩
  5018. * range.shrinkBoundary();
  5019. *
  5020. * //结果选区
  5021. * //<b>x[xx]</b><i>xxx</i>
  5022. * </script>
  5023. * ```
  5024. *
  5025. * @example
  5026. * ```html
  5027. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  5028. * ```
  5029. */
  5030. /**
  5031. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  5032. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  5033. * @method shrinkBoundary
  5034. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  5035. * @return { UE.dom.Range } 当前range对象
  5036. * @see UE.dom.domUtils.Range:shrinkBoundary()
  5037. */
  5038. shrinkBoundary: function (ignoreEnd) {
  5039. var me = this, child,
  5040. collapsed = me.collapsed;
  5041. function check(node) {
  5042. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  5043. }
  5044. while (me.startContainer.nodeType == 1 //是element
  5045. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  5046. && check(child)) {
  5047. me.setStart(child, 0);
  5048. }
  5049. if (collapsed) {
  5050. return me.collapse(true);
  5051. }
  5052. if (!ignoreEnd) {
  5053. while (me.endContainer.nodeType == 1//是element
  5054. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  5055. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  5056. && check(child)) {
  5057. me.setEnd(child, child.childNodes.length);
  5058. }
  5059. }
  5060. return me;
  5061. },
  5062. /**
  5063. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  5064. * @method getCommonAncestor
  5065. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  5066. * @return { Node } 当前range对象内所有节点的公共祖先节点
  5067. * @example
  5068. * ```html
  5069. * //选区示例
  5070. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  5071. * <script>
  5072. *
  5073. * var node = range.getCommonAncestor();
  5074. *
  5075. * //公共祖先节点是: b节点
  5076. * //输出: B
  5077. * console.log(node.tagName);
  5078. *
  5079. * </script>
  5080. * ```
  5081. */
  5082. /**
  5083. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  5084. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  5085. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  5086. * @method getCommonAncestor
  5087. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  5088. * @return { Node } 当前range对象内所有节点的公共祖先节点
  5089. * @see UE.dom.Range:getCommonAncestor()
  5090. * @example
  5091. * ```html
  5092. * <body>
  5093. *
  5094. * <!-- 选区示例 -->
  5095. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  5096. *
  5097. * <script>
  5098. *
  5099. * var node = range.getCommonAncestor( false );
  5100. *
  5101. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  5102. * //output: B
  5103. * console.log( node.tagName );
  5104. *
  5105. * </script>
  5106. *
  5107. * </body>
  5108. * ```
  5109. */
  5110. /**
  5111. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  5112. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  5113. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  5114. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  5115. * @method getCommonAncestor
  5116. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  5117. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  5118. * @return { Node } 当前range对象内所有节点的公共祖先节点
  5119. * @see UE.dom.Range:getCommonAncestor()
  5120. * @see UE.dom.Range:getCommonAncestor(Boolean)
  5121. * @example
  5122. * ```html
  5123. * <body>
  5124. *
  5125. * <!-- 选区示例 -->
  5126. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  5127. *
  5128. * <script>
  5129. *
  5130. * var node = range.getCommonAncestor( true, false );
  5131. *
  5132. * //output: SPAN
  5133. * console.log( node.tagName );
  5134. *
  5135. * </script>
  5136. *
  5137. * </body>
  5138. * ```
  5139. */
  5140. getCommonAncestor: function (includeSelf, ignoreTextNode) {
  5141. var me = this,
  5142. start = me.startContainer,
  5143. end = me.endContainer;
  5144. if (start === end) {
  5145. if (includeSelf && selectOneNode(this)) {
  5146. start = start.childNodes[me.startOffset];
  5147. if (start.nodeType == 1)
  5148. return start;
  5149. }
  5150. //只有在上来就相等的情况下才会出现是文本的情况
  5151. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  5152. }
  5153. return domUtils.getCommonAncestor(start, end);
  5154. },
  5155. /**
  5156. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  5157. * @method trimBoundary
  5158. * @remind 该操作有可能会引起文本节点被切开
  5159. * @return { UE.dom.Range } 当前range对象
  5160. * @example
  5161. * ```html
  5162. *
  5163. * //选区示例
  5164. * <b>xxx<i>[xxxxx]</i>xxx</b>
  5165. *
  5166. * <script>
  5167. * //未调整前, 选区的开始容器和结束都是文本节点
  5168. * //执行调整
  5169. * range.trimBoundary();
  5170. *
  5171. * //调整之后, 容器节点变成了i节点
  5172. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  5173. * </script>
  5174. * ```
  5175. */
  5176. /**
  5177. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  5178. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  5179. * @method trimBoundary
  5180. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  5181. * @return { UE.dom.Range } 当前range对象
  5182. * @example
  5183. * ```html
  5184. *
  5185. * //选区示例
  5186. * <b>xxx<i>[xxxxx]</i>xxx</b>
  5187. *
  5188. * <script>
  5189. * //未调整前, 选区的开始容器和结束都是文本节点
  5190. * //执行调整
  5191. * range.trimBoundary( true );
  5192. *
  5193. * //调整之后, 开始容器节点变成了i节点
  5194. * //但是, 结束容器没有发生变化
  5195. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  5196. * </script>
  5197. * ```
  5198. */
  5199. trimBoundary: function (ignoreEnd) {
  5200. this.txtToElmBoundary();
  5201. var start = this.startContainer,
  5202. offset = this.startOffset,
  5203. collapsed = this.collapsed,
  5204. end = this.endContainer;
  5205. if (start.nodeType == 3) {
  5206. if (offset == 0) {
  5207. this.setStartBefore(start);
  5208. } else {
  5209. if (offset >= start.nodeValue.length) {
  5210. this.setStartAfter(start);
  5211. } else {
  5212. var textNode = domUtils.split(start, offset);
  5213. //跟新结束边界
  5214. if (start === end) {
  5215. this.setEnd(textNode, this.endOffset - offset);
  5216. } else if (start.parentNode === end) {
  5217. this.endOffset += 1;
  5218. }
  5219. this.setStartBefore(textNode);
  5220. }
  5221. }
  5222. if (collapsed) {
  5223. return this.collapse(true);
  5224. }
  5225. }
  5226. if (!ignoreEnd) {
  5227. offset = this.endOffset;
  5228. end = this.endContainer;
  5229. if (end.nodeType == 3) {
  5230. if (offset == 0) {
  5231. this.setEndBefore(end);
  5232. } else {
  5233. offset < end.nodeValue.length && domUtils.split(end, offset);
  5234. this.setEndAfter(end);
  5235. }
  5236. }
  5237. }
  5238. return this;
  5239. },
  5240. /**
  5241. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  5242. * @method txtToElmBoundary
  5243. * @remind 该操作不会修改dom节点
  5244. * @return { UE.dom.Range } 当前range对象
  5245. */
  5246. /**
  5247. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  5248. * ignoreCollapsed 的值决定是否执行该调整
  5249. * @method txtToElmBoundary
  5250. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  5251. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  5252. * @return { UE.dom.Range } 当前range对象
  5253. */
  5254. txtToElmBoundary: function (ignoreCollapsed) {
  5255. function adjust(r, c) {
  5256. var container = r[c + 'Container'],
  5257. offset = r[c + 'Offset'];
  5258. if (container.nodeType == 3) {
  5259. if (!offset) {
  5260. r['set' + c.replace(/(\w)/, function (a) {
  5261. return a.toUpperCase();
  5262. }) + 'Before'](container);
  5263. } else if (offset >= container.nodeValue.length) {
  5264. r['set' + c.replace(/(\w)/, function (a) {
  5265. return a.toUpperCase();
  5266. }) + 'After'](container);
  5267. }
  5268. }
  5269. }
  5270. if (ignoreCollapsed || !this.collapsed) {
  5271. adjust(this, 'start');
  5272. adjust(this, 'end');
  5273. }
  5274. return this;
  5275. },
  5276. /**
  5277. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5278. * @method insertNode
  5279. * @param { Node } node 需要插入的节点
  5280. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5281. * @return { UE.dom.Range } 当前range对象
  5282. */
  5283. insertNode: function (node) {
  5284. var first = node, length = 1;
  5285. if (node.nodeType == 11) {
  5286. first = node.firstChild;
  5287. length = node.childNodes.length;
  5288. }
  5289. this.trimBoundary(true);
  5290. var start = this.startContainer,
  5291. offset = this.startOffset;
  5292. var nextNode = start.childNodes[offset];
  5293. if (nextNode) {
  5294. start.insertBefore(node, nextNode);
  5295. } else {
  5296. start.appendChild(node);
  5297. }
  5298. if (first.parentNode === this.endContainer) {
  5299. this.endOffset = this.endOffset + length;
  5300. }
  5301. return this.setStartBefore(first);
  5302. },
  5303. /**
  5304. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5305. * @method setCursor
  5306. * @return { UE.dom.Range } 当前range对象
  5307. * @see UE.dom.Range:collapse()
  5308. */
  5309. /**
  5310. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5311. * @method setCursor
  5312. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5313. * 反之,则向开始容器方向闭合
  5314. * @return { UE.dom.Range } 当前range对象
  5315. * @see UE.dom.Range:collapse(Boolean)
  5316. */
  5317. setCursor: function (toEnd, noFillData) {
  5318. return this.collapse(!toEnd).select(noFillData);
  5319. },
  5320. /**
  5321. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5322. * @method createBookmark
  5323. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5324. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5325. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5326. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5327. * 返回的记录的类型为ID, 反之则为引用
  5328. */
  5329. createBookmark: function (serialize, same) {
  5330. var endNode,
  5331. startNode = this.document.createElement('span');
  5332. startNode.style.cssText = 'display:none;line-height:0px;';
  5333. startNode.appendChild(this.document.createTextNode('\u200D'));
  5334. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5335. if (!this.collapsed) {
  5336. endNode = startNode.cloneNode(true);
  5337. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5338. }
  5339. this.insertNode(startNode);
  5340. if (endNode) {
  5341. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5342. }
  5343. this.setStartAfter(startNode);
  5344. return {
  5345. start: serialize ? startNode.id : startNode,
  5346. end: endNode ? serialize ? endNode.id : endNode : null,
  5347. id: serialize
  5348. }
  5349. },
  5350. /**
  5351. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5352. * @method moveToBookmark
  5353. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5354. * @return { UE.dom.Range } 当前range对象
  5355. * @see UE.dom.Range:createBookmark(Boolean)
  5356. */
  5357. moveToBookmark: function (bookmark) {
  5358. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5359. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5360. this.setStartBefore(start);
  5361. domUtils.remove(start);
  5362. if (end) {
  5363. this.setEndBefore(end);
  5364. domUtils.remove(end);
  5365. } else {
  5366. this.collapse(true);
  5367. }
  5368. return this;
  5369. },
  5370. /**
  5371. * 调整range的边界,使其"放大"到最近的父节点
  5372. * @method enlarge
  5373. * @remind 会引起选区的变化
  5374. * @return { UE.dom.Range } 当前range对象
  5375. */
  5376. /**
  5377. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5378. * 要求扩大之后的父节点是block节点
  5379. * @method enlarge
  5380. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5381. * @return { UE.dom.Range } 当前range对象
  5382. */
  5383. enlarge: function (toBlock, stopFn) {
  5384. var isBody = domUtils.isBody,
  5385. pre, node, tmp = this.document.createTextNode('');
  5386. if (toBlock) {
  5387. node = this.startContainer;
  5388. if (node.nodeType == 1) {
  5389. if (node.childNodes[this.startOffset]) {
  5390. pre = node = node.childNodes[this.startOffset]
  5391. } else {
  5392. node.appendChild(tmp);
  5393. pre = node = tmp;
  5394. }
  5395. } else {
  5396. pre = node;
  5397. }
  5398. while (1) {
  5399. if (domUtils.isBlockElm(node)) {
  5400. node = pre;
  5401. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5402. node = pre;
  5403. }
  5404. this.setStartBefore(node);
  5405. break;
  5406. }
  5407. pre = node;
  5408. node = node.parentNode;
  5409. }
  5410. node = this.endContainer;
  5411. if (node.nodeType == 1) {
  5412. if (pre = node.childNodes[this.endOffset]) {
  5413. node.insertBefore(tmp, pre);
  5414. } else {
  5415. node.appendChild(tmp);
  5416. }
  5417. pre = node = tmp;
  5418. } else {
  5419. pre = node;
  5420. }
  5421. while (1) {
  5422. if (domUtils.isBlockElm(node)) {
  5423. node = pre;
  5424. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5425. node = pre;
  5426. }
  5427. this.setEndAfter(node);
  5428. break;
  5429. }
  5430. pre = node;
  5431. node = node.parentNode;
  5432. }
  5433. if (tmp.parentNode === this.endContainer) {
  5434. this.endOffset--;
  5435. }
  5436. domUtils.remove(tmp);
  5437. }
  5438. // 扩展边界到最大
  5439. if (!this.collapsed) {
  5440. while (this.startOffset == 0) {
  5441. if (stopFn && stopFn(this.startContainer)) {
  5442. break;
  5443. }
  5444. if (isBody(this.startContainer)) {
  5445. break;
  5446. }
  5447. this.setStartBefore(this.startContainer);
  5448. }
  5449. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5450. if (stopFn && stopFn(this.endContainer)) {
  5451. break;
  5452. }
  5453. if (isBody(this.endContainer)) {
  5454. break;
  5455. }
  5456. this.setEndAfter(this.endContainer);
  5457. }
  5458. }
  5459. return this;
  5460. },
  5461. enlargeToBlockElm: function (ignoreEnd) {
  5462. while (!domUtils.isBlockElm(this.startContainer)) {
  5463. this.setStartBefore(this.startContainer);
  5464. }
  5465. if (!ignoreEnd) {
  5466. while (!domUtils.isBlockElm(this.endContainer)) {
  5467. this.setEndAfter(this.endContainer);
  5468. }
  5469. }
  5470. return this;
  5471. },
  5472. /**
  5473. * 调整Range的边界,使其"缩小"到最合适的位置
  5474. * @method adjustmentBoundary
  5475. * @return { UE.dom.Range } 当前range对象
  5476. * @see UE.dom.Range:shrinkBoundary()
  5477. */
  5478. adjustmentBoundary: function () {
  5479. if (!this.collapsed) {
  5480. while (!domUtils.isBody(this.startContainer) &&
  5481. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5482. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5483. ) {
  5484. this.setStartAfter(this.startContainer);
  5485. }
  5486. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5487. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5488. ) {
  5489. this.setEndBefore(this.endContainer);
  5490. }
  5491. }
  5492. return this;
  5493. },
  5494. /**
  5495. * 给range选区中的内容添加给定的inline标签
  5496. * @method applyInlineStyle
  5497. * @param { String } tagName 需要添加的标签名
  5498. * @example
  5499. * ```html
  5500. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5501. * ```
  5502. */
  5503. /**
  5504. * 0603
  5505. * add:ueditor 添加样式辅助类
  5506. */
  5507. ueStyleUtils: {
  5508. applyChildStyle: function (elm, attrs) {
  5509. for (var i = 0; i < elm.children.length; i++) {
  5510. var node = elm.children[i];
  5511. var nodeStyle = node.style.cssText;
  5512. var newStyle = attrs.style;
  5513. if (newStyle) {
  5514. node.style.cssText = nodeStyle + newStyle;
  5515. }
  5516. this.applyChildStyle(node, attrs)
  5517. }
  5518. },
  5519. isAddFontWeight: function () {
  5520. },
  5521. isRemoveFontWeight: function (tagNames) {
  5522. return tagNames && ((tagNames.indexOf('strong') > -1) || (tagNames.indexOf('b') > -1))
  5523. },
  5524. hasFontWeightStyle: function (elm) {
  5525. var result = false;
  5526. if (elm && elm.style.cssText && elm.style.cssText.indexOf('font-weight') > -1) {
  5527. //本身有加粗效果
  5528. result = true;
  5529. } else if (elm && elm.children && elm.children.length > 0) {
  5530. //子节点有加粗效果
  5531. for (var i = 0; i < elm.children.length; i++) {
  5532. var node = elm.children[i];
  5533. var nodeStyle = node.style.cssText;
  5534. if (nodeStyle && nodeStyle.indexOf('font-weight') > -1) {
  5535. result = true;
  5536. break;
  5537. }
  5538. }
  5539. }
  5540. return result;
  5541. },
  5542. isParentHasFontWeightStyle: function (parent) {
  5543. var result = false;
  5544. if (parent && parent.tagName && parent.tagName.toLowerCase() != 'body') {
  5545. if (parent && parent.style.cssText && parent.style.cssText.indexOf('font-weight') > -1) {
  5546. result = true;
  5547. } else {
  5548. var parentNode = parent.parentNode;
  5549. result = this.isParentHasFontWeightStyle(parentNode);
  5550. }
  5551. }
  5552. return result;
  5553. },
  5554. removeChildFontWeight: function (elm) {
  5555. for (var i = 0; i < elm.children.length; i++) {
  5556. var node = elm.children[i];
  5557. var nodeStyle = node.style.cssText;
  5558. var newStyle = "font-weight: normal;";
  5559. node.style.cssText = (nodeStyle || '') + newStyle;
  5560. this.removeChildFontWeight(node)
  5561. }
  5562. },
  5563. },
  5564. /**
  5565. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5566. * @method applyInlineStyle
  5567. * @param { String } tagName 需要添加的标签名
  5568. * @param { Object } attrs 跟随新添加的标签的属性
  5569. * @return { UE.dom.Range } 当前选区
  5570. * @example
  5571. * ```html
  5572. * <p>xxxx[xxxx]x</p>
  5573. *
  5574. * ==>
  5575. *
  5576. * <!-- 执行操作 -->
  5577. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5578. *
  5579. * ==>
  5580. *
  5581. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5582. * ```
  5583. */
  5584. applyInlineStyle: function (tagName, attrs, list) {
  5585. if (this.collapsed) return this;
  5586. this.trimBoundary().enlarge(false,
  5587. function (node) {
  5588. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5589. }).adjustmentBoundary();
  5590. var bookmark = this.createBookmark(),
  5591. end = bookmark.end,
  5592. filterFn = function (node) {
  5593. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5594. },
  5595. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5596. node,
  5597. pre,
  5598. range = this.cloneRange();
  5599. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5600. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5601. range.setStartBefore(current);
  5602. node = current;
  5603. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5604. pre = node;
  5605. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5606. return dtd[tagName][parent.tagName];
  5607. });
  5608. }
  5609. var frag = range.setEndAfter(pre).extractContents(), elm;
  5610. if (list && list.length > 0) {
  5611. var level, top;
  5612. top = level = list[0].cloneNode(false);
  5613. for (var i = 1, ci; ci = list[i++];) {
  5614. level.appendChild(ci.cloneNode(false));
  5615. level = level.firstChild;
  5616. }
  5617. elm = level;
  5618. } else {
  5619. elm = range.document.createElement(tagName);
  5620. }
  5621. if (attrs) {
  5622. domUtils.setAttributes(elm, attrs);
  5623. }
  5624. elm.appendChild(frag);
  5625. range.insertNode(list ? top : elm);
  5626. /**
  5627. * 0603
  5628. * add:给所有子节点都加上改变后样式
  5629. */
  5630. //添加普通样式
  5631. if (attrs && elm.childElementCount > 0) {
  5632. this.ueStyleUtils.applyChildStyle(elm, attrs)
  5633. }
  5634. //添加加粗样式
  5635. if (!attrs && tagName && tagName == 'strong' && elm && elm.tagName.toLowerCase() == 'strong' && elm.children && elm.children.length > 0) {
  5636. this.ueStyleUtils.applyChildStyle(elm, {style: "font-weight: bold"});
  5637. }
  5638. /********************* */
  5639. //处理下滑线在a上的情况
  5640. var aNode;
  5641. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5642. domUtils.setAttributes(aNode, attrs);
  5643. domUtils.remove(elm, true);
  5644. elm = aNode;
  5645. } else {
  5646. domUtils.mergeSibling(elm);
  5647. domUtils.clearEmptySibling(elm);
  5648. }
  5649. //去除子节点相同的
  5650. domUtils.mergeChild(elm, attrs);
  5651. current = domUtils.getNextDomNode(elm, false, filterFn);
  5652. domUtils.mergeToParent(elm);
  5653. if (node === end) {
  5654. break;
  5655. }
  5656. } else {
  5657. current = domUtils.getNextDomNode(current, true, filterFn);
  5658. }
  5659. }
  5660. return this.moveToBookmark(bookmark);
  5661. },
  5662. /**
  5663. * 移除当前选区内指定的inline标签,但保留其中的内容
  5664. * @method removeInlineStyle
  5665. * @param { String } tagName 需要移除的标签名
  5666. * @return { UE.dom.Range } 当前的range对象
  5667. * @example
  5668. * ```html
  5669. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5670. * ```
  5671. */
  5672. /**
  5673. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5674. * @method removeInlineStyle
  5675. * @param { Array } tagNameArr 需要移除的标签名的数组
  5676. * @return { UE.dom.Range } 当前的range对象
  5677. * @see UE.dom.Range:removeInlineStyle(String)
  5678. */
  5679. removeInlineStyle: function (tagNames) {
  5680. if (this.collapsed) return this;
  5681. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5682. this.shrinkBoundary().adjustmentBoundary();
  5683. var start = this.startContainer, end = this.endContainer;
  5684. while (1) {
  5685. if (start.nodeType == 1) {
  5686. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5687. break;
  5688. }
  5689. if (start.tagName.toLowerCase() == 'body') {
  5690. start = null;
  5691. break;
  5692. }
  5693. }
  5694. start = start.parentNode;
  5695. }
  5696. while (1) {
  5697. if (end.nodeType == 1) {
  5698. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5699. break;
  5700. }
  5701. if (end.tagName.toLowerCase() == 'body') {
  5702. end = null;
  5703. break;
  5704. }
  5705. }
  5706. end = end.parentNode;
  5707. }
  5708. var bookmark = this.createBookmark(),
  5709. frag,
  5710. tmpRange;
  5711. if (start) {
  5712. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5713. frag = tmpRange.extractContents();
  5714. tmpRange.insertNode(frag);
  5715. domUtils.clearEmptySibling(start, true);
  5716. start.parentNode.insertBefore(bookmark.start, start);
  5717. }
  5718. if (end) {
  5719. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5720. frag = tmpRange.extractContents();
  5721. tmpRange.insertNode(frag);
  5722. domUtils.clearEmptySibling(end, false, true);
  5723. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5724. }
  5725. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5726. return node.nodeType == 1;
  5727. }), next;
  5728. while (current && current !== bookmark.end) {
  5729. next = domUtils.getNextDomNode(current, true, function (node) {
  5730. return node.nodeType == 1;
  5731. });
  5732. // if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5733. // domUtils.remove(current, true);
  5734. // }
  5735. /**
  5736. * 0603
  5737. * add:移除加粗时,要把字节点里的style里的font-weight一起移除掉
  5738. */
  5739. //如果是strong标签,去掉本身加粗样式及子节点的font-weight
  5740. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5741. if (this.ueStyleUtils.isRemoveFontWeight(tagNames)) {
  5742. this.ueStyleUtils.removeChildFontWeight(current)
  5743. }
  5744. domUtils.remove(current, true, this);
  5745. }
  5746. //非strong 标签,移除本身及子节点的font-weight
  5747. if (this.ueStyleUtils.isRemoveFontWeight(tagNames) && this.ueStyleUtils.hasFontWeightStyle(current)) {
  5748. this.ueStyleUtils.removeChildFontWeight(current)
  5749. }
  5750. /***************************** */
  5751. current = next;
  5752. }
  5753. return this.moveToBookmark(bookmark);
  5754. },
  5755. /**
  5756. * 获取当前选中的自闭合的节点
  5757. * @method getClosedNode
  5758. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5759. */
  5760. getClosedNode: function () {
  5761. var node;
  5762. if (!this.collapsed) {
  5763. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5764. if (selectOneNode(range)) {
  5765. var child = range.startContainer.childNodes[range.startOffset];
  5766. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5767. node = child;
  5768. }
  5769. }
  5770. }
  5771. return node;
  5772. },
  5773. /**
  5774. * 在页面上高亮range所表示的选区
  5775. * @method select
  5776. * @return { UE.dom.Range } 返回当前Range对象
  5777. */
  5778. //这里不区分ie9以上,trace:3824
  5779. select: browser.ie ? function (noFillData, textRange) {
  5780. var nativeRange;
  5781. if (!this.collapsed)
  5782. this.shrinkBoundary();
  5783. var node = this.getClosedNode();
  5784. if (node && !textRange) {
  5785. try {
  5786. nativeRange = this.document.body.createControlRange();
  5787. nativeRange.addElement(node);
  5788. nativeRange.select();
  5789. } catch (e) {
  5790. }
  5791. return this;
  5792. }
  5793. var bookmark = this.createBookmark(),
  5794. start = bookmark.start,
  5795. end;
  5796. nativeRange = this.document.body.createTextRange();
  5797. nativeRange.moveToElementText(start);
  5798. nativeRange.moveStart('character', 1);
  5799. if (!this.collapsed) {
  5800. var nativeRangeEnd = this.document.body.createTextRange();
  5801. end = bookmark.end;
  5802. nativeRangeEnd.moveToElementText(end);
  5803. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5804. } else {
  5805. if (!noFillData && this.startContainer.nodeType != 3) {
  5806. //使用<span>|x<span>固定住光标
  5807. var tmpText = this.document.createTextNode(fillChar),
  5808. tmp = this.document.createElement('span');
  5809. tmp.appendChild(this.document.createTextNode(fillChar));
  5810. start.parentNode.insertBefore(tmp, start);
  5811. start.parentNode.insertBefore(tmpText, start);
  5812. //当点b,i,u时,不能清除i上边的b
  5813. removeFillData(this.document, tmpText);
  5814. fillData = tmpText;
  5815. mergeSibling(tmp, 'previousSibling');
  5816. mergeSibling(start, 'nextSibling');
  5817. nativeRange.moveStart('character', -1);
  5818. nativeRange.collapse(true);
  5819. }
  5820. }
  5821. this.moveToBookmark(bookmark);
  5822. tmp && domUtils.remove(tmp);
  5823. //IE在隐藏状态下不支持range操作,catch一下
  5824. try {
  5825. nativeRange.select();
  5826. } catch (e) {
  5827. }
  5828. return this;
  5829. } : function (notInsertFillData) {
  5830. function checkOffset(rng) {
  5831. function check(node, offset, dir) {
  5832. if (node.nodeType == 3 && node.nodeValue.length < offset) {
  5833. rng[dir + 'Offset'] = node.nodeValue.length
  5834. }
  5835. }
  5836. check(rng.startContainer, rng.startOffset, 'start');
  5837. check(rng.endContainer, rng.endOffset, 'end');
  5838. }
  5839. var win = domUtils.getWindow(this.document),
  5840. sel = win.getSelection(),
  5841. txtNode;
  5842. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5843. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5844. browser.gecko ? this.document.body.focus() : win.focus();
  5845. if (sel) {
  5846. sel.removeAllRanges();
  5847. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5848. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5849. if (this.collapsed && !notInsertFillData) {
  5850. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5851. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5852. // var tmp = this.document.createTextNode('');
  5853. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5854. // }
  5855. //
  5856. //处理光标落在文本节点的情况
  5857. //处理以下的情况
  5858. //<b>|xxxx</b>
  5859. //<b>xxxx</b>|xxxx
  5860. //xxxx<b>|</b>
  5861. var start = this.startContainer, child = start;
  5862. if (start.nodeType == 1) {
  5863. child = start.childNodes[this.startOffset];
  5864. }
  5865. if (!(start.nodeType == 3 && this.startOffset) &&
  5866. (child ?
  5867. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5868. :
  5869. (!start.lastChild || start.lastChild.nodeType != 3)
  5870. )
  5871. ) {
  5872. txtNode = this.document.createTextNode(fillChar);
  5873. //跟着前边走
  5874. this.insertNode(txtNode);
  5875. removeFillData(this.document, txtNode);
  5876. mergeSibling(txtNode, 'previousSibling');
  5877. mergeSibling(txtNode, 'nextSibling');
  5878. fillData = txtNode;
  5879. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5880. }
  5881. }
  5882. var nativeRange = this.document.createRange();
  5883. if (this.collapsed && browser.opera && this.startContainer.nodeType == 1) {
  5884. var child = this.startContainer.childNodes[this.startOffset];
  5885. if (!child) {
  5886. //往前靠拢
  5887. child = this.startContainer.lastChild;
  5888. if (child && domUtils.isBr(child)) {
  5889. this.setStartBefore(child).collapse(true);
  5890. }
  5891. } else {
  5892. //向后靠拢
  5893. while (child && domUtils.isBlockElm(child)) {
  5894. if (child.nodeType == 1 && child.childNodes[0]) {
  5895. child = child.childNodes[0]
  5896. } else {
  5897. break;
  5898. }
  5899. }
  5900. child && this.setStartBefore(child).collapse(true)
  5901. }
  5902. }
  5903. //是createAddress最后一位算的不准,现在这里进行微调
  5904. checkOffset(this);
  5905. nativeRange.setStart(this.startContainer, this.startOffset);
  5906. nativeRange.setEnd(this.endContainer, this.endOffset);
  5907. sel.addRange(nativeRange);
  5908. }
  5909. return this;
  5910. },
  5911. /**
  5912. * 滚动到当前range开始的位置
  5913. * @method scrollToView
  5914. * @param { Window } win 当前range对象所属的window对象
  5915. * @return { UE.dom.Range } 当前Range对象
  5916. */
  5917. /**
  5918. * 滚动到距离当前range开始位置 offset 的位置处
  5919. * @method scrollToView
  5920. * @param { Window } win 当前range对象所属的window对象
  5921. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5922. * @return { UE.dom.Range } 当前Range对象
  5923. */
  5924. scrollToView: function (win, offset) {
  5925. win = win ? window : domUtils.getWindow(this.document);
  5926. var me = this,
  5927. span = me.document.createElement('span');
  5928. //trace:717
  5929. span.innerHTML = '&nbsp;';
  5930. me.cloneRange().insertNode(span);
  5931. domUtils.scrollToView(span, win, offset);
  5932. domUtils.remove(span);
  5933. return me;
  5934. },
  5935. /**
  5936. * 判断当前选区内容是否占位符
  5937. * @private
  5938. * @method inFillChar
  5939. * @return { Boolean } 如果是占位符返回true,否则返回false
  5940. */
  5941. inFillChar: function () {
  5942. var start = this.startContainer;
  5943. if (this.collapsed && start.nodeType == 3
  5944. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar), '').length + 1 == start.nodeValue.length
  5945. ) {
  5946. return true;
  5947. }
  5948. return false;
  5949. },
  5950. /**
  5951. * 保存
  5952. * @method createAddress
  5953. * @private
  5954. * @return { Boolean } 返回开始和结束的位置
  5955. * @example
  5956. * ```html
  5957. * <body>
  5958. * <p>
  5959. * aaaa
  5960. * <em>
  5961. * <!-- 选区开始 -->
  5962. * bbbb
  5963. * <!-- 选区结束 -->
  5964. * </em>
  5965. * </p>
  5966. *
  5967. * <script>
  5968. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5969. * console.log( range.createAddress() );
  5970. * </script>
  5971. * </body>
  5972. * ```
  5973. */
  5974. createAddress: function (ignoreEnd, ignoreTxt) {
  5975. var addr = {}, me = this;
  5976. function getAddress(isStart) {
  5977. var node = isStart ? me.startContainer : me.endContainer;
  5978. var parents = domUtils.findParents(node, true, function (node) {
  5979. return !domUtils.isBody(node)
  5980. }),
  5981. addrs = [];
  5982. for (var i = 0, ci; ci = parents[i++];) {
  5983. addrs.push(domUtils.getNodeIndex(ci, ignoreTxt));
  5984. }
  5985. var firstIndex = 0;
  5986. if (ignoreTxt) {
  5987. if (node.nodeType == 3) {
  5988. var tmpNode = node.previousSibling;
  5989. while (tmpNode && tmpNode.nodeType == 3) {
  5990. firstIndex += tmpNode.nodeValue.replace(fillCharReg, '').length;
  5991. tmpNode = tmpNode.previousSibling;
  5992. }
  5993. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5994. } else {
  5995. node = node.childNodes[isStart ? me.startOffset : me.endOffset];
  5996. if (node) {
  5997. firstIndex = domUtils.getNodeIndex(node, ignoreTxt);
  5998. } else {
  5999. node = isStart ? me.startContainer : me.endContainer;
  6000. var first = node.firstChild;
  6001. while (first) {
  6002. if (domUtils.isFillChar(first)) {
  6003. first = first.nextSibling;
  6004. continue;
  6005. }
  6006. firstIndex++;
  6007. if (first.nodeType == 3) {
  6008. while (first && first.nodeType == 3) {
  6009. first = first.nextSibling;
  6010. }
  6011. } else {
  6012. first = first.nextSibling;
  6013. }
  6014. }
  6015. }
  6016. }
  6017. } else {
  6018. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  6019. }
  6020. if (firstIndex < 0) {
  6021. firstIndex = 0;
  6022. }
  6023. addrs.push(firstIndex);
  6024. return addrs;
  6025. }
  6026. addr.startAddress = getAddress(true);
  6027. if (!ignoreEnd) {
  6028. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  6029. }
  6030. return addr;
  6031. },
  6032. /**
  6033. * 保存
  6034. * @method createAddress
  6035. * @private
  6036. * @return { Boolean } 返回开始和结束的位置
  6037. * @example
  6038. * ```html
  6039. * <body>
  6040. * <p>
  6041. * aaaa
  6042. * <em>
  6043. * <!-- 选区开始 -->
  6044. * bbbb
  6045. * <!-- 选区结束 -->
  6046. * </em>
  6047. * </p>
  6048. *
  6049. * <script>
  6050. * var range = editor.selection.getRange();
  6051. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  6052. * range.select();
  6053. * //output: 'bbbb'
  6054. * console.log(editor.selection.getText());
  6055. * </script>
  6056. * </body>
  6057. * ```
  6058. */
  6059. moveToAddress: function (addr, ignoreEnd) {
  6060. var me = this;
  6061. function getNode(address, isStart) {
  6062. var tmpNode = me.document.body,
  6063. parentNode, offset;
  6064. for (var i = 0, ci, l = address.length; i < l; i++) {
  6065. ci = address[i];
  6066. parentNode = tmpNode;
  6067. tmpNode = tmpNode.childNodes[ci];
  6068. if (!tmpNode) {
  6069. offset = ci;
  6070. break;
  6071. }
  6072. }
  6073. if (isStart) {
  6074. if (tmpNode) {
  6075. me.setStartBefore(tmpNode)
  6076. } else {
  6077. me.setStart(parentNode, offset)
  6078. }
  6079. } else {
  6080. if (tmpNode) {
  6081. me.setEndBefore(tmpNode)
  6082. } else {
  6083. me.setEnd(parentNode, offset)
  6084. }
  6085. }
  6086. }
  6087. getNode(addr.startAddress, true);
  6088. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  6089. return me;
  6090. },
  6091. /**
  6092. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  6093. * @method equals
  6094. * @param { UE.dom.Range } 需要判断的Range对象
  6095. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  6096. */
  6097. equals: function (rng) {
  6098. for (var p in this) {
  6099. if (this.hasOwnProperty(p)) {
  6100. if (this[p] !== rng[p])
  6101. return false
  6102. }
  6103. }
  6104. return true;
  6105. },
  6106. /**
  6107. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  6108. * 作为其参数。
  6109. * @method traversal
  6110. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  6111. * @return { UE.dom.Range } 当前range对象
  6112. * @example
  6113. * ```html
  6114. *
  6115. * <body>
  6116. *
  6117. * <!-- 选区开始 -->
  6118. * <span></span>
  6119. * <a></a>
  6120. * <!-- 选区结束 -->
  6121. * </body>
  6122. *
  6123. * <script>
  6124. *
  6125. * //output: <span></span><a></a>
  6126. * console.log( range.cloneContents() );
  6127. *
  6128. * range.traversal( function ( node ) {
  6129. *
  6130. * if ( node.nodeType === 1 ) {
  6131. * node.className = "test";
  6132. * }
  6133. *
  6134. * } );
  6135. *
  6136. * //output: <span class="test"></span><a class="test"></a>
  6137. * console.log( range.cloneContents() );
  6138. *
  6139. * </script>
  6140. * ```
  6141. */
  6142. /**
  6143. * 遍历range内的节点。
  6144. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  6145. * 作为其参数。
  6146. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  6147. * 发doFn函数的执行
  6148. * @method traversal
  6149. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  6150. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  6151. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  6152. * 会触发doFn。
  6153. * @return { UE.dom.Range } 当前range对象
  6154. * @see UE.dom.Range:traversal(Function)
  6155. * @example
  6156. * ```html
  6157. *
  6158. * <body>
  6159. *
  6160. * <!-- 选区开始 -->
  6161. * <span></span>
  6162. * <a></a>
  6163. * <!-- 选区结束 -->
  6164. * </body>
  6165. *
  6166. * <script>
  6167. *
  6168. * //output: <span></span><a></a>
  6169. * console.log( range.cloneContents() );
  6170. *
  6171. * range.traversal( function ( node ) {
  6172. *
  6173. * node.className = "test";
  6174. *
  6175. * }, function ( node ) {
  6176. * return node.nodeType === 1;
  6177. * } );
  6178. *
  6179. * //output: <span class="test"></span><a class="test"></a>
  6180. * console.log( range.cloneContents() );
  6181. *
  6182. * </script>
  6183. * ```
  6184. */
  6185. traversal: function (doFn, filterFn) {
  6186. if (this.collapsed)
  6187. return this;
  6188. var bookmark = this.createBookmark(),
  6189. end = bookmark.end,
  6190. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  6191. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  6192. var tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  6193. doFn(current);
  6194. current = tmpNode;
  6195. }
  6196. return this.moveToBookmark(bookmark);
  6197. }
  6198. };
  6199. })();
  6200. // core/Selection.js
  6201. /**
  6202. * 选集
  6203. * @file
  6204. * @module UE.dom
  6205. * @class Selection
  6206. * @since 1.2.6.1
  6207. */
  6208. /**
  6209. * 选区集合
  6210. * @unfile
  6211. * @module UE.dom
  6212. * @class Selection
  6213. */
  6214. (function () {
  6215. function getBoundaryInformation(range, start) {
  6216. var getIndex = domUtils.getNodeIndex;
  6217. range = range.duplicate();
  6218. range.collapse(start);
  6219. var parent = range.parentElement();
  6220. //如果节点里没有子节点,直接退出
  6221. if (!parent.hasChildNodes()) {
  6222. return {container: parent, offset: 0};
  6223. }
  6224. var siblings = parent.children,
  6225. child,
  6226. testRange = range.duplicate(),
  6227. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  6228. distance;
  6229. while (startIndex <= endIndex) {
  6230. index = Math.floor((startIndex + endIndex) / 2);
  6231. child = siblings[index];
  6232. testRange.moveToElementText(child);
  6233. var position = testRange.compareEndPoints('StartToStart', range);
  6234. if (position > 0) {
  6235. endIndex = index - 1;
  6236. } else if (position < 0) {
  6237. startIndex = index + 1;
  6238. } else {
  6239. //trace:1043
  6240. return {container: parent, offset: getIndex(child)};
  6241. }
  6242. }
  6243. if (index == -1) {
  6244. testRange.moveToElementText(parent);
  6245. testRange.setEndPoint('StartToStart', range);
  6246. distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length;
  6247. siblings = parent.childNodes;
  6248. if (!distance) {
  6249. child = siblings[siblings.length - 1];
  6250. return {container: child, offset: child.nodeValue.length};
  6251. }
  6252. var i = siblings.length;
  6253. while (distance > 0) {
  6254. distance -= siblings[--i].nodeValue.length;
  6255. }
  6256. return {container: siblings[i], offset: -distance};
  6257. }
  6258. testRange.collapse(position > 0);
  6259. testRange.setEndPoint(position > 0 ? 'StartToStart' : 'EndToStart', range);
  6260. distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length;
  6261. if (!distance) {
  6262. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  6263. {container: parent, offset: getIndex(child) + (position > 0 ? 0 : 1)} :
  6264. {container: child, offset: position > 0 ? 0 : child.childNodes.length}
  6265. }
  6266. while (distance > 0) {
  6267. try {
  6268. var pre = child;
  6269. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  6270. distance -= child.nodeValue.length;
  6271. } catch (e) {
  6272. return {container: parent, offset: getIndex(pre)};
  6273. }
  6274. }
  6275. return {container: child, offset: position > 0 ? -distance : child.nodeValue.length + distance}
  6276. }
  6277. /**
  6278. * 将ieRange转换为Range对象
  6279. * @param {Range} ieRange ieRange对象
  6280. * @param {Range} range Range对象
  6281. * @return {Range} range 返回转换后的Range对象
  6282. */
  6283. function transformIERangeToRange(ieRange, range) {
  6284. if (ieRange.item) {
  6285. range.selectNode(ieRange.item(0));
  6286. } else {
  6287. var bi = getBoundaryInformation(ieRange, true);
  6288. range.setStart(bi.container, bi.offset);
  6289. if (ieRange.compareEndPoints('StartToEnd', ieRange) != 0) {
  6290. bi = getBoundaryInformation(ieRange, false);
  6291. range.setEnd(bi.container, bi.offset);
  6292. }
  6293. }
  6294. return range;
  6295. }
  6296. /**
  6297. * 获得ieRange
  6298. * @param {Selection} sel Selection对象
  6299. * @return {ieRange} 得到ieRange
  6300. */
  6301. function _getIERange(sel) {
  6302. var ieRange;
  6303. //ie下有可能报错
  6304. try {
  6305. ieRange = sel.getNative().createRange();
  6306. } catch (e) {
  6307. return null;
  6308. }
  6309. var el = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
  6310. if ((el.ownerDocument || el) === sel.document) {
  6311. return ieRange;
  6312. }
  6313. return null;
  6314. }
  6315. var Selection = dom.Selection = function (doc) {
  6316. var me = this, iframe;
  6317. me.document = doc;
  6318. if (browser.ie9below) {
  6319. iframe = domUtils.getWindow(doc).frameElement;
  6320. domUtils.on(iframe, 'beforedeactivate', function () {
  6321. me._bakIERange = me.getIERange();
  6322. });
  6323. domUtils.on(iframe, 'activate', function () {
  6324. try {
  6325. if (!_getIERange(me) && me._bakIERange) {
  6326. me._bakIERange.select();
  6327. }
  6328. } catch (ex) {
  6329. }
  6330. me._bakIERange = null;
  6331. });
  6332. }
  6333. iframe = doc = null;
  6334. };
  6335. Selection.prototype = {
  6336. rangeInBody: function (rng, txtRange) {
  6337. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  6338. return node === this.document.body || domUtils.inDoc(node, this.document);
  6339. },
  6340. /**
  6341. * 获取原生seleciton对象
  6342. * @method getNative
  6343. * @return { Object } 获得selection对象
  6344. * @example
  6345. * ```javascript
  6346. * editor.selection.getNative();
  6347. * ```
  6348. */
  6349. getNative: function () {
  6350. var doc = this.document;
  6351. try {
  6352. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow(doc).getSelection();
  6353. } catch (e) {
  6354. return null;
  6355. }
  6356. },
  6357. /**
  6358. * 获得ieRange
  6359. * @method getIERange
  6360. * @return { Object } 返回ie原生的Range
  6361. * @example
  6362. * ```javascript
  6363. * editor.selection.getIERange();
  6364. * ```
  6365. */
  6366. getIERange: function () {
  6367. var ieRange = _getIERange(this);
  6368. if (!ieRange) {
  6369. if (this._bakIERange) {
  6370. return this._bakIERange;
  6371. }
  6372. }
  6373. return ieRange;
  6374. },
  6375. /**
  6376. * 缓存当前选区的range和选区的开始节点
  6377. * @method cache
  6378. */
  6379. cache: function () {
  6380. this.clear();
  6381. this._cachedRange = this.getRange();
  6382. this._cachedStartElement = this.getStart();
  6383. this._cachedStartElementPath = this.getStartElementPath();
  6384. },
  6385. /**
  6386. * 获取选区开始位置的父节点到body
  6387. * @method getStartElementPath
  6388. * @return { Array } 返回父节点集合
  6389. * @example
  6390. * ```javascript
  6391. * editor.selection.getStartElementPath();
  6392. * ```
  6393. */
  6394. getStartElementPath: function () {
  6395. if (this._cachedStartElementPath) {
  6396. return this._cachedStartElementPath;
  6397. }
  6398. var start = this.getStart();
  6399. if (start) {
  6400. return domUtils.findParents(start, true, null, true)
  6401. }
  6402. return [];
  6403. },
  6404. /**
  6405. * 清空缓存
  6406. * @method clear
  6407. */
  6408. clear: function () {
  6409. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6410. },
  6411. /**
  6412. * 编辑器是否得到了选区
  6413. * @method isFocus
  6414. */
  6415. isFocus: function () {
  6416. try {
  6417. if (browser.ie9below) {
  6418. var nativeRange = _getIERange(this);
  6419. return !!(nativeRange && this.rangeInBody(nativeRange));
  6420. } else {
  6421. return !!this.getNative().rangeCount;
  6422. }
  6423. } catch (e) {
  6424. return false;
  6425. }
  6426. },
  6427. /**
  6428. * 获取选区对应的Range
  6429. * @method getRange
  6430. * @return { Object } 得到Range对象
  6431. * @example
  6432. * ```javascript
  6433. * editor.selection.getRange();
  6434. * ```
  6435. */
  6436. getRange: function () {
  6437. var me = this;
  6438. function optimze(range) {
  6439. var child = me.document.body.firstChild,
  6440. collapsed = range.collapsed;
  6441. while (child && child.firstChild) {
  6442. range.setStart(child, 0);
  6443. child = child.firstChild;
  6444. }
  6445. if (!range.startContainer) {
  6446. range.setStart(me.document.body, 0)
  6447. }
  6448. if (collapsed) {
  6449. range.collapse(true);
  6450. }
  6451. }
  6452. if (me._cachedRange != null) {
  6453. return this._cachedRange;
  6454. }
  6455. var range = new baidu.editor.dom.Range(me.document);
  6456. if (browser.ie9below) {
  6457. var nativeRange = me.getIERange();
  6458. if (nativeRange) {
  6459. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6460. try {
  6461. transformIERangeToRange(nativeRange, range);
  6462. } catch (e) {
  6463. optimze(range);
  6464. }
  6465. } else {
  6466. optimze(range);
  6467. }
  6468. } else {
  6469. var sel = me.getNative();
  6470. if (sel && sel.rangeCount) {
  6471. var firstRange = sel.getRangeAt(0);
  6472. var lastRange = sel.getRangeAt(sel.rangeCount - 1);
  6473. range.setStart(firstRange.startContainer, firstRange.startOffset).setEnd(lastRange.endContainer, lastRange.endOffset);
  6474. if (range.collapsed && domUtils.isBody(range.startContainer) && !range.startOffset) {
  6475. optimze(range);
  6476. }
  6477. } else {
  6478. //trace:1734 有可能已经不在dom树上了,标识的节点
  6479. if (this._bakRange && domUtils.inDoc(this._bakRange.startContainer, this.document)) {
  6480. return this._bakRange;
  6481. }
  6482. optimze(range);
  6483. }
  6484. }
  6485. return this._bakRange = range;
  6486. },
  6487. /**
  6488. * 获取开始元素,用于状态反射
  6489. * @method getStart
  6490. * @return { Element } 获得开始元素
  6491. * @example
  6492. * ```javascript
  6493. * editor.selection.getStart();
  6494. * ```
  6495. */
  6496. getStart: function () {
  6497. if (this._cachedStartElement) {
  6498. return this._cachedStartElement;
  6499. }
  6500. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6501. tmpRange,
  6502. start, tmp, parent;
  6503. if (browser.ie9below) {
  6504. if (!range) {
  6505. //todo 给第一个值可能会有问题
  6506. return this.document.body.firstChild;
  6507. }
  6508. //control元素
  6509. if (range.item) {
  6510. return range.item(0);
  6511. }
  6512. tmpRange = range.duplicate();
  6513. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6514. tmpRange.text.length > 0 && tmpRange.moveStart('character', 1);
  6515. tmpRange.collapse(1);
  6516. start = tmpRange.parentElement();
  6517. parent = tmp = range.parentElement();
  6518. while (tmp = tmp.parentNode) {
  6519. if (tmp == start) {
  6520. start = parent;
  6521. break;
  6522. }
  6523. }
  6524. } else {
  6525. range.shrinkBoundary();
  6526. start = range.startContainer;
  6527. if (start.nodeType == 1 && start.hasChildNodes()) {
  6528. start = start.childNodes[Math.min(start.childNodes.length - 1, range.startOffset)];
  6529. }
  6530. if (start.nodeType == 3) {
  6531. return start.parentNode;
  6532. }
  6533. }
  6534. return start;
  6535. },
  6536. /**
  6537. * 得到选区中的文本
  6538. * @method getText
  6539. * @return { String } 选区中包含的文本
  6540. * @example
  6541. * ```javascript
  6542. * editor.selection.getText();
  6543. * ```
  6544. */
  6545. getText: function () {
  6546. var nativeSel, nativeRange;
  6547. if (this.isFocus() && (nativeSel = this.getNative())) {
  6548. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt(0);
  6549. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6550. }
  6551. return '';
  6552. },
  6553. /**
  6554. * 清除选区
  6555. * @method clearRange
  6556. * @example
  6557. * ```javascript
  6558. * editor.selection.clearRange();
  6559. * ```
  6560. */
  6561. clearRange: function () {
  6562. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6563. }
  6564. };
  6565. })();
  6566. // core/Editor.js
  6567. /**
  6568. * 编辑器主类,包含编辑器提供的大部分公用接口
  6569. * @file
  6570. * @module UE
  6571. * @class Editor
  6572. * @since 1.2.6.1
  6573. */
  6574. /**
  6575. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6576. * @unfile
  6577. * @module UE
  6578. */
  6579. /**
  6580. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6581. * @unfile
  6582. * @module UE
  6583. * @class Editor
  6584. */
  6585. (function () {
  6586. var uid = 0, _selectionChangeTimer;
  6587. /**
  6588. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6589. * @private
  6590. * @method setValue
  6591. * @param { UE.Editor } editor 编辑器事例
  6592. */
  6593. function setValue(form, editor) {
  6594. var textarea;
  6595. if (editor.textarea) {
  6596. if (utils.isString(editor.textarea)) {
  6597. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6598. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6599. textarea = ti;
  6600. break;
  6601. }
  6602. }
  6603. } else {
  6604. textarea = editor.textarea;
  6605. }
  6606. }
  6607. if (!textarea) {
  6608. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6609. 'name': editor.options.textarea,
  6610. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6611. 'style': "display:none"
  6612. }));
  6613. //不要产生多个textarea
  6614. editor.textarea = textarea;
  6615. }
  6616. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea);
  6617. textarea.value = editor.hasContents() ?
  6618. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6619. ''
  6620. }
  6621. function loadPlugins(me) {
  6622. //初始化插件
  6623. for (var pi in UE.plugins) {
  6624. UE.plugins[pi].call(me);
  6625. }
  6626. }
  6627. function checkCurLang(I18N) {
  6628. for (var lang in I18N) {
  6629. return lang
  6630. }
  6631. }
  6632. function langReadied(me) {
  6633. me.langIsReady = true;
  6634. me.fireEvent("langReady");
  6635. }
  6636. /**
  6637. * 编辑器准备就绪后会触发该事件
  6638. * @module UE
  6639. * @class Editor
  6640. * @event ready
  6641. * @remind render方法执行完成之后,会触发该事件
  6642. * @remind
  6643. * @example
  6644. * ```javascript
  6645. * editor.addListener( 'ready', function( editor ) {
  6646. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6647. * } );
  6648. * ```
  6649. */
  6650. /**
  6651. * 执行destroy方法,会触发该事件
  6652. * @module UE
  6653. * @class Editor
  6654. * @event destroy
  6655. * @see UE.Editor:destroy()
  6656. */
  6657. /**
  6658. * 执行reset方法,会触发该事件
  6659. * @module UE
  6660. * @class Editor
  6661. * @event reset
  6662. * @see UE.Editor:reset()
  6663. */
  6664. /**
  6665. * 执行focus方法,会触发该事件
  6666. * @module UE
  6667. * @class Editor
  6668. * @event focus
  6669. * @see UE.Editor:focus(Boolean)
  6670. */
  6671. /**
  6672. * 语言加载完成会触发该事件
  6673. * @module UE
  6674. * @class Editor
  6675. * @event langReady
  6676. */
  6677. /**
  6678. * 运行命令之后会触发该命令
  6679. * @module UE
  6680. * @class Editor
  6681. * @event beforeExecCommand
  6682. */
  6683. /**
  6684. * 运行命令之后会触发该命令
  6685. * @module UE
  6686. * @class Editor
  6687. * @event afterExecCommand
  6688. */
  6689. /**
  6690. * 运行命令之前会触发该命令
  6691. * @module UE
  6692. * @class Editor
  6693. * @event firstBeforeExecCommand
  6694. */
  6695. /**
  6696. * 在getContent方法执行之前会触发该事件
  6697. * @module UE
  6698. * @class Editor
  6699. * @event beforeGetContent
  6700. * @see UE.Editor:getContent()
  6701. */
  6702. /**
  6703. * 在getContent方法执行之后会触发该事件
  6704. * @module UE
  6705. * @class Editor
  6706. * @event afterGetContent
  6707. * @see UE.Editor:getContent()
  6708. */
  6709. /**
  6710. * 在getAllHtml方法执行时会触发该事件
  6711. * @module UE
  6712. * @class Editor
  6713. * @event getAllHtml
  6714. * @see UE.Editor:getAllHtml()
  6715. */
  6716. /**
  6717. * 在setContent方法执行之前会触发该事件
  6718. * @module UE
  6719. * @class Editor
  6720. * @event beforeSetContent
  6721. * @see UE.Editor:setContent(String)
  6722. */
  6723. /**
  6724. * 在setContent方法执行之后会触发该事件
  6725. * @module UE
  6726. * @class Editor
  6727. * @event afterSetContent
  6728. * @see UE.Editor:setContent(String)
  6729. */
  6730. /**
  6731. * 每当编辑器内部选区发生改变时,将触发该事件
  6732. * @event selectionchange
  6733. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6734. * @example
  6735. * ```javascript
  6736. * editor.addListener( 'selectionchange', function( editor ) {
  6737. * console.log('选区发生改变');
  6738. * }
  6739. */
  6740. /**
  6741. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6742. * @module UE
  6743. * @class Editor
  6744. * @event beforeSelectionChange
  6745. * @see UE.Editor:selectionchange
  6746. */
  6747. /**
  6748. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6749. * @module UE
  6750. * @class Editor
  6751. * @event afterSelectionChange
  6752. * @see UE.Editor:selectionchange
  6753. */
  6754. /**
  6755. * 编辑器内容发生改变时会触发该事件
  6756. * @module UE
  6757. * @class Editor
  6758. * @event contentChange
  6759. */
  6760. /**
  6761. * 以默认参数构建一个编辑器实例
  6762. * @constructor
  6763. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6764. * @example
  6765. * ```javascript
  6766. * var editor = new UE.Editor();
  6767. * editor.execCommand('blod');
  6768. * ```
  6769. * @see UE.Config
  6770. */
  6771. /**
  6772. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6773. * @constructor
  6774. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6775. * @param { Object } setting 创建编辑器的参数
  6776. * @example
  6777. * ```javascript
  6778. * var editor = new UE.Editor();
  6779. * editor.execCommand('blod');
  6780. * ```
  6781. * @see UE.Config
  6782. */
  6783. var Editor = UE.Editor = function (options) {
  6784. var me = this;
  6785. me.uid = uid++;
  6786. EventBase.call(me);
  6787. me.commands = {};
  6788. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6789. me.shortcutkeys = {};
  6790. me.inputRules = [];
  6791. me.outputRules = [];
  6792. //设置默认的常用属性
  6793. me.setOpt(Editor.defaultOptions(me));
  6794. /* 尝试异步加载后台配置 */
  6795. me.loadServerConfig();
  6796. if (!utils.isEmptyObject(UE.I18N)) {
  6797. //修改默认的语言类型
  6798. me.options.lang = checkCurLang(UE.I18N);
  6799. UE.plugin.load(me);
  6800. langReadied(me);
  6801. } else {
  6802. utils.loadFile(document, {
  6803. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6804. tag: "script",
  6805. type: "text/javascript",
  6806. defer: "defer"
  6807. }, function () {
  6808. UE.plugin.load(me);
  6809. langReadied(me);
  6810. });
  6811. }
  6812. UE.instants['ueditorInstant' + me.uid] = me;
  6813. };
  6814. Editor.prototype = {
  6815. registerCommand: function (name, obj) {
  6816. this.commands[name] = obj;
  6817. },
  6818. /**
  6819. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6820. * @method ready
  6821. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6822. * 立即触发该回调。
  6823. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6824. * @example
  6825. * ```javascript
  6826. * editor.ready( function( editor ) {
  6827. * editor.setContent('初始化完毕');
  6828. * } );
  6829. * ```
  6830. * @see UE.Editor.event:ready
  6831. */
  6832. ready: function (fn) {
  6833. var me = this;
  6834. if (fn) {
  6835. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6836. }
  6837. },
  6838. /**
  6839. * 该方法是提供给插件里面使用,设置配置项默认值
  6840. * @method setOpt
  6841. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6842. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6843. * @param { String } key 编辑器的可接受的选项名称
  6844. * @param { * } val 该选项可接受的值
  6845. * @example
  6846. * ```javascript
  6847. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6848. * ```
  6849. */
  6850. /**
  6851. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6852. * @method setOpt
  6853. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6854. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6855. * @param { Object } options 将要设置的选项的键值对对象
  6856. * @example
  6857. * ```javascript
  6858. * editor.setOpt( {
  6859. * 'initContent': '欢迎使用编辑器'
  6860. * } );
  6861. * ```
  6862. */
  6863. setOpt: function (key, val) {
  6864. var obj = {};
  6865. if (utils.isString(key)) {
  6866. obj[key] = val
  6867. } else {
  6868. obj = key;
  6869. }
  6870. utils.extend(this.options, obj, true);
  6871. },
  6872. getOpt: function (key) {
  6873. return this.options[key]
  6874. },
  6875. /**
  6876. * 销毁编辑器实例,使用textarea代替
  6877. * @method destroy
  6878. * @example
  6879. * ```javascript
  6880. * editor.destroy();
  6881. * ```
  6882. */
  6883. destroy: function () {
  6884. var me = this;
  6885. me.fireEvent('destroy');
  6886. var container = me.container.parentNode;
  6887. var textarea = me.textarea;
  6888. if (!textarea) {
  6889. textarea = document.createElement('textarea');
  6890. container.parentNode.insertBefore(textarea, container);
  6891. } else {
  6892. textarea.style.display = ''
  6893. }
  6894. textarea.style.width = me.iframe.offsetWidth + 'px';
  6895. textarea.style.height = me.iframe.offsetHeight + 'px';
  6896. textarea.value = me.getContent();
  6897. textarea.id = me.key;
  6898. container.innerHTML = '';
  6899. domUtils.remove(container);
  6900. var key = me.key;
  6901. //trace:2004
  6902. for (var p in me) {
  6903. if (me.hasOwnProperty(p)) {
  6904. delete this[p];
  6905. }
  6906. }
  6907. UE.delEditor(key);
  6908. },
  6909. /**
  6910. * 渲染编辑器的DOM到指定容器
  6911. * @method render
  6912. * @param { String } containerId 指定一个容器ID
  6913. * @remind 执行该方法,会触发ready事件
  6914. * @warning 必须且只能调用一次
  6915. */
  6916. /**
  6917. * 渲染编辑器的DOM到指定容器
  6918. * @method render
  6919. * @param { Element } containerDom 直接指定容器对象
  6920. * @remind 执行该方法,会触发ready事件
  6921. * @warning 必须且只能调用一次
  6922. */
  6923. render: function (container) {
  6924. var me = this,
  6925. options = me.options,
  6926. getStyleValue = function (attr) {
  6927. return parseInt(domUtils.getComputedStyle(container, attr));
  6928. };
  6929. if (utils.isString(container)) {
  6930. container = document.getElementById(container);
  6931. }
  6932. if (container) {
  6933. if (options.initialFrameWidth) {
  6934. options.minFrameWidth = options.initialFrameWidth
  6935. } else {
  6936. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6937. }
  6938. if (options.initialFrameHeight) {
  6939. options.minFrameHeight = options.initialFrameHeight
  6940. } else {
  6941. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6942. }
  6943. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth -
  6944. getStyleValue("padding-left") - getStyleValue("padding-right") + 'px';
  6945. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6946. getStyleValue("padding-top") - getStyleValue("padding-bottom") + 'px';
  6947. container.style.zIndex = options.zIndex;
  6948. var html = (ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6949. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6950. '<style type=\'text/css\'>' +
  6951. //设置四周的留边
  6952. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6953. //设置默认字体和字号
  6954. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6955. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6956. //设置段落间距
  6957. 'p{margin:5px 0;}</style>' +
  6958. (options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '') +
  6959. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6960. '</head><body class=\'view\' ></body>' +
  6961. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '') + ' id=\'_initialScript\'>' +
  6962. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6963. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6964. container.appendChild(domUtils.createElement(document, 'iframe', {
  6965. id: 'ueditor_' + me.uid,
  6966. width: "100%",
  6967. height: "100%",
  6968. frameborder: "0",
  6969. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6970. // scrolling :'no',
  6971. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6972. 'document.write("' + html + '");document.close();}())'
  6973. }));
  6974. container.style.overflow = 'hidden';
  6975. //解决如果是给定的百分比,会导致高度算不对的问题
  6976. setTimeout(function () {
  6977. if (/%$/.test(options.initialFrameWidth)) {
  6978. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6979. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6980. // container.style.width = options.initialFrameWidth + 'px';
  6981. }
  6982. if (/%$/.test(options.initialFrameHeight)) {
  6983. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6984. container.style.height = options.initialFrameHeight + 'px';
  6985. }
  6986. })
  6987. }
  6988. },
  6989. /**
  6990. * 编辑器初始化
  6991. * @method _setup
  6992. * @private
  6993. * @param { Element } doc 编辑器Iframe中的文档对象
  6994. */
  6995. _setup: function (doc) {
  6996. var me = this,
  6997. options = me.options;
  6998. if (ie) {
  6999. doc.body.disabled = true;
  7000. doc.body.contentEditable = true;
  7001. doc.body.disabled = false;
  7002. } else {
  7003. doc.body.contentEditable = true;
  7004. }
  7005. doc.body.spellcheck = false;
  7006. me.document = doc;
  7007. me.window = doc.defaultView || doc.parentWindow;
  7008. me.iframe = me.window.frameElement;
  7009. me.body = doc.body;
  7010. me.selection = new dom.Selection(doc);
  7011. //gecko初始化就能得到range,无法判断isFocus了
  7012. var geckoSel;
  7013. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7014. geckoSel.removeAllRanges();
  7015. }
  7016. this._initEvents();
  7017. //为form提交提供一个隐藏的textarea
  7018. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  7019. if (form.tagName == 'FORM') {
  7020. me.form = form;
  7021. if (me.options.autoSyncData) {
  7022. domUtils.on(me.window, 'blur', function () {
  7023. setValue(form, me);
  7024. });
  7025. } else {
  7026. domUtils.on(form, 'submit', function () {
  7027. setValue(this, me);
  7028. });
  7029. }
  7030. break;
  7031. }
  7032. }
  7033. if (options.initialContent) {
  7034. if (options.autoClearinitialContent) {
  7035. var oldExecCommand = me.execCommand;
  7036. me.execCommand = function () {
  7037. me.fireEvent('firstBeforeExecCommand');
  7038. return oldExecCommand.apply(me, arguments);
  7039. };
  7040. this._setDefaultContent(options.initialContent);
  7041. } else
  7042. this.setContent(options.initialContent, false, true);
  7043. }
  7044. //编辑器不能为空内容
  7045. if (domUtils.isEmptyNode(me.body)) {
  7046. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  7047. }
  7048. //如果要求focus, 就把光标定位到内容开始
  7049. if (options.focus) {
  7050. setTimeout(function () {
  7051. me.focus(me.options.focusInEnd);
  7052. //如果自动清除开着,就不需要做selectionchange;
  7053. !me.options.autoClearinitialContent && me._selectionChange();
  7054. }, 0);
  7055. }
  7056. if (!me.container) {
  7057. me.container = this.iframe.parentNode;
  7058. }
  7059. if (options.fullscreen && me.ui) {
  7060. me.ui.setFullScreen(true);
  7061. }
  7062. try {
  7063. me.document.execCommand('2D-position', false, false);
  7064. } catch (e) {
  7065. }
  7066. try {
  7067. me.document.execCommand('enableInlineTableEditing', false, false);
  7068. } catch (e) {
  7069. }
  7070. try {
  7071. me.document.execCommand('enableObjectResizing', false, false);
  7072. } catch (e) {
  7073. }
  7074. //挂接快捷键
  7075. me._bindshortcutKeys();
  7076. me.isReady = 1;
  7077. me.fireEvent('ready');
  7078. options.onready && options.onready.call(me);
  7079. if (!browser.ie9below) {
  7080. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  7081. //chrome下会出现alt+tab切换时,导致选区位置不对
  7082. if (e.type == 'blur') {
  7083. me._bakRange = me.selection.getRange();
  7084. try {
  7085. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  7086. me.selection.getNative().removeAllRanges();
  7087. } catch (e) {
  7088. me._bakNativeRange = null;
  7089. }
  7090. } else {
  7091. try {
  7092. me._bakRange && me._bakRange.select();
  7093. } catch (e) {
  7094. }
  7095. }
  7096. });
  7097. }
  7098. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  7099. if (browser.gecko && browser.version <= 10902) {
  7100. //修复ff3.6初始化进来,不能点击获得焦点
  7101. me.body.contentEditable = false;
  7102. setTimeout(function () {
  7103. me.body.contentEditable = true;
  7104. }, 100);
  7105. setInterval(function () {
  7106. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  7107. }, 100)
  7108. }
  7109. !options.isShow && me.setHide();
  7110. options.readonly && me.setDisabled();
  7111. },
  7112. /**
  7113. * 同步数据到编辑器所在的form
  7114. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  7115. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  7116. * @method sync
  7117. * @example
  7118. * ```javascript
  7119. * editor.sync();
  7120. * form.sumbit(); //form变量已经指向了form元素
  7121. * ```
  7122. */
  7123. /**
  7124. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  7125. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  7126. * @method sync
  7127. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  7128. */
  7129. sync: function (formId) {
  7130. var me = this,
  7131. form = formId ? document.getElementById(formId) :
  7132. domUtils.findParent(me.iframe.parentNode, function (node) {
  7133. return node.tagName == 'FORM'
  7134. }, true);
  7135. form && setValue(form, me);
  7136. },
  7137. /**
  7138. * 设置编辑器高度
  7139. * @method setHeight
  7140. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  7141. * @param { Number } number 设置的高度值,纯数值,不带单位
  7142. * @example
  7143. * ```javascript
  7144. * editor.setHeight(number);
  7145. * ```
  7146. */
  7147. setHeight: function (height, notSetHeight) {
  7148. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  7149. this.iframe.parentNode.style.height = height + 'px';
  7150. }
  7151. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  7152. this.body.style.height = height + 'px';
  7153. !notSetHeight && this.trigger('setHeight')
  7154. },
  7155. /**
  7156. * 为编辑器的编辑命令提供快捷键
  7157. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  7158. * @method addshortcutkey
  7159. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  7160. * @example
  7161. * ```javascript
  7162. * editor.addshortcutkey({
  7163. * "Bold" : "ctrl+66",//^B
  7164. * "Italic" : "ctrl+73", //^I
  7165. * });
  7166. * ```
  7167. */
  7168. /**
  7169. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  7170. * @method addshortcutkey
  7171. * @param { String } cmd 触发快捷键时,响应的命令
  7172. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  7173. * @example
  7174. * ```javascript
  7175. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  7176. * ```
  7177. */
  7178. addshortcutkey: function (cmd, keys) {
  7179. var obj = {};
  7180. if (keys) {
  7181. obj[cmd] = keys
  7182. } else {
  7183. obj = cmd;
  7184. }
  7185. utils.extend(this.shortcutkeys, obj)
  7186. },
  7187. /**
  7188. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  7189. * @method _bindshortcutKeys
  7190. * @private
  7191. */
  7192. _bindshortcutKeys: function () {
  7193. var me = this, shortcutkeys = this.shortcutkeys;
  7194. me.addListener('keydown', function (type, e) {
  7195. var keyCode = e.keyCode || e.which;
  7196. for (var i in shortcutkeys) {
  7197. var tmp = shortcutkeys[i].split(',');
  7198. for (var t = 0, ti; ti = tmp[t++];) {
  7199. ti = ti.split(':');
  7200. var key = ti[0], param = ti[1];
  7201. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  7202. if (((RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  7203. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  7204. && keyCode == RegExp.$3
  7205. ) ||
  7206. keyCode == RegExp.$1
  7207. ) {
  7208. if (me.queryCommandState(i, param) != -1)
  7209. me.execCommand(i, param);
  7210. domUtils.preventDefault(e);
  7211. }
  7212. }
  7213. }
  7214. }
  7215. });
  7216. },
  7217. /**
  7218. * 获取编辑器的内容
  7219. * @method getContent
  7220. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  7221. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  7222. * @example
  7223. * ```javascript
  7224. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  7225. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  7226. * ```
  7227. */
  7228. /**
  7229. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  7230. * @method getContent
  7231. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  7232. * 代表当前编辑器的内容是否空,
  7233. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  7234. * 经过内置过滤规则处理后的内容。
  7235. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  7236. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  7237. * @return { String } 编辑器的内容字符串
  7238. * @example
  7239. * ```javascript
  7240. * // editor 是一个编辑器的实例
  7241. * var content = editor.getContent( function ( editor ) {
  7242. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  7243. * } );
  7244. * ```
  7245. */
  7246. getContent: function (cmd, fn, notSetCursor, ignoreBlank, formatter) {
  7247. var me = this;
  7248. if (cmd && utils.isFunction(cmd)) {
  7249. fn = cmd;
  7250. cmd = '';
  7251. }
  7252. if (fn ? !fn() : !this.hasContents()) {
  7253. return '';
  7254. }
  7255. me.fireEvent('beforegetcontent');
  7256. var root = UE.htmlparser(me.body.innerHTML, ignoreBlank);
  7257. me.filterOutputRule(root);
  7258. me.fireEvent('aftergetcontent', cmd, root);
  7259. return root.toHtml(formatter);
  7260. },
  7261. /**
  7262. * 取得完整的html代码,可以直接显示成完整的html文档
  7263. * @method getAllHtml
  7264. * @return { String } 编辑器的内容html文档字符串
  7265. * @eaxmple
  7266. * ```javascript
  7267. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  7268. * ```
  7269. */
  7270. getAllHtml: function () {
  7271. var me = this,
  7272. headHtml = [],
  7273. html = '';
  7274. me.fireEvent('getAllHtml', headHtml);
  7275. if (browser.ie && browser.version > 8) {
  7276. var headHtmlForIE9 = '';
  7277. utils.each(me.document.styleSheets, function (si) {
  7278. headHtmlForIE9 += (si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  7279. });
  7280. utils.each(me.document.getElementsByTagName('script'), function (si) {
  7281. headHtmlForIE9 += si.outerHTML;
  7282. });
  7283. }
  7284. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  7285. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  7286. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  7287. },
  7288. /**
  7289. * 得到编辑器的纯文本内容,但会保留段落格式
  7290. * @method getPlainTxt
  7291. * @return { String } 编辑器带段落格式的纯文本内容字符串
  7292. * @example
  7293. * ```javascript
  7294. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  7295. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  7296. * ```
  7297. */
  7298. getPlainTxt: function () {
  7299. var reg = new RegExp(domUtils.fillChar, 'g'),
  7300. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  7301. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  7302. .replace(/<br\/?>/gi, '\n')
  7303. .replace(/<[^>/]+>/g, '')
  7304. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  7305. return dtd.$block[c] ? '\n' : b ? b : '';
  7306. });
  7307. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  7308. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  7309. },
  7310. /**
  7311. * 获取编辑器中的纯文本内容,没有段落格式
  7312. * @method getContentTxt
  7313. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  7314. * @example
  7315. * ```javascript
  7316. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  7317. * console.log(editor.getPlainTxt()); //输出:"12
  7318. * ```
  7319. */
  7320. getContentTxt: function () {
  7321. var reg = new RegExp(domUtils.fillChar, 'g');
  7322. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  7323. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  7324. },
  7325. /**
  7326. * 设置编辑器的内容,可修改编辑器当前的html内容
  7327. * @method setContent
  7328. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  7329. * @warning 该方法会触发selectionchange事件
  7330. * @param { String } html 要插入的html内容
  7331. * @example
  7332. * ```javascript
  7333. * editor.getContent('<p>test</p>');
  7334. * ```
  7335. */
  7336. /**
  7337. * 设置编辑器的内容,可修改编辑器当前的html内容
  7338. * @method setContent
  7339. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  7340. * @warning 该方法会触发selectionchange事件
  7341. * @param { String } html 要插入的html内容
  7342. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  7343. * @example
  7344. * ```javascript
  7345. * //假设设置前的编辑器内容是 <p>old text</p>
  7346. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  7347. * ```
  7348. */
  7349. setContent: function (html, isAppendTo, notFireSelectionchange) {
  7350. var me = this;
  7351. me.fireEvent('beforesetcontent', html);
  7352. var root = UE.htmlparser(html);
  7353. me.filterInputRule(root);
  7354. html = root.toHtml();
  7355. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  7356. function isCdataDiv(node) {
  7357. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  7358. }
  7359. //给文本或者inline节点套p标签
  7360. if (me.options.enterTag == 'p') {
  7361. var child = this.body.firstChild, tmpNode;
  7362. if (!child || child.nodeType == 1 &&
  7363. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7364. domUtils.isCustomeNode(child)
  7365. )
  7366. && child === this.body.lastChild) {
  7367. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7368. } else {
  7369. var p = me.document.createElement('p');
  7370. while (child) {
  7371. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7372. tmpNode = child.nextSibling;
  7373. p.appendChild(child);
  7374. child = tmpNode;
  7375. }
  7376. if (p.firstChild) {
  7377. if (!child) {
  7378. me.body.appendChild(p);
  7379. break;
  7380. } else {
  7381. child.parentNode.insertBefore(p, child);
  7382. p = me.document.createElement('p');
  7383. }
  7384. }
  7385. child = child.nextSibling;
  7386. }
  7387. }
  7388. }
  7389. me.fireEvent('aftersetcontent');
  7390. me.fireEvent('contentchange');
  7391. !notFireSelectionchange && me._selectionChange();
  7392. //清除保存的选区
  7393. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7394. //trace:1742 setContent后gecko能得到焦点问题
  7395. var geckoSel;
  7396. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7397. geckoSel.removeAllRanges();
  7398. }
  7399. if (me.options.autoSyncData) {
  7400. me.form && setValue(me.form, me);
  7401. }
  7402. },
  7403. /**
  7404. * 让编辑器获得焦点,默认focus到编辑器头部
  7405. * @method focus
  7406. * @example
  7407. * ```javascript
  7408. * editor.focus()
  7409. * ```
  7410. */
  7411. /**
  7412. * 让编辑器获得焦点,toEnd确定focus位置
  7413. * @method focus
  7414. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7415. * @example
  7416. * ```javascript
  7417. * editor.focus(true)
  7418. * ```
  7419. */
  7420. focus: function (toEnd) {
  7421. try {
  7422. var me = this,
  7423. rng = me.selection.getRange();
  7424. if (toEnd) {
  7425. var node = me.body.lastChild;
  7426. if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) {
  7427. if (domUtils.isEmptyBlock(node)) {
  7428. rng.setStartAtFirst(node)
  7429. } else {
  7430. rng.setStartAtLast(node)
  7431. }
  7432. rng.collapse(true);
  7433. }
  7434. rng.setCursor(true);
  7435. } else {
  7436. if (!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0) {
  7437. var node = me.body.firstChild;
  7438. if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) {
  7439. rng.setStartAtFirst(node).collapse(true);
  7440. }
  7441. }
  7442. rng.select(true);
  7443. }
  7444. this.fireEvent('focus selectionchange');
  7445. } catch (e) {
  7446. }
  7447. },
  7448. isFocus: function () {
  7449. return this.selection.isFocus();
  7450. },
  7451. blur: function () {
  7452. var sel = this.selection.getNative();
  7453. if (sel.empty && browser.ie) {
  7454. var nativeRng = document.body.createTextRange();
  7455. nativeRng.moveToElementText(document.body);
  7456. nativeRng.collapse(true);
  7457. nativeRng.select();
  7458. sel.empty()
  7459. } else {
  7460. sel.removeAllRanges()
  7461. }
  7462. //this.fireEvent('blur selectionchange');
  7463. },
  7464. /**
  7465. * 初始化UE事件及部分事件代理
  7466. * @method _initEvents
  7467. * @private
  7468. */
  7469. _initEvents: function () {
  7470. var me = this,
  7471. doc = me.document,
  7472. win = me.window;
  7473. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7474. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7475. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7476. domUtils.on(me.body, 'drop', function (e) {
  7477. //阻止ff下默认的弹出新页面打开图片
  7478. if (browser.gecko && e.stopPropagation) {
  7479. e.stopPropagation();
  7480. }
  7481. me.fireEvent('contentchange')
  7482. });
  7483. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7484. //特殊键不触发selectionchange
  7485. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7486. return;
  7487. }
  7488. if (evt.button == 2) return;
  7489. me._selectionChange(250, evt);
  7490. });
  7491. },
  7492. /**
  7493. * 触发事件代理
  7494. * @method _proxyDomEvent
  7495. * @private
  7496. * @return { * } fireEvent的返回值
  7497. * @see UE.EventBase:fireEvent(String)
  7498. */
  7499. _proxyDomEvent: function (evt) {
  7500. if (this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false) {
  7501. return false;
  7502. }
  7503. if (this.fireEvent(evt.type.replace(/^on/, ''), evt) === false) {
  7504. return false;
  7505. }
  7506. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7507. },
  7508. /**
  7509. * 变化选区
  7510. * @method _selectionChange
  7511. * @private
  7512. */
  7513. _selectionChange: function (delay, evt) {
  7514. var me = this;
  7515. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7516. // if ( !me.selection.isFocus() ){
  7517. // return;
  7518. // }
  7519. var hackForMouseUp = false;
  7520. var mouseX, mouseY;
  7521. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7522. var range = this.selection.getRange();
  7523. if (!range.collapsed) {
  7524. hackForMouseUp = true;
  7525. mouseX = evt.clientX;
  7526. mouseY = evt.clientY;
  7527. }
  7528. }
  7529. clearTimeout(_selectionChangeTimer);
  7530. _selectionChangeTimer = setTimeout(function () {
  7531. if (!me.selection || !me.selection.getNative()) {
  7532. return;
  7533. }
  7534. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7535. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7536. var ieRange;
  7537. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7538. ieRange = me.document.body.createTextRange();
  7539. try {
  7540. ieRange.moveToPoint(mouseX, mouseY);
  7541. } catch (ex) {
  7542. ieRange = null;
  7543. }
  7544. }
  7545. var bakGetIERange;
  7546. if (ieRange) {
  7547. bakGetIERange = me.selection.getIERange;
  7548. me.selection.getIERange = function () {
  7549. return ieRange;
  7550. };
  7551. }
  7552. me.selection.cache();
  7553. if (bakGetIERange) {
  7554. me.selection.getIERange = bakGetIERange;
  7555. }
  7556. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7557. me.fireEvent('beforeselectionchange');
  7558. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7559. me.fireEvent('selectionchange', !!evt);
  7560. me.fireEvent('afterselectionchange');
  7561. me.selection.clear();
  7562. }
  7563. }, delay || 50);
  7564. },
  7565. /**
  7566. * 执行编辑命令
  7567. * @method _callCmdFn
  7568. * @private
  7569. * @param { String } fnName 函数名称
  7570. * @param { * } args 传给命令函数的参数
  7571. * @return { * } 返回命令函数运行的返回值
  7572. */
  7573. _callCmdFn: function (fnName, args) {
  7574. var cmdName = args[0].toLowerCase(),
  7575. cmd, cmdFn;
  7576. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7577. cmdFn = cmd && cmd[fnName];
  7578. //没有querycommandstate或者没有command的都默认返回0
  7579. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7580. return 0;
  7581. } else if (cmdFn) {
  7582. return cmdFn.apply(this, args);
  7583. }
  7584. },
  7585. /**
  7586. * 执行编辑命令cmdName,完成富文本编辑效果
  7587. * @method execCommand
  7588. * @param { String } cmdName 需要执行的命令
  7589. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7590. * @return { * } 返回命令函数运行的返回值
  7591. * @example
  7592. * ```javascript
  7593. * editor.execCommand(cmdName);
  7594. * ```
  7595. */
  7596. execCommand: function (cmdName) {
  7597. cmdName = cmdName.toLowerCase();
  7598. var me = this,
  7599. result,
  7600. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7601. if (!cmd || !cmd.execCommand) {
  7602. return null;
  7603. }
  7604. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7605. me.__hasEnterExecCommand = true;
  7606. if (me.queryCommandState.apply(me, arguments) != -1) {
  7607. me.fireEvent('saveScene');
  7608. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7609. result = this._callCmdFn('execCommand', arguments);
  7610. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7611. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7612. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7613. me.fireEvent('saveScene');
  7614. }
  7615. me.__hasEnterExecCommand = false;
  7616. } else {
  7617. result = this._callCmdFn('execCommand', arguments);
  7618. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7619. }
  7620. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7621. return result;
  7622. },
  7623. /**
  7624. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7625. * @method queryCommandState
  7626. * @param { String } cmdName 需要查询的命令名称
  7627. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7628. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7629. * @example
  7630. * ```javascript
  7631. * editor.queryCommandState(cmdName) => (-1|0|1)
  7632. * ```
  7633. * @see COMMAND.LIST
  7634. */
  7635. queryCommandState: function (cmdName) {
  7636. return this._callCmdFn('queryCommandState', arguments);
  7637. },
  7638. /**
  7639. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7640. * @method queryCommandValue
  7641. * @param { String } cmdName 需要查询的命令名称
  7642. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7643. * @remind 只有部分插件有此方法
  7644. * @return { * } 返回每个命令特定的当前状态值
  7645. * @grammar editor.queryCommandValue(cmdName) => {*}
  7646. * @see COMMAND.LIST
  7647. */
  7648. queryCommandValue: function (cmdName) {
  7649. return this._callCmdFn('queryCommandValue', arguments);
  7650. },
  7651. /**
  7652. * 检查编辑区域中是否有内容
  7653. * @method hasContents
  7654. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7655. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7656. * @return { Boolean } 检查有内容返回true,否则返回false
  7657. * @example
  7658. * ```javascript
  7659. * editor.hasContents()
  7660. * ```
  7661. */
  7662. /**
  7663. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7664. * @method hasContents
  7665. * @param { Array } tags 传入数组判断时用到的节点类型
  7666. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7667. * @example
  7668. * ```javascript
  7669. * editor.hasContents(['span']);
  7670. * ```
  7671. */
  7672. hasContents: function (tags) {
  7673. if (tags) {
  7674. for (var i = 0, ci; ci = tags[i++];) {
  7675. if (this.document.getElementsByTagName(ci).length > 0) {
  7676. return true;
  7677. }
  7678. }
  7679. }
  7680. if (!domUtils.isEmptyBlock(this.body)) {
  7681. return true
  7682. }
  7683. //随时添加,定义的特殊标签如果存在,不能认为是空
  7684. tags = ['div'];
  7685. for (i = 0; ci = tags[i++];) {
  7686. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7687. for (var n = 0, cn; cn = nodes[n++];) {
  7688. if (domUtils.isCustomeNode(cn)) {
  7689. return true;
  7690. }
  7691. }
  7692. }
  7693. return false;
  7694. },
  7695. /**
  7696. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7697. * @method reset
  7698. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7699. * @example
  7700. * ```javascript
  7701. * editor.reset()
  7702. * ```
  7703. */
  7704. reset: function () {
  7705. this.fireEvent('reset');
  7706. },
  7707. /**
  7708. * 设置当前编辑区域可以编辑
  7709. * @method setEnabled
  7710. * @example
  7711. * ```javascript
  7712. * editor.setEnabled()
  7713. * ```
  7714. */
  7715. setEnabled: function () {
  7716. var me = this, range;
  7717. if (me.body.contentEditable == 'false') {
  7718. me.body.contentEditable = true;
  7719. range = me.selection.getRange();
  7720. //有可能内容丢失了
  7721. try {
  7722. range.moveToBookmark(me.lastBk);
  7723. delete me.lastBk
  7724. } catch (e) {
  7725. range.setStartAtFirst(me.body).collapse(true)
  7726. }
  7727. range.select(true);
  7728. if (me.bkqueryCommandState) {
  7729. me.queryCommandState = me.bkqueryCommandState;
  7730. delete me.bkqueryCommandState;
  7731. }
  7732. if (me.bkqueryCommandValue) {
  7733. me.queryCommandValue = me.bkqueryCommandValue;
  7734. delete me.bkqueryCommandValue;
  7735. }
  7736. me.fireEvent('selectionchange');
  7737. }
  7738. },
  7739. enable: function () {
  7740. return this.setEnabled();
  7741. },
  7742. /** 设置当前编辑区域不可编辑
  7743. * @method setDisabled
  7744. */
  7745. /** 设置当前编辑区域不可编辑,except中的命令除外
  7746. * @method setDisabled
  7747. * @param { String } except 例外命令的字符串
  7748. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7749. * @example
  7750. * ```javascript
  7751. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7752. * ```
  7753. */
  7754. /** 设置当前编辑区域不可编辑,except中的命令除外
  7755. * @method setDisabled
  7756. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7757. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7758. * @example
  7759. * ```javascript
  7760. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7761. * ```
  7762. */
  7763. setDisabled: function (except) {
  7764. var me = this;
  7765. except = except ? utils.isArray(except) ? except : [except] : [];
  7766. if (me.body.contentEditable == 'true') {
  7767. if (!me.lastBk) {
  7768. me.lastBk = me.selection.getRange().createBookmark(true);
  7769. }
  7770. me.body.contentEditable = false;
  7771. me.bkqueryCommandState = me.queryCommandState;
  7772. me.bkqueryCommandValue = me.queryCommandValue;
  7773. me.queryCommandState = function (type) {
  7774. if (utils.indexOf(except, type) != -1) {
  7775. return me.bkqueryCommandState.apply(me, arguments);
  7776. }
  7777. return -1;
  7778. };
  7779. me.queryCommandValue = function (type) {
  7780. if (utils.indexOf(except, type) != -1) {
  7781. return me.bkqueryCommandValue.apply(me, arguments);
  7782. }
  7783. return null;
  7784. };
  7785. me.fireEvent('selectionchange');
  7786. }
  7787. },
  7788. disable: function (except) {
  7789. return this.setDisabled(except);
  7790. },
  7791. /**
  7792. * 设置默认内容
  7793. * @method _setDefaultContent
  7794. * @private
  7795. * @param { String } cont 要存入的内容
  7796. */
  7797. _setDefaultContent: function () {
  7798. function clear() {
  7799. var me = this;
  7800. if (me.document.getElementById('initContent')) {
  7801. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7802. me.removeListener('firstBeforeExecCommand focus', clear);
  7803. setTimeout(function () {
  7804. me.focus();
  7805. me._selectionChange();
  7806. }, 0)
  7807. }
  7808. }
  7809. return function (cont) {
  7810. var me = this;
  7811. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7812. me.addListener('firstBeforeExecCommand focus', clear);
  7813. }
  7814. }(),
  7815. /**
  7816. * 显示编辑器
  7817. * @method setShow
  7818. * @example
  7819. * ```javascript
  7820. * editor.setShow()
  7821. * ```
  7822. */
  7823. setShow: function () {
  7824. var me = this, range = me.selection.getRange();
  7825. if (me.container.style.display == 'none') {
  7826. //有可能内容丢失了
  7827. try {
  7828. range.moveToBookmark(me.lastBk);
  7829. delete me.lastBk
  7830. } catch (e) {
  7831. range.setStartAtFirst(me.body).collapse(true)
  7832. }
  7833. //ie下focus实效,所以做了个延迟
  7834. setTimeout(function () {
  7835. range.select(true);
  7836. }, 100);
  7837. me.container.style.display = '';
  7838. }
  7839. },
  7840. show: function () {
  7841. return this.setShow();
  7842. },
  7843. /**
  7844. * 隐藏编辑器
  7845. * @method setHide
  7846. * @example
  7847. * ```javascript
  7848. * editor.setHide()
  7849. * ```
  7850. */
  7851. setHide: function () {
  7852. var me = this;
  7853. if (!me.lastBk) {
  7854. me.lastBk = me.selection.getRange().createBookmark(true);
  7855. }
  7856. me.container.style.display = 'none'
  7857. },
  7858. hide: function () {
  7859. return this.setHide();
  7860. },
  7861. /**
  7862. * 根据指定的路径,获取对应的语言资源
  7863. * @method getLang
  7864. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7865. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7866. * @example
  7867. * ```javascript
  7868. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7869. * ```
  7870. */
  7871. getLang: function (path) {
  7872. var lang = UE.I18N[this.options.lang];
  7873. if (!lang) {
  7874. throw Error("not import language file");
  7875. }
  7876. path = (path || "").split(".");
  7877. for (var i = 0, ci; ci = path[i++];) {
  7878. lang = lang[ci];
  7879. if (!lang) break;
  7880. }
  7881. return lang;
  7882. },
  7883. /**
  7884. * 计算编辑器html内容字符串的长度
  7885. * @method getContentLength
  7886. * @return { Number } 返回计算的长度
  7887. * @example
  7888. * ```javascript
  7889. * //编辑器html内容<p><strong>132</strong></p>
  7890. * editor.getContentLength() //返回27
  7891. * ```
  7892. */
  7893. /**
  7894. * 计算编辑器当前纯文本内容的长度
  7895. * @method getContentLength
  7896. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7897. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7898. * @example
  7899. * ```javascript
  7900. * //编辑器html内容<p><strong>132</strong></p>
  7901. * editor.getContentLength() //返回3
  7902. * ```
  7903. */
  7904. getContentLength: function (ingoneHtml, tagNames) {
  7905. var count = this.getContent(false, false, true).length;
  7906. if (ingoneHtml) {
  7907. tagNames = (tagNames || []).concat(['hr', 'img', 'iframe']);
  7908. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7909. for (var i = 0, ci; ci = tagNames[i++];) {
  7910. count += this.document.getElementsByTagName(ci).length;
  7911. }
  7912. }
  7913. return count;
  7914. },
  7915. /**
  7916. * 注册输入过滤规则
  7917. * @method addInputRule
  7918. * @param { Function } rule 要添加的过滤规则
  7919. * @example
  7920. * ```javascript
  7921. * editor.addInputRule(function(root){
  7922. * $.each(root.getNodesByTagName('div'),function(i,node){
  7923. * node.tagName="p";
  7924. * });
  7925. * });
  7926. * ```
  7927. */
  7928. addInputRule: function (rule) {
  7929. this.inputRules.push(rule);
  7930. },
  7931. /**
  7932. * 执行注册的过滤规则
  7933. * @method filterInputRule
  7934. * @param { UE.uNode } root 要过滤的uNode节点
  7935. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7936. * @example
  7937. * ```javascript
  7938. * editor.filterInputRule(editor.body);
  7939. * ```
  7940. * @see UE.Editor:addInputRule
  7941. */
  7942. filterInputRule: function (root) {
  7943. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7944. ci.call(this, root)
  7945. }
  7946. },
  7947. /**
  7948. * 注册输出过滤规则
  7949. * @method addOutputRule
  7950. * @param { Function } rule 要添加的过滤规则
  7951. * @example
  7952. * ```javascript
  7953. * editor.addOutputRule(function(root){
  7954. * $.each(root.getNodesByTagName('p'),function(i,node){
  7955. * node.tagName="div";
  7956. * });
  7957. * });
  7958. * ```
  7959. */
  7960. addOutputRule: function (rule) {
  7961. this.outputRules.push(rule)
  7962. },
  7963. /**
  7964. * 根据输出过滤规则,过滤编辑器内容
  7965. * @method filterOutputRule
  7966. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7967. * @param { UE.uNode } root 要过滤的uNode节点
  7968. * @example
  7969. * ```javascript
  7970. * editor.filterOutputRule(editor.body);
  7971. * ```
  7972. * @see UE.Editor:addOutputRule
  7973. */
  7974. filterOutputRule: function (root) {
  7975. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7976. ci.call(this, root)
  7977. }
  7978. },
  7979. /**
  7980. * 根据action名称获取请求的路径
  7981. * @method getActionUrl
  7982. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7983. * @param { String } action action名称
  7984. * @example
  7985. * ```javascript
  7986. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7987. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7988. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7989. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7990. * ```
  7991. */
  7992. getActionUrl: function (action) {
  7993. var actionName = this.getOpt(action) || action,
  7994. imageUrl = this.getOpt('imageUrl'),
  7995. serverUrl = this.getOpt('serverUrl');
  7996. if (!serverUrl && imageUrl) {
  7997. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7998. }
  7999. if (serverUrl) {
  8000. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?' : '&') + 'action=' + (actionName || '');
  8001. return utils.formatUrl(serverUrl);
  8002. } else {
  8003. return '';
  8004. }
  8005. }
  8006. };
  8007. utils.inherits(Editor, EventBase);
  8008. })();
  8009. // core/Editor.defaultoptions.js
  8010. //维护编辑器一下默认的不在插件中的配置项
  8011. UE.Editor.defaultOptions = function (editor) {
  8012. var _url = editor.options.UEDITOR_HOME_URL;
  8013. return {
  8014. isShow: true,
  8015. initialContent: '',
  8016. initialStyle: '',
  8017. autoClearinitialContent: false,
  8018. iframeCssUrl: _url + 'themes/iframe.css',
  8019. textarea: 'editorValue',
  8020. focus: false,
  8021. focusInEnd: true,
  8022. autoClearEmptyNode: true,
  8023. fullscreen: false,
  8024. readonly: false,
  8025. zIndex: 999,
  8026. imagePopup: true,
  8027. enterTag: 'p',
  8028. customDomain: false,
  8029. lang: 'zh-cn',
  8030. langPath: _url + 'lang/',
  8031. theme: 'default',
  8032. themePath: _url + 'themes/',
  8033. allHtmlEnabled: false,
  8034. scaleEnabled: false,
  8035. tableNativeEditInFF: false,
  8036. autoSyncData: true,
  8037. fileNameFormat: '{time}{rand:6}'
  8038. }
  8039. };
  8040. // core/loadconfig.js
  8041. (function () {
  8042. UE.Editor.prototype.loadServerConfig = function () {
  8043. var me = this;
  8044. setTimeout(function () {
  8045. try {
  8046. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  8047. var configUrl = me.getActionUrl('config'),
  8048. isJsonp = utils.isCrossDomainUrl(configUrl);
  8049. /* 发出ajax请求 */
  8050. me._serverConfigLoaded = false;
  8051. configUrl && UE.ajax.request(configUrl, {
  8052. 'method': 'GET',
  8053. 'dataType': isJsonp ? 'jsonp' : '',
  8054. 'onsuccess': function (r) {
  8055. try {
  8056. var config = isJsonp ? r : eval("(" + r.responseText + ")");
  8057. utils.extend(me.options, config);
  8058. me.fireEvent('serverConfigLoaded');
  8059. me._serverConfigLoaded = true;
  8060. } catch (e) {
  8061. showErrorMsg(me.getLang('loadconfigFormatError'));
  8062. }
  8063. },
  8064. 'onerror': function () {
  8065. showErrorMsg(me.getLang('loadconfigHttpError'));
  8066. }
  8067. });
  8068. } catch (e) {
  8069. showErrorMsg(me.getLang('loadconfigError'));
  8070. }
  8071. });
  8072. function showErrorMsg(msg) {
  8073. console && console.error(msg);
  8074. //me.fireEvent('showMessage', {
  8075. // 'title': msg,
  8076. // 'type': 'error'
  8077. //});
  8078. }
  8079. };
  8080. UE.Editor.prototype.isServerConfigLoaded = function () {
  8081. var me = this;
  8082. return me._serverConfigLoaded || false;
  8083. };
  8084. UE.Editor.prototype.afterConfigReady = function (handler) {
  8085. if (!handler || !utils.isFunction(handler)) return;
  8086. var me = this;
  8087. var readyHandler = function () {
  8088. handler.apply(me, arguments);
  8089. me.removeListener('serverConfigLoaded', readyHandler);
  8090. };
  8091. if (me.isServerConfigLoaded()) {
  8092. handler.call(me, 'serverConfigLoaded');
  8093. } else {
  8094. me.addListener('serverConfigLoaded', readyHandler);
  8095. }
  8096. };
  8097. })();
  8098. // core/ajax.js
  8099. /**
  8100. * @file
  8101. * @module UE.ajax
  8102. * @since 1.2.6.1
  8103. */
  8104. /**
  8105. * 提供对ajax请求的支持
  8106. * @module UE.ajax
  8107. */
  8108. UE.ajax = function () {
  8109. //创建一个ajaxRequest对象
  8110. var fnStr = 'XMLHttpRequest()';
  8111. try {
  8112. new ActiveXObject("Msxml2.XMLHTTP");
  8113. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  8114. } catch (e) {
  8115. try {
  8116. new ActiveXObject("Microsoft.XMLHTTP");
  8117. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  8118. } catch (e) {
  8119. }
  8120. }
  8121. var creatAjaxRequest = new Function('return new ' + fnStr);
  8122. /**
  8123. * 将json参数转化成适合ajax提交的参数列表
  8124. * @param json
  8125. */
  8126. function json2str(json) {
  8127. var strArr = [];
  8128. for (var i in json) {
  8129. //忽略默认的几个参数
  8130. if (i == "method" || i == "timeout" || i == "async" || i == "dataType" || i == "callback") continue;
  8131. //忽略控制
  8132. if (json[i] == undefined || json[i] == null) continue;
  8133. //传递过来的对象和函数不在提交之列
  8134. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  8135. strArr.push(encodeURIComponent(i) + "=" + encodeURIComponent(json[i]));
  8136. } else if (utils.isArray(json[i])) {
  8137. //支持传数组内容
  8138. for (var j = 0; j < json[i].length; j++) {
  8139. strArr.push(encodeURIComponent(i) + "[]=" + encodeURIComponent(json[i][j]));
  8140. }
  8141. }
  8142. }
  8143. return strArr.join("&");
  8144. }
  8145. function doAjax(url, ajaxOptions) {
  8146. var xhr = creatAjaxRequest(),
  8147. //是否超时
  8148. timeIsOut = false,
  8149. //默认参数
  8150. defaultAjaxOptions = {
  8151. method: "POST",
  8152. timeout: 5000,
  8153. async: true,
  8154. data: {},//需要传递对象的话只能覆盖
  8155. onsuccess: function () {
  8156. },
  8157. onerror: function () {
  8158. }
  8159. };
  8160. if (typeof url === "object") {
  8161. ajaxOptions = url;
  8162. url = ajaxOptions.url;
  8163. }
  8164. if (!xhr || !url) return;
  8165. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions, ajaxOptions) : defaultAjaxOptions;
  8166. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  8167. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  8168. if (!utils.isEmptyObject(ajaxOpts.data)) {
  8169. submitStr += (submitStr ? "&" : "") + json2str(ajaxOpts.data);
  8170. }
  8171. //超时检测
  8172. var timerID = setTimeout(function () {
  8173. if (xhr.readyState != 4) {
  8174. timeIsOut = true;
  8175. xhr.abort();
  8176. clearTimeout(timerID);
  8177. }
  8178. }, ajaxOpts.timeout);
  8179. var method = ajaxOpts.method.toUpperCase();
  8180. var str = url + (url.indexOf("?") == -1 ? "?" : "&") + (method == "POST" ? "" : submitStr + "&noCache=" + +new Date);
  8181. xhr.open(method, str, ajaxOpts.async);
  8182. xhr.onreadystatechange = function () {
  8183. if (xhr.readyState == 4) {
  8184. if (!timeIsOut && xhr.status == 200) {
  8185. ajaxOpts.onsuccess(xhr);
  8186. } else {
  8187. ajaxOpts.onerror(xhr);
  8188. }
  8189. }
  8190. };
  8191. if (method == "POST") {
  8192. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  8193. xhr.send(submitStr);
  8194. } else {
  8195. xhr.send(null);
  8196. }
  8197. }
  8198. function doJsonp(url, opts) {
  8199. var successhandler = opts.onsuccess || function () {
  8200. },
  8201. scr = document.createElement('SCRIPT'),
  8202. options = opts || {},
  8203. charset = options['charset'],
  8204. callbackField = options['jsonp'] || 'callback',
  8205. callbackFnName,
  8206. timeOut = options['timeOut'] || 0,
  8207. timer,
  8208. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  8209. matches;
  8210. if (utils.isFunction(successhandler)) {
  8211. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  8212. window[callbackFnName] = getCallBack(0);
  8213. } else if (utils.isString(successhandler)) {
  8214. callbackFnName = successhandler;
  8215. } else {
  8216. if (matches = reg.exec(url)) {
  8217. callbackFnName = matches[2];
  8218. }
  8219. }
  8220. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  8221. if (url.search(reg) < 0) {
  8222. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  8223. }
  8224. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  8225. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  8226. if (!utils.isEmptyObject(opts.data)) {
  8227. queryStr += (queryStr ? "&" : "") + json2str(opts.data);
  8228. }
  8229. if (queryStr) {
  8230. url = url.replace(/\?/, '?' + queryStr + '&');
  8231. }
  8232. scr.onerror = getCallBack(1);
  8233. if (timeOut) {
  8234. timer = setTimeout(getCallBack(1), timeOut);
  8235. }
  8236. createScriptTag(scr, url, charset);
  8237. function createScriptTag(scr, url, charset) {
  8238. scr.setAttribute('type', 'text/javascript');
  8239. scr.setAttribute('defer', 'defer');
  8240. charset && scr.setAttribute('charset', charset);
  8241. scr.setAttribute('src', url);
  8242. document.getElementsByTagName('head')[0].appendChild(scr);
  8243. }
  8244. function getCallBack(onTimeOut) {
  8245. return function () {
  8246. try {
  8247. if (onTimeOut) {
  8248. options.onerror && options.onerror();
  8249. } else {
  8250. try {
  8251. clearTimeout(timer);
  8252. successhandler.apply(window, arguments);
  8253. } catch (e) {
  8254. }
  8255. }
  8256. } catch (exception) {
  8257. options.onerror && options.onerror.call(window, exception);
  8258. } finally {
  8259. options.oncomplete && options.oncomplete.apply(window, arguments);
  8260. scr.parentNode && scr.parentNode.removeChild(scr);
  8261. window[callbackFnName] = null;
  8262. try {
  8263. delete window[callbackFnName];
  8264. } catch (e) {
  8265. }
  8266. }
  8267. }
  8268. }
  8269. }
  8270. return {
  8271. /**
  8272. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  8273. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  8274. * @method request
  8275. * @param { URLString } url ajax请求的url地址
  8276. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  8277. * @example
  8278. * ```javascript
  8279. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  8280. * UE.ajax.requeset( 'sayhello.php', {
  8281. *
  8282. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  8283. * method: 'GET',
  8284. *
  8285. * //超时时间。 默认为5000, 单位是ms
  8286. * timeout: 10000,
  8287. *
  8288. * //是否是异步请求。 true为异步请求, false为同步请求
  8289. * async: true,
  8290. *
  8291. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  8292. * data: {
  8293. * name: 'ueditor'
  8294. * },
  8295. *
  8296. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  8297. * onsuccess: function ( xhr ) {
  8298. * console.log( xhr.responseText );
  8299. * },
  8300. *
  8301. * //请求失败或者超时后的回调。
  8302. * onerror: function ( xhr ) {
  8303. * alert( 'Ajax请求失败' );
  8304. * }
  8305. *
  8306. * } );
  8307. * ```
  8308. */
  8309. /**
  8310. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  8311. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  8312. * @method request
  8313. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  8314. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  8315. * @example
  8316. * ```javascript
  8317. *
  8318. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  8319. * UE.ajax.requeset( 'sayhello.php', {
  8320. *
  8321. * //请求的地址, 该项是必须的。
  8322. * url: 'sayhello.php'
  8323. *
  8324. * } );
  8325. * ```
  8326. */
  8327. request: function (url, opts) {
  8328. if (opts && opts.dataType == 'jsonp') {
  8329. doJsonp(url, opts);
  8330. } else {
  8331. doAjax(url, opts);
  8332. }
  8333. },
  8334. getJSONP: function (url, data, fn) {
  8335. var opts = {
  8336. 'data': data,
  8337. 'oncomplete': fn
  8338. };
  8339. doJsonp(url, opts);
  8340. }
  8341. };
  8342. }();
  8343. // core/filterword.js
  8344. /**
  8345. * UE过滤word的静态方法
  8346. * @file
  8347. */
  8348. /**
  8349. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8350. * @module UE
  8351. */
  8352. /**
  8353. * 根据传入html字符串过滤word
  8354. * @module UE
  8355. * @since 1.2.6.1
  8356. * @method filterWord
  8357. * @param { String } html html字符串
  8358. * @return { String } 已过滤后的结果字符串
  8359. * @example
  8360. * ```javascript
  8361. * UE.filterWord(html);
  8362. * ```
  8363. */
  8364. var filterWord = UE.filterWord = function () {
  8365. //是否是word过来的内容
  8366. function isWordDocument(str) {
  8367. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test(str);
  8368. }
  8369. //去掉小数
  8370. function transUnit(v) {
  8371. v = v.replace(/[\d.]+\w+/g, function (m) {
  8372. return utils.transUnitToPx(m);
  8373. });
  8374. return v;
  8375. }
  8376. function filterPasteWord(str) {
  8377. return str.replace(/[\t\r\n]+/g, ' ')
  8378. .replace(/<!--[\s\S]*?-->/ig, "")
  8379. //转换图片
  8380. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi, function (str) {
  8381. //opera能自己解析出image所这里直接返回空
  8382. if (browser.opera) {
  8383. return '';
  8384. }
  8385. try {
  8386. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8387. if (/Bitmap/i.test(str)) {
  8388. return '';
  8389. }
  8390. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8391. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8392. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8393. return '<img width="' + transUnit(width) + '" height="' + transUnit(height) + '" src="' + src + '" />';
  8394. } catch (e) {
  8395. return '';
  8396. }
  8397. })
  8398. //针对wps添加的多余标签处理
  8399. .replace(/<\/?div[^>]*>/g, '')
  8400. //去掉多余的属性
  8401. .replace(/v:\w+=(["']?)[^'"]+\1/g, '')
  8402. .replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "")
  8403. .replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>")
  8404. //去掉多余的属性
  8405. .replace(/\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function (str, name, marks, val) {
  8406. //保留list的标示
  8407. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8408. })
  8409. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8410. .replace(/<(font|span)[^>]*>(\s*)<\/\1>/gi, function (a, b, c) {
  8411. return c.replace(/[\t\r\n ]+/g, ' ')
  8412. })
  8413. //处理style的问题
  8414. .replace(/(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function (str, tag, tmp, style) {
  8415. var n = [],
  8416. s = style.replace(/^\s+|\s+$/, '')
  8417. .replace(/&#39;/g, '\'')
  8418. .replace(/&quot;/gi, "'")
  8419. .replace(/[\d.]+(cm|pt)/g, function (str) {
  8420. return utils.transUnitToPx(str)
  8421. })
  8422. .split(/;\s*/g);
  8423. for (var i = 0, v; v = s[i]; i++) {
  8424. var name, value,
  8425. parts = v.split(":");
  8426. if (parts.length == 2) {
  8427. name = parts[0].toLowerCase();
  8428. value = parts[1].toLowerCase();
  8429. if (/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g, '').length == 0
  8430. ||
  8431. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8432. ) {
  8433. continue;
  8434. }
  8435. switch (name) {
  8436. case "mso-padding-alt":
  8437. case "mso-padding-top-alt":
  8438. case "mso-padding-right-alt":
  8439. case "mso-padding-bottom-alt":
  8440. case "mso-padding-left-alt":
  8441. case "mso-margin-alt":
  8442. case "mso-margin-top-alt":
  8443. case "mso-margin-right-alt":
  8444. case "mso-margin-bottom-alt":
  8445. case "mso-margin-left-alt":
  8446. //ie下会出现挤到一起的情况
  8447. //case "mso-table-layout-alt":
  8448. case "mso-height":
  8449. case "mso-width":
  8450. case "mso-vertical-align-alt":
  8451. //trace:1819 ff下会解析出padding在table上
  8452. if (!/<table/.test(tag))
  8453. n[i] = name.replace(/^mso-|-alt$/g, "") + ":" + transUnit(value);
  8454. continue;
  8455. case "horiz-align":
  8456. n[i] = "text-align:" + value;
  8457. continue;
  8458. case "vert-align":
  8459. n[i] = "vertical-align:" + value;
  8460. continue;
  8461. case "font-color":
  8462. case "mso-foreground":
  8463. n[i] = "color:" + value;
  8464. continue;
  8465. case "mso-background":
  8466. case "mso-highlight":
  8467. n[i] = "background:" + value;
  8468. continue;
  8469. case "mso-default-height":
  8470. n[i] = "min-height:" + transUnit(value);
  8471. continue;
  8472. case "mso-default-width":
  8473. n[i] = "min-width:" + transUnit(value);
  8474. continue;
  8475. case "mso-padding-between-alt":
  8476. n[i] = "border-collapse:separate;border-spacing:" + transUnit(value);
  8477. continue;
  8478. case "text-line-through":
  8479. if ((value == "single") || (value == "double")) {
  8480. n[i] = "text-decoration:line-through";
  8481. }
  8482. continue;
  8483. case "mso-zero-height":
  8484. if (value == "yes") {
  8485. n[i] = "display:none";
  8486. }
  8487. continue;
  8488. // case 'background':
  8489. // break;
  8490. case 'margin':
  8491. if (!/[1-9]/.test(value)) {
  8492. continue;
  8493. }
  8494. }
  8495. 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)
  8496. ||
  8497. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8498. ) {
  8499. continue;
  8500. }
  8501. n[i] = name + ":" + parts[1];
  8502. }
  8503. }
  8504. return tag + (n.length ? ' style="' + n.join(';').replace(/;{2,}/g, ';') + '"' : '');
  8505. })
  8506. }
  8507. return function (html) {
  8508. return (isWordDocument(html) ? filterPasteWord(html) : html);
  8509. };
  8510. }();
  8511. // core/node.js
  8512. /**
  8513. * 编辑器模拟的节点类
  8514. * @file
  8515. * @module UE
  8516. * @class uNode
  8517. * @since 1.2.6.1
  8518. */
  8519. /**
  8520. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8521. * @unfile
  8522. * @module UE
  8523. */
  8524. (function () {
  8525. /**
  8526. * 编辑器模拟的节点类
  8527. * @unfile
  8528. * @module UE
  8529. * @class uNode
  8530. */
  8531. /**
  8532. * 通过一个键值对,创建一个uNode对象
  8533. * @constructor
  8534. * @param { Object } attr 传入要创建的uNode的初始属性
  8535. * @example
  8536. * ```javascript
  8537. * var node = new uNode({
  8538. * type:'element',
  8539. * tagName:'span',
  8540. * attrs:{style:'font-size:14px;'}
  8541. * }
  8542. * ```
  8543. */
  8544. var uNode = UE.uNode = function (obj) {
  8545. this.type = obj.type;
  8546. this.data = obj.data;
  8547. this.tagName = obj.tagName;
  8548. this.parentNode = obj.parentNode;
  8549. this.attrs = obj.attrs || {};
  8550. this.children = obj.children;
  8551. };
  8552. var notTransAttrs = {
  8553. 'href': 1,
  8554. 'src': 1,
  8555. '_src': 1,
  8556. '_href': 1,
  8557. 'cdata_data': 1
  8558. };
  8559. var notTransTagName = {
  8560. style: 1,
  8561. script: 1
  8562. };
  8563. var indentChar = ' ',
  8564. breakChar = '\n';
  8565. function insertLine(arr, current, begin) {
  8566. arr.push(breakChar);
  8567. return current + (begin ? 1 : -1);
  8568. }
  8569. function insertIndent(arr, current) {
  8570. //插入缩进
  8571. for (var i = 0; i < current; i++) {
  8572. arr.push(indentChar);
  8573. }
  8574. }
  8575. //创建uNode的静态方法
  8576. //支持标签和html
  8577. uNode.createElement = function (html) {
  8578. if (/[<>]/.test(html)) {
  8579. return UE.htmlparser(html).children[0]
  8580. } else {
  8581. return new uNode({
  8582. type: 'element',
  8583. children: [],
  8584. tagName: html
  8585. })
  8586. }
  8587. };
  8588. uNode.createText = function (data, noTrans) {
  8589. return new UE.uNode({
  8590. type: 'text',
  8591. 'data': noTrans ? data : utils.unhtml(data || '')
  8592. })
  8593. };
  8594. function nodeToHtml(node, arr, formatter, current) {
  8595. switch (node.type) {
  8596. case 'root':
  8597. for (var i = 0, ci; ci = node.children[i++];) {
  8598. //插入新行
  8599. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8600. insertLine(arr, current, true);
  8601. insertIndent(arr, current)
  8602. }
  8603. nodeToHtml(ci, arr, formatter, current)
  8604. }
  8605. break;
  8606. case 'text':
  8607. isText(node, arr);
  8608. break;
  8609. case 'element':
  8610. isElement(node, arr, formatter, current);
  8611. break;
  8612. case 'comment':
  8613. isComment(node, arr, formatter);
  8614. }
  8615. return arr;
  8616. }
  8617. function isText(node, arr) {
  8618. if (node.parentNode.tagName == 'pre') {
  8619. //源码模式下输入html标签,不能做转换处理,直接输出
  8620. arr.push(node.data)
  8621. } else {
  8622. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g, ' &nbsp;'))
  8623. }
  8624. }
  8625. function isElement(node, arr, formatter, current) {
  8626. var attrhtml = '';
  8627. if (node.attrs) {
  8628. attrhtml = [];
  8629. var attrs = node.attrs;
  8630. for (var a in attrs) {
  8631. //这里就针对
  8632. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8633. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8634. //有可能做的不够
  8635. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8636. return '&quot;'
  8637. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8638. }
  8639. attrhtml = attrhtml.join(' ');
  8640. }
  8641. arr.push('<' + node.tagName +
  8642. (attrhtml ? ' ' + attrhtml : '') +
  8643. (dtd.$empty[node.tagName] ? '\/' : '') + '>'
  8644. );
  8645. //插入新行
  8646. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8647. if (node.children && node.children.length) {
  8648. current = insertLine(arr, current, true);
  8649. insertIndent(arr, current)
  8650. }
  8651. }
  8652. if (node.children && node.children.length) {
  8653. for (var i = 0, ci; ci = node.children[i++];) {
  8654. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8655. insertLine(arr, current);
  8656. insertIndent(arr, current)
  8657. }
  8658. nodeToHtml(ci, arr, formatter, current)
  8659. }
  8660. }
  8661. if (!dtd.$empty[node.tagName]) {
  8662. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8663. if (node.children && node.children.length) {
  8664. current = insertLine(arr, current);
  8665. insertIndent(arr, current)
  8666. }
  8667. }
  8668. arr.push('<\/' + node.tagName + '>');
  8669. }
  8670. }
  8671. function isComment(node, arr) {
  8672. arr.push('<!--' + node.data + '-->');
  8673. }
  8674. function getNodeById(root, id) {
  8675. var node;
  8676. if (root.type == 'element' && root.getAttr('id') == id) {
  8677. return root;
  8678. }
  8679. if (root.children && root.children.length) {
  8680. for (var i = 0, ci; ci = root.children[i++];) {
  8681. if (node = getNodeById(ci, id)) {
  8682. return node;
  8683. }
  8684. }
  8685. }
  8686. }
  8687. function getNodesByTagName(node, tagName, arr) {
  8688. if (node.type == 'element' && node.tagName == tagName) {
  8689. arr.push(node);
  8690. }
  8691. if (node.children && node.children.length) {
  8692. for (var i = 0, ci; ci = node.children[i++];) {
  8693. getNodesByTagName(ci, tagName, arr)
  8694. }
  8695. }
  8696. }
  8697. function nodeTraversal(root, fn) {
  8698. if (root.children && root.children.length) {
  8699. for (var i = 0, ci; ci = root.children[i];) {
  8700. nodeTraversal(ci, fn);
  8701. //ci被替换的情况,这里就不再走 fn了
  8702. if (ci.parentNode) {
  8703. if (ci.children && ci.children.length) {
  8704. fn(ci)
  8705. }
  8706. if (ci.parentNode) i++
  8707. }
  8708. }
  8709. } else {
  8710. fn(root)
  8711. }
  8712. }
  8713. uNode.prototype = {
  8714. /**
  8715. * 当前节点对象,转换成html文本
  8716. * @method toHtml
  8717. * @return { String } 返回转换后的html字符串
  8718. * @example
  8719. * ```javascript
  8720. * node.toHtml();
  8721. * ```
  8722. */
  8723. /**
  8724. * 当前节点对象,转换成html文本
  8725. * @method toHtml
  8726. * @param { Boolean } formatter 是否格式化返回值
  8727. * @return { String } 返回转换后的html字符串
  8728. * @example
  8729. * ```javascript
  8730. * node.toHtml( true );
  8731. * ```
  8732. */
  8733. toHtml: function (formatter) {
  8734. var arr = [];
  8735. nodeToHtml(this, arr, formatter, 0);
  8736. return arr.join('')
  8737. },
  8738. /**
  8739. * 获取节点的html内容
  8740. * @method innerHTML
  8741. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8742. * @return { String } 返回节点的html内容
  8743. * @example
  8744. * ```javascript
  8745. * var htmlstr = node.innerHTML();
  8746. * ```
  8747. */
  8748. /**
  8749. * 设置节点的html内容
  8750. * @method innerHTML
  8751. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8752. * @param { String } htmlstr 传入要设置的html内容
  8753. * @return { UE.uNode } 返回节点本身
  8754. * @example
  8755. * ```javascript
  8756. * node.innerHTML('<span>text</span>');
  8757. * ```
  8758. */
  8759. innerHTML: function (htmlstr) {
  8760. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8761. return this;
  8762. }
  8763. if (utils.isString(htmlstr)) {
  8764. if (this.children) {
  8765. for (var i = 0, ci; ci = this.children[i++];) {
  8766. ci.parentNode = null;
  8767. }
  8768. }
  8769. this.children = [];
  8770. var tmpRoot = UE.htmlparser(htmlstr);
  8771. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8772. this.children.push(ci);
  8773. ci.parentNode = this;
  8774. }
  8775. return this;
  8776. } else {
  8777. var tmpRoot = new UE.uNode({
  8778. type: 'root',
  8779. children: this.children
  8780. });
  8781. return tmpRoot.toHtml();
  8782. }
  8783. },
  8784. /**
  8785. * 获取节点的纯文本内容
  8786. * @method innerText
  8787. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8788. * @return { String } 返回节点的存文本内容
  8789. * @example
  8790. * ```javascript
  8791. * var textStr = node.innerText();
  8792. * ```
  8793. */
  8794. /**
  8795. * 设置节点的纯文本内容
  8796. * @method innerText
  8797. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8798. * @param { String } textStr 传入要设置的文本内容
  8799. * @return { UE.uNode } 返回节点本身
  8800. * @example
  8801. * ```javascript
  8802. * node.innerText('<span>text</span>');
  8803. * ```
  8804. */
  8805. innerText: function (textStr, noTrans) {
  8806. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8807. return this;
  8808. }
  8809. if (textStr) {
  8810. if (this.children) {
  8811. for (var i = 0, ci; ci = this.children[i++];) {
  8812. ci.parentNode = null;
  8813. }
  8814. }
  8815. this.children = [];
  8816. this.appendChild(uNode.createText(textStr, noTrans));
  8817. return this;
  8818. } else {
  8819. return this.toHtml().replace(/<[^>]+>/g, '');
  8820. }
  8821. },
  8822. /**
  8823. * 获取当前对象的data属性
  8824. * @method getData
  8825. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8826. * @example
  8827. * ```javascript
  8828. * node.getData();
  8829. * ```
  8830. */
  8831. getData: function () {
  8832. if (this.type == 'element')
  8833. return '';
  8834. return this.data
  8835. },
  8836. /**
  8837. * 获取当前节点下的第一个子节点
  8838. * @method firstChild
  8839. * @return { UE.uNode } 返回第一个子节点
  8840. * @example
  8841. * ```javascript
  8842. * node.firstChild(); //返回第一个子节点
  8843. * ```
  8844. */
  8845. firstChild: function () {
  8846. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8847. // return this;
  8848. // }
  8849. return this.children ? this.children[0] : null;
  8850. },
  8851. /**
  8852. * 获取当前节点下的最后一个子节点
  8853. * @method lastChild
  8854. * @return { UE.uNode } 返回最后一个子节点
  8855. * @example
  8856. * ```javascript
  8857. * node.lastChild(); //返回最后一个子节点
  8858. * ```
  8859. */
  8860. lastChild: function () {
  8861. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8862. // return this;
  8863. // }
  8864. return this.children ? this.children[this.children.length - 1] : null;
  8865. },
  8866. /**
  8867. * 获取和当前节点有相同父亲节点的前一个节点
  8868. * @method previousSibling
  8869. * @return { UE.uNode } 返回前一个节点
  8870. * @example
  8871. * ```javascript
  8872. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8873. * ```
  8874. */
  8875. previousSibling: function () {
  8876. var parent = this.parentNode;
  8877. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8878. if (ci === this) {
  8879. return i == 0 ? null : parent.children[i - 1];
  8880. }
  8881. }
  8882. },
  8883. /**
  8884. * 获取和当前节点有相同父亲节点的后一个节点
  8885. * @method nextSibling
  8886. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8887. * @example
  8888. * ```javascript
  8889. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8890. * ```
  8891. */
  8892. nextSibling: function () {
  8893. var parent = this.parentNode;
  8894. for (var i = 0, ci; ci = parent.children[i++];) {
  8895. if (ci === this) {
  8896. return parent.children[i];
  8897. }
  8898. }
  8899. },
  8900. /**
  8901. * 用新的节点替换当前节点
  8902. * @method replaceChild
  8903. * @param { UE.uNode } target 要替换成该节点参数
  8904. * @param { UE.uNode } source 要被替换掉的节点
  8905. * @return { UE.uNode } 返回替换之后的节点对象
  8906. * @example
  8907. * ```javascript
  8908. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8909. * ```
  8910. */
  8911. replaceChild: function (target, source) {
  8912. if (this.children) {
  8913. if (target.parentNode) {
  8914. target.parentNode.removeChild(target);
  8915. }
  8916. for (var i = 0, ci; ci = this.children[i]; i++) {
  8917. if (ci === source) {
  8918. this.children.splice(i, 1, target);
  8919. source.parentNode = null;
  8920. target.parentNode = this;
  8921. return target;
  8922. }
  8923. }
  8924. }
  8925. },
  8926. /**
  8927. * 在节点的子节点列表最后位置插入一个节点
  8928. * @method appendChild
  8929. * @param { UE.uNode } node 要插入的节点
  8930. * @return { UE.uNode } 返回刚插入的子节点
  8931. * @example
  8932. * ```javascript
  8933. * node.appendChild( newNode ); //在node内插入子节点newNode
  8934. * ```
  8935. */
  8936. appendChild: function (node) {
  8937. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8938. if (!this.children) {
  8939. this.children = []
  8940. }
  8941. if (node.parentNode) {
  8942. node.parentNode.removeChild(node);
  8943. }
  8944. for (var i = 0, ci; ci = this.children[i]; i++) {
  8945. if (ci === node) {
  8946. this.children.splice(i, 1);
  8947. break;
  8948. }
  8949. }
  8950. this.children.push(node);
  8951. node.parentNode = this;
  8952. return node;
  8953. }
  8954. },
  8955. /**
  8956. * 在传入节点的前面插入一个节点
  8957. * @method insertBefore
  8958. * @param { UE.uNode } target 要插入的节点
  8959. * @param { UE.uNode } source 在该参数节点前面插入
  8960. * @return { UE.uNode } 返回刚插入的子节点
  8961. * @example
  8962. * ```javascript
  8963. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8964. * ```
  8965. */
  8966. insertBefore: function (target, source) {
  8967. if (this.children) {
  8968. if (target.parentNode) {
  8969. target.parentNode.removeChild(target);
  8970. }
  8971. for (var i = 0, ci; ci = this.children[i]; i++) {
  8972. if (ci === source) {
  8973. this.children.splice(i, 0, target);
  8974. target.parentNode = this;
  8975. return target;
  8976. }
  8977. }
  8978. }
  8979. },
  8980. /**
  8981. * 在传入节点的后面插入一个节点
  8982. * @method insertAfter
  8983. * @param { UE.uNode } target 要插入的节点
  8984. * @param { UE.uNode } source 在该参数节点后面插入
  8985. * @return { UE.uNode } 返回刚插入的子节点
  8986. * @example
  8987. * ```javascript
  8988. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8989. * ```
  8990. */
  8991. insertAfter: function (target, source) {
  8992. if (this.children) {
  8993. if (target.parentNode) {
  8994. target.parentNode.removeChild(target);
  8995. }
  8996. for (var i = 0, ci; ci = this.children[i]; i++) {
  8997. if (ci === source) {
  8998. this.children.splice(i + 1, 0, target);
  8999. target.parentNode = this;
  9000. return target;
  9001. }
  9002. }
  9003. }
  9004. },
  9005. /**
  9006. * 从当前节点的子节点列表中,移除节点
  9007. * @method removeChild
  9008. * @param { UE.uNode } node 要移除的节点引用
  9009. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  9010. * @return { * } 返回刚移除的子节点
  9011. * @example
  9012. * ```javascript
  9013. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  9014. * ```
  9015. */
  9016. removeChild: function (node, keepChildren) {
  9017. if (this.children) {
  9018. for (var i = 0, ci; ci = this.children[i]; i++) {
  9019. if (ci === node) {
  9020. this.children.splice(i, 1);
  9021. ci.parentNode = null;
  9022. if (keepChildren && ci.children && ci.children.length) {
  9023. for (var j = 0, cj; cj = ci.children[j]; j++) {
  9024. this.children.splice(i + j, 0, cj);
  9025. cj.parentNode = this;
  9026. }
  9027. }
  9028. return ci;
  9029. }
  9030. }
  9031. }
  9032. },
  9033. /**
  9034. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  9035. * @method getAttr
  9036. * @param { String } attrName 要获取的属性名称
  9037. * @return { * } 返回attrs对象下的属性值
  9038. * @example
  9039. * ```javascript
  9040. * node.getAttr('title');
  9041. * ```
  9042. */
  9043. getAttr: function (attrName) {
  9044. return this.attrs && this.attrs[attrName.toLowerCase()]
  9045. },
  9046. /**
  9047. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  9048. * @method setAttr
  9049. * @param { String } attrName 要设置的属性名称
  9050. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  9051. * @return { * } 返回attrs对象下的属性值
  9052. * @example
  9053. * ```javascript
  9054. * node.setAttr('title','标题');
  9055. * ```
  9056. */
  9057. setAttr: function (attrName, attrVal) {
  9058. if (!attrName) {
  9059. delete this.attrs;
  9060. return;
  9061. }
  9062. if (!this.attrs) {
  9063. this.attrs = {};
  9064. }
  9065. if (utils.isObject(attrName)) {
  9066. for (var a in attrName) {
  9067. if (!attrName[a]) {
  9068. delete this.attrs[a]
  9069. } else {
  9070. this.attrs[a.toLowerCase()] = attrName[a];
  9071. }
  9072. }
  9073. } else {
  9074. if (!attrVal) {
  9075. delete this.attrs[attrName]
  9076. } else {
  9077. this.attrs[attrName.toLowerCase()] = attrVal;
  9078. }
  9079. }
  9080. },
  9081. /**
  9082. * 获取当前节点在父节点下的位置索引
  9083. * @method getIndex
  9084. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  9085. * @example
  9086. * ```javascript
  9087. * node.getIndex();
  9088. * ```
  9089. */
  9090. getIndex: function () {
  9091. var parent = this.parentNode;
  9092. for (var i = 0, ci; ci = parent.children[i]; i++) {
  9093. if (ci === this) {
  9094. return i;
  9095. }
  9096. }
  9097. return -1;
  9098. },
  9099. /**
  9100. * 在当前节点下,根据id查找节点
  9101. * @method getNodeById
  9102. * @param { String } id 要查找的id
  9103. * @return { UE.uNode } 返回找到的节点
  9104. * @example
  9105. * ```javascript
  9106. * node.getNodeById('textId');
  9107. * ```
  9108. */
  9109. getNodeById: function (id) {
  9110. var node;
  9111. if (this.children && this.children.length) {
  9112. for (var i = 0, ci; ci = this.children[i++];) {
  9113. if (node = getNodeById(ci, id)) {
  9114. return node;
  9115. }
  9116. }
  9117. }
  9118. },
  9119. /**
  9120. * 在当前节点下,根据元素名称查找节点列表
  9121. * @method getNodesByTagName
  9122. * @param { String } tagNames 要查找的元素名称
  9123. * @return { Array } 返回找到的节点列表
  9124. * @example
  9125. * ```javascript
  9126. * node.getNodesByTagName('span');
  9127. * ```
  9128. */
  9129. getNodesByTagName: function (tagNames) {
  9130. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  9131. var arr = [], me = this;
  9132. utils.each(tagNames, function (tagName) {
  9133. if (me.children && me.children.length) {
  9134. for (var i = 0, ci; ci = me.children[i++];) {
  9135. getNodesByTagName(ci, tagName, arr)
  9136. }
  9137. }
  9138. });
  9139. return arr;
  9140. },
  9141. /**
  9142. * 根据样式名称,获取节点的样式值
  9143. * @method getStyle
  9144. * @param { String } name 要获取的样式名称
  9145. * @return { String } 返回样式值
  9146. * @example
  9147. * ```javascript
  9148. * node.getStyle('font-size');
  9149. * ```
  9150. */
  9151. getStyle: function (name) {
  9152. var cssStyle = this.getAttr('style');
  9153. if (!cssStyle) {
  9154. return ''
  9155. }
  9156. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)', 'i');
  9157. var match = cssStyle.match(reg);
  9158. if (match && match[0]) {
  9159. return match[2]
  9160. }
  9161. return '';
  9162. },
  9163. /**
  9164. * 给节点设置样式
  9165. * @method setStyle
  9166. * @param { String } name 要设置的的样式名称
  9167. * @param { String } val 要设置的的样值
  9168. * @example
  9169. * ```javascript
  9170. * node.setStyle('font-size', '12px');
  9171. * ```
  9172. */
  9173. setStyle: function (name, val) {
  9174. function exec(name, val) {
  9175. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  9176. cssStyle = cssStyle.replace(reg, '$1');
  9177. if (val) {
  9178. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  9179. }
  9180. }
  9181. var cssStyle = this.getAttr('style');
  9182. if (!cssStyle) {
  9183. cssStyle = '';
  9184. }
  9185. if (utils.isObject(name)) {
  9186. for (var a in name) {
  9187. exec(a, name[a])
  9188. }
  9189. } else {
  9190. exec(name, val)
  9191. }
  9192. this.setAttr('style', utils.trim(cssStyle))
  9193. },
  9194. /**
  9195. * 传入一个函数,递归遍历当前节点下的所有节点
  9196. * @method traversal
  9197. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  9198. * @example
  9199. * ```javascript
  9200. * traversal(node, function(){
  9201. * console.log(node.type);
  9202. * });
  9203. * ```
  9204. */
  9205. traversal: function (fn) {
  9206. if (this.children && this.children.length) {
  9207. nodeTraversal(this, fn);
  9208. }
  9209. return this;
  9210. }
  9211. }
  9212. })();
  9213. // core/htmlparser.js
  9214. /**
  9215. * html字符串转换成uNode节点
  9216. * @file
  9217. * @module UE
  9218. * @since 1.2.6.1
  9219. */
  9220. /**
  9221. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9222. * @unfile
  9223. * @module UE
  9224. */
  9225. /**
  9226. * html字符串转换成uNode节点的静态方法
  9227. * @method htmlparser
  9228. * @param { String } htmlstr 要转换的html代码
  9229. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  9230. * @return { uNode } 给定的html片段转换形成的uNode对象
  9231. * @example
  9232. * ```javascript
  9233. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  9234. * ```
  9235. */
  9236. var htmlparser = UE.htmlparser = function(htmlstr, ignoreBlank) {
  9237. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  9238. //先去掉了,加上的原因忘了,这里先记录
  9239. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  9240. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  9241. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  9242. var allowEmptyTags = {
  9243. b: 1, code: 1, i: 1, u: 1, strike: 1, s: 1, tt: 1, strong: 1, q: 1, samp: 1, em: 1, span: 1,
  9244. sub: 1, img: 1, sup: 1, font: 1, big: 1, small: 1, iframe: 1, a: 1, br: 1, pre: 1
  9245. };
  9246. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  9247. if (!ignoreBlank) {
  9248. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n' + (ignoreBlank ? '' : ' ') + ']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n' + (ignoreBlank ? '' : ' ') + ']*', 'g'), function (a, b) {
  9249. //br暂时单独处理
  9250. if (b && allowEmptyTags[b.toLowerCase()]) {
  9251. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g, '');
  9252. }
  9253. return a.replace(new RegExp('^[\\r\\n' + (ignoreBlank ? '' : ' ') + ']+'), '').replace(new RegExp('[\\r\\n' + (ignoreBlank ? '' : ' ') + ']+$'), '');
  9254. });
  9255. }
  9256. var notTransAttrs = {
  9257. 'href': 1,
  9258. 'src': 1
  9259. };
  9260. var uNode = UE.uNode,
  9261. needParentNode = {
  9262. 'td': 'tr',
  9263. 'tr': ['tbody', 'thead', 'tfoot'],
  9264. 'tbody': 'table',
  9265. 'th': 'tr',
  9266. 'thead': 'table',
  9267. 'tfoot': 'table',
  9268. 'caption': 'table',
  9269. 'li': ['ul', 'ol'],
  9270. 'dt': 'dl',
  9271. 'dd': 'dl',
  9272. 'option': 'select'
  9273. },
  9274. needChild = {
  9275. 'ol': 'li',
  9276. 'ul': 'li'
  9277. };
  9278. function text(parent, data) {
  9279. if (needChild[parent.tagName]) {
  9280. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  9281. parent.appendChild(tmpNode);
  9282. tmpNode.appendChild(uNode.createText(data));
  9283. parent = tmpNode;
  9284. } else {
  9285. parent.appendChild(uNode.createText(data));
  9286. }
  9287. }
  9288. function element(parent, tagName, htmlattr) {
  9289. var needParentTag;
  9290. if (needParentTag = needParentNode[tagName]) {
  9291. var tmpParent = parent, hasParent;
  9292. while (tmpParent.type != 'root') {
  9293. if (utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName) {
  9294. parent = tmpParent;
  9295. hasParent = true;
  9296. break;
  9297. }
  9298. tmpParent = tmpParent.parentNode;
  9299. }
  9300. if (!hasParent) {
  9301. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  9302. }
  9303. }
  9304. //按dtd处理嵌套
  9305. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  9306. // parent = parent.parentNode;
  9307. var elm = new uNode({
  9308. parentNode: parent,
  9309. type: 'element',
  9310. tagName: tagName.toLowerCase(),
  9311. //是自闭合的处理一下
  9312. children: dtd.$empty[tagName] ? null : []
  9313. });
  9314. //如果属性存在,处理属性
  9315. if (htmlattr) {
  9316. var attrs = {}, match;
  9317. while (match = re_attr.exec(htmlattr)) {
  9318. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  9319. }
  9320. elm.attrs = attrs;
  9321. }
  9322. //trace:3970
  9323. // //如果parent下不能放elm
  9324. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  9325. // parent = parent.parentNode;
  9326. // elm.parentNode = parent;
  9327. // }
  9328. parent.children.push(elm);
  9329. //如果是自闭合节点返回父亲节点
  9330. return dtd.$empty[tagName] ? parent : elm
  9331. }
  9332. function comment(parent, data) {
  9333. parent.children.push(new uNode({
  9334. type: 'comment',
  9335. data: data,
  9336. parentNode: parent
  9337. }));
  9338. }
  9339. var match, currentIndex = 0, nextIndex = 0;
  9340. //设置根节点
  9341. var root = new uNode({
  9342. type: 'root',
  9343. children: []
  9344. });
  9345. var currentParent = root;
  9346. while (match = re_tag.exec(htmlstr)) {
  9347. currentIndex = match.index;
  9348. try {
  9349. if (currentIndex > nextIndex) {
  9350. //text node
  9351. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  9352. }
  9353. if (match[3]) {
  9354. if (dtd.$cdata[currentParent.tagName]) {
  9355. text(currentParent, match[0]);
  9356. } else {
  9357. //start tag
  9358. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  9359. }
  9360. } else if (match[1]) {
  9361. if (currentParent.type != 'root') {
  9362. if (dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]) {
  9363. text(currentParent, match[0]);
  9364. } else {
  9365. var tmpParent = currentParent;
  9366. while (currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()) {
  9367. currentParent = currentParent.parentNode;
  9368. if (currentParent.type == 'root') {
  9369. currentParent = tmpParent;
  9370. throw 'break'
  9371. }
  9372. }
  9373. //end tag
  9374. currentParent = currentParent.parentNode;
  9375. }
  9376. }
  9377. } else if (match[2]) {
  9378. //comment
  9379. comment(currentParent, match[2])
  9380. }
  9381. } catch (e) {
  9382. }
  9383. nextIndex = re_tag.lastIndex;
  9384. }
  9385. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9386. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9387. if (nextIndex < htmlstr.length) {
  9388. text(currentParent, htmlstr.slice(nextIndex));
  9389. }
  9390. return root;
  9391. };
  9392. // core/filternode.js
  9393. /**
  9394. * UE过滤节点的静态方法
  9395. * @file
  9396. */
  9397. /**
  9398. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9399. * @module UE
  9400. */
  9401. /**
  9402. * 根据传入节点和过滤规则过滤相应节点
  9403. * @module UE
  9404. * @since 1.2.6.1
  9405. * @method filterNode
  9406. * @param { Object } root 指定root节点
  9407. * @param { Object } rules 过滤规则json对象
  9408. * @example
  9409. * ```javascript
  9410. * UE.filterNode(root,editor.options.filterRules);
  9411. * ```
  9412. */
  9413. var filterNode = UE.filterNode = function () {
  9414. function filterNode(node, rules) {
  9415. switch (node.type) {
  9416. case 'text':
  9417. break;
  9418. case 'element':
  9419. var val;
  9420. if (val = rules[node.tagName]) {
  9421. if (val === '-') {
  9422. node.parentNode.removeChild(node)
  9423. } else if (utils.isFunction(val)) {
  9424. var parentNode = node.parentNode,
  9425. index = node.getIndex();
  9426. val(node);
  9427. if (node.parentNode) {
  9428. if (node.children) {
  9429. for (var i = 0, ci; ci = node.children[i];) {
  9430. filterNode(ci, rules);
  9431. if (ci.parentNode) {
  9432. i++;
  9433. }
  9434. }
  9435. }
  9436. } else {
  9437. for (var i = index, ci; ci = parentNode.children[i];) {
  9438. filterNode(ci, rules);
  9439. if (ci.parentNode) {
  9440. i++;
  9441. }
  9442. }
  9443. }
  9444. } else {
  9445. var attrs = val['$'];
  9446. if (attrs && node.attrs) {
  9447. var tmpAttrs = {}, tmpVal;
  9448. for (var a in attrs) {
  9449. tmpVal = node.getAttr(a);
  9450. //todo 只先对style单独处理
  9451. if (a == 'style' && utils.isArray(attrs[a])) {
  9452. var tmpCssStyle = [];
  9453. utils.each(attrs[a], function (v) {
  9454. var tmp;
  9455. if (tmp = node.getStyle(v)) {
  9456. tmpCssStyle.push(v + ':' + tmp);
  9457. }
  9458. });
  9459. tmpVal = tmpCssStyle.join(';')
  9460. }
  9461. if (tmpVal) {
  9462. tmpAttrs[a] = tmpVal;
  9463. }
  9464. }
  9465. node.attrs = tmpAttrs;
  9466. }
  9467. if (node.children) {
  9468. for (var i = 0, ci; ci = node.children[i];) {
  9469. filterNode(ci, rules);
  9470. if (ci.parentNode) {
  9471. i++;
  9472. }
  9473. }
  9474. }
  9475. }
  9476. } else {
  9477. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9478. if (dtd.$cdata[node.tagName]) {
  9479. node.parentNode.removeChild(node)
  9480. } else {
  9481. var parentNode = node.parentNode,
  9482. index = node.getIndex();
  9483. node.parentNode.removeChild(node, true);
  9484. for (var i = index, ci; ci = parentNode.children[i];) {
  9485. filterNode(ci, rules);
  9486. if (ci.parentNode) {
  9487. i++;
  9488. }
  9489. }
  9490. }
  9491. }
  9492. break;
  9493. case 'comment':
  9494. node.parentNode.removeChild(node)
  9495. }
  9496. }
  9497. return function (root, rules) {
  9498. if (utils.isEmptyObject(rules)) {
  9499. return root;
  9500. }
  9501. var val;
  9502. if (val = rules['-']) {
  9503. utils.each(val.split(' '), function (k) {
  9504. rules[k] = '-'
  9505. })
  9506. }
  9507. for (var i = 0, ci; ci = root.children[i];) {
  9508. filterNode(ci, rules);
  9509. if (ci.parentNode) {
  9510. i++;
  9511. }
  9512. }
  9513. return root;
  9514. }
  9515. }();
  9516. // core/plugin.js
  9517. /**
  9518. * Created with JetBrains PhpStorm.
  9519. * User: campaign
  9520. * Date: 10/8/13
  9521. * Time: 6:15 PM
  9522. * To change this template use File | Settings | File Templates.
  9523. */
  9524. UE.plugin = function () {
  9525. var _plugins = {};
  9526. return {
  9527. register: function (pluginName, fn, oldOptionName, afterDisabled) {
  9528. if (oldOptionName && utils.isFunction(oldOptionName)) {
  9529. afterDisabled = oldOptionName;
  9530. oldOptionName = null
  9531. }
  9532. _plugins[pluginName] = {
  9533. optionName: oldOptionName || pluginName,
  9534. execFn: fn,
  9535. //当插件被禁用时执行
  9536. afterDisabled: afterDisabled
  9537. }
  9538. },
  9539. load: function (editor) {
  9540. utils.each(_plugins, function (plugin) {
  9541. var _export = plugin.execFn.call(editor);
  9542. if (editor.options[plugin.optionName] !== false) {
  9543. if (_export) {
  9544. //后边需要再做扩展
  9545. utils.each(_export, function (v, k) {
  9546. switch (k.toLowerCase()) {
  9547. case 'shortcutkey':
  9548. editor.addshortcutkey(v);
  9549. break;
  9550. case 'bindevents':
  9551. utils.each(v, function (fn, eventName) {
  9552. editor.addListener(eventName, fn);
  9553. });
  9554. break;
  9555. case 'bindmultievents':
  9556. utils.each(utils.isArray(v) ? v : [v], function (event) {
  9557. var types = utils.trim(event.type).split(/\s+/);
  9558. utils.each(types, function (eventName) {
  9559. editor.addListener(eventName, event.handler);
  9560. });
  9561. });
  9562. break;
  9563. case 'commands':
  9564. utils.each(v, function (execFn, execName) {
  9565. editor.commands[execName] = execFn
  9566. });
  9567. break;
  9568. case 'outputrule':
  9569. editor.addOutputRule(v);
  9570. break;
  9571. case 'inputrule':
  9572. editor.addInputRule(v);
  9573. break;
  9574. case 'defaultoptions':
  9575. editor.setOpt(v)
  9576. }
  9577. })
  9578. }
  9579. } else if (plugin.afterDisabled) {
  9580. plugin.afterDisabled.call(editor)
  9581. }
  9582. });
  9583. //向下兼容
  9584. utils.each(UE.plugins, function (plugin) {
  9585. plugin.call(editor);
  9586. });
  9587. },
  9588. run: function (pluginName, editor) {
  9589. var plugin = _plugins[pluginName];
  9590. if (plugin) {
  9591. plugin.exeFn.call(editor)
  9592. }
  9593. }
  9594. }
  9595. }();
  9596. // core/keymap.js
  9597. var keymap = UE.keymap = {
  9598. 'Backspace': 8,
  9599. 'Tab': 9,
  9600. 'Enter': 13,
  9601. 'Shift': 16,
  9602. 'Control': 17,
  9603. 'Alt': 18,
  9604. 'CapsLock': 20,
  9605. 'Esc': 27,
  9606. 'Spacebar': 32,
  9607. 'PageUp': 33,
  9608. 'PageDown': 34,
  9609. 'End': 35,
  9610. 'Home': 36,
  9611. 'Left': 37,
  9612. 'Up': 38,
  9613. 'Right': 39,
  9614. 'Down': 40,
  9615. 'Insert': 45,
  9616. 'Del': 46,
  9617. 'NumLock': 144,
  9618. 'Cmd': 91,
  9619. '=': 187,
  9620. '-': 189,
  9621. "b": 66,
  9622. 'i': 73,
  9623. //回退
  9624. 'z': 90,
  9625. 'y': 89,
  9626. //粘贴
  9627. 'v': 86,
  9628. 'x': 88,
  9629. 's': 83,
  9630. 'n': 78
  9631. };
  9632. // core/localstorage.js
  9633. //存储媒介封装
  9634. var LocalStorage = UE.LocalStorage = (function () {
  9635. var storage = window.localStorage || getUserData() || null,
  9636. LOCAL_FILE = 'localStorage';
  9637. return {
  9638. saveLocalData: function (key, data) {
  9639. if (storage && data) {
  9640. storage.setItem(key, data);
  9641. return true;
  9642. }
  9643. return false;
  9644. },
  9645. getLocalData: function (key) {
  9646. if (storage) {
  9647. return storage.getItem(key);
  9648. }
  9649. return null;
  9650. },
  9651. removeItem: function (key) {
  9652. storage && storage.removeItem(key);
  9653. }
  9654. };
  9655. function getUserData() {
  9656. var container = document.createElement("div");
  9657. container.style.display = "none";
  9658. if (!container.addBehavior) {
  9659. return null;
  9660. }
  9661. container.addBehavior("#default#userdata");
  9662. return {
  9663. getItem: function (key) {
  9664. var result = null;
  9665. try {
  9666. document.body.appendChild(container);
  9667. container.load(LOCAL_FILE);
  9668. result = container.getAttribute(key);
  9669. document.body.removeChild(container);
  9670. } catch (e) {
  9671. }
  9672. return result;
  9673. },
  9674. setItem: function (key, value) {
  9675. document.body.appendChild(container);
  9676. container.setAttribute(key, value);
  9677. container.save(LOCAL_FILE);
  9678. document.body.removeChild(container);
  9679. },
  9680. //// 暂时没有用到
  9681. //clear: function () {
  9682. //
  9683. // var expiresTime = new Date();
  9684. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9685. // document.body.appendChild(container);
  9686. // container.expires = expiresTime.toUTCString();
  9687. // container.save(LOCAL_FILE);
  9688. // document.body.removeChild(container);
  9689. //
  9690. //},
  9691. removeItem: function (key) {
  9692. document.body.appendChild(container);
  9693. container.removeAttribute(key);
  9694. container.save(LOCAL_FILE);
  9695. document.body.removeChild(container);
  9696. }
  9697. };
  9698. }
  9699. })();
  9700. (function () {
  9701. var ROOTKEY = 'ueditor_preference';
  9702. UE.Editor.prototype.setPreferences = function (key, value) {
  9703. var obj = {};
  9704. if (utils.isString(key)) {
  9705. obj[key] = value;
  9706. } else {
  9707. obj = key;
  9708. }
  9709. var data = LocalStorage.getLocalData(ROOTKEY);
  9710. if (data && (data = utils.str2json(data))) {
  9711. utils.extend(data, obj);
  9712. } else {
  9713. data = obj;
  9714. }
  9715. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9716. };
  9717. UE.Editor.prototype.getPreferences = function (key) {
  9718. var data = LocalStorage.getLocalData(ROOTKEY);
  9719. if (data && (data = utils.str2json(data))) {
  9720. return key ? data[key] : data
  9721. }
  9722. return null;
  9723. };
  9724. UE.Editor.prototype.removePreferences = function (key) {
  9725. var data = LocalStorage.getLocalData(ROOTKEY);
  9726. if (data && (data = utils.str2json(data))) {
  9727. data[key] = undefined;
  9728. delete data[key]
  9729. }
  9730. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9731. };
  9732. })();
  9733. // plugins/defaultfilter.js
  9734. ///import core
  9735. ///plugin 编辑器默认的过滤转换机制
  9736. UE.plugins['defaultfilter'] = function () {
  9737. var me = this;
  9738. me.setOpt({
  9739. 'allowDivTransToP': true,
  9740. 'disabledTableInTable': true
  9741. });
  9742. //默认的过滤处理
  9743. //进入编辑器的内容处理
  9744. me.addInputRule(function (root) {
  9745. var allowDivTransToP = this.options.allowDivTransToP;
  9746. var val;
  9747. function tdParent(node) {
  9748. while (node && node.type == 'element') {
  9749. if (node.tagName == 'td') {
  9750. return true;
  9751. }
  9752. node = node.parentNode;
  9753. }
  9754. return false;
  9755. }
  9756. //进行默认的处理
  9757. root.traversal(function (node) {
  9758. if (node.type == 'element') {
  9759. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9760. if (!node.firstChild()) node.parentNode.removeChild(node);
  9761. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9762. node.parentNode.removeChild(node, true)
  9763. }
  9764. return;
  9765. }
  9766. switch (node.tagName) {
  9767. case 'style':
  9768. case 'script':
  9769. node.setAttr({
  9770. cdata_tag: node.tagName,
  9771. cdata_data: (node.innerHTML() || ''),
  9772. '_ue_custom_node_': 'true'
  9773. });
  9774. node.tagName = 'div';
  9775. node.innerHTML('');
  9776. break;
  9777. case 'a':
  9778. if (val = node.getAttr('href')) {
  9779. node.setAttr('_href', val)
  9780. }
  9781. break;
  9782. case 'img':
  9783. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9784. if (val = node.getAttr('src')) {
  9785. if (/^data:/.test(val)) {
  9786. node.parentNode.removeChild(node);
  9787. break;
  9788. }
  9789. }
  9790. node.setAttr('_src', node.getAttr('src'));
  9791. break;
  9792. case 'span':
  9793. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9794. if (/nowrap|normal/.test(val)) {
  9795. node.setStyle('white-space', '');
  9796. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9797. node.parentNode.removeChild(node, true)
  9798. }
  9799. }
  9800. }
  9801. val = node.getAttr('id');
  9802. if (val && /^_baidu_bookmark_/i.test(val)) {
  9803. node.parentNode.removeChild(node)
  9804. }
  9805. break;
  9806. case 'p':
  9807. if (val = node.getAttr('align')) {
  9808. node.setAttr('align');
  9809. node.setStyle('text-align', val)
  9810. }
  9811. //trace:3431
  9812. // var cssStyle = node.getAttr('style');
  9813. // if (cssStyle) {
  9814. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9815. // node.setAttr('style', cssStyle)
  9816. //
  9817. // }
  9818. //p标签不允许嵌套
  9819. utils.each(node.children, function (n) {
  9820. if (n.type == 'element' && n.tagName == 'p') {
  9821. var next = n.nextSibling();
  9822. node.parentNode.insertAfter(n, node);
  9823. var last = n;
  9824. while (next) {
  9825. var tmp = next.nextSibling();
  9826. node.parentNode.insertAfter(next, last);
  9827. last = next;
  9828. next = tmp;
  9829. }
  9830. return false;
  9831. }
  9832. });
  9833. if (!node.firstChild()) {
  9834. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9835. }
  9836. break;
  9837. case 'div':
  9838. if (node.getAttr('cdata_tag')) {
  9839. break;
  9840. }
  9841. //针对代码这里不处理插入代码的div
  9842. val = node.getAttr('class');
  9843. if (val && /^line number\d+/.test(val)) {
  9844. break;
  9845. }
  9846. if (!allowDivTransToP) {
  9847. break;
  9848. }
  9849. var tmpNode, p = UE.uNode.createElement('p');
  9850. while (tmpNode = node.firstChild()) {
  9851. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9852. p.appendChild(tmpNode);
  9853. } else {
  9854. if (p.firstChild()) {
  9855. node.parentNode.insertBefore(p, node);
  9856. p = UE.uNode.createElement('p');
  9857. } else {
  9858. node.parentNode.insertBefore(tmpNode, node);
  9859. }
  9860. }
  9861. }
  9862. if (p.firstChild()) {
  9863. node.parentNode.insertBefore(p, node);
  9864. }
  9865. node.parentNode.removeChild(node);
  9866. break;
  9867. case 'dl':
  9868. node.tagName = 'ul';
  9869. break;
  9870. case 'dt':
  9871. case 'dd':
  9872. node.tagName = 'li';
  9873. break;
  9874. case 'li':
  9875. var className = node.getAttr('class');
  9876. if (!className || !/list\-/.test(className)) {
  9877. node.setAttr()
  9878. }
  9879. var tmpNodes = node.getNodesByTagName('ol ul');
  9880. UE.utils.each(tmpNodes, function (n) {
  9881. node.parentNode.insertAfter(n, node);
  9882. });
  9883. break;
  9884. case 'td':
  9885. case 'th':
  9886. case 'caption':
  9887. if (!node.children || !node.children.length) {
  9888. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9889. }
  9890. break;
  9891. case 'table':
  9892. if (me.options.disabledTableInTable && tdParent(node)) {
  9893. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()), node);
  9894. node.parentNode.removeChild(node)
  9895. }
  9896. }
  9897. }
  9898. // if(node.type == 'comment'){
  9899. // node.parentNode.removeChild(node);
  9900. // }
  9901. })
  9902. });
  9903. //从编辑器出去的内容处理
  9904. me.addOutputRule(function(root) {
  9905. var val;
  9906. root.traversal(function(node) {
  9907. if (node.type == 'element') {
  9908. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9909. if (!node.firstChild()) node.parentNode.removeChild(node);
  9910. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9911. node.parentNode.removeChild(node, true)
  9912. }
  9913. return;
  9914. }
  9915. switch (node.tagName) {
  9916. case 'div':
  9917. if (val = node.getAttr('cdata_tag')) {
  9918. node.tagName = val;
  9919. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9920. node.setAttr({cdata_tag: '', cdata_data: '', '_ue_custom_node_': ''});
  9921. }
  9922. break;
  9923. case 'a':
  9924. if (val = node.getAttr('_href')) {
  9925. node.setAttr({
  9926. 'href': utils.html(val),
  9927. '_href': ''
  9928. })
  9929. }
  9930. break;
  9931. break;
  9932. case 'span':
  9933. val = node.getAttr('id');
  9934. if (val && /^_baidu_bookmark_/i.test(val)) {
  9935. node.parentNode.removeChild(node)
  9936. }
  9937. break;
  9938. case 'img':
  9939. if (val = node.getAttr('_src')) {
  9940. node.setAttr({
  9941. 'src': node.getAttr('_src'),
  9942. '_src': ''
  9943. })
  9944. }
  9945. }
  9946. }
  9947. })
  9948. });
  9949. };
  9950. // plugins/inserthtml.js
  9951. /**
  9952. * 插入html字符串插件
  9953. * @file
  9954. * @since 1.2.6.1
  9955. */
  9956. /**
  9957. * 插入html代码
  9958. * @command inserthtml
  9959. * @method execCommand
  9960. * @param { String } cmd 命令字符串
  9961. * @param { String } html 插入的html字符串
  9962. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9963. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9964. * @example
  9965. * ```javascript
  9966. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9967. * //执行命令,插入<b>CC</b>
  9968. * //插入后的效果 xxx<b>CC</b>xxx
  9969. * //<p>xx|xxx</p> 当前选区为闭合状态
  9970. * //插入<p>CC</p>
  9971. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9972. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9973. * //插入 xxxx
  9974. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9975. * ```
  9976. */
  9977. UE.commands['inserthtml'] = {
  9978. execCommand: function (command, html, notNeedFilter) {
  9979. var me = this,
  9980. range,
  9981. div;
  9982. if (!html) {
  9983. return;
  9984. }
  9985. if (me.fireEvent('beforeinserthtml', html) === true) {
  9986. return;
  9987. }
  9988. range = me.selection.getRange();
  9989. div = range.document.createElement('div');
  9990. div.style.display = 'inline';
  9991. if (!notNeedFilter) {
  9992. var root = UE.htmlparser(html);
  9993. //如果给了过滤规则就先进行过滤
  9994. if (me.options.filterRules) {
  9995. UE.filterNode(root, me.options.filterRules);
  9996. }
  9997. //执行默认的处理
  9998. me.filterInputRule(root);
  9999. html = root.toHtml()
  10000. }
  10001. div.innerHTML = utils.trim(html);
  10002. if (!range.collapsed) {
  10003. var tmpNode = range.startContainer;
  10004. if (domUtils.isFillChar(tmpNode)) {
  10005. range.setStartBefore(tmpNode)
  10006. }
  10007. tmpNode = range.endContainer;
  10008. if (domUtils.isFillChar(tmpNode)) {
  10009. range.setEndAfter(tmpNode)
  10010. }
  10011. range.txtToElmBoundary();
  10012. //结束边界可能放到了br的前边,要把br包含进来
  10013. // x[xxx]<br/>
  10014. if (range.endContainer && range.endContainer.nodeType == 1) {
  10015. tmpNode = range.endContainer.childNodes[range.endOffset];
  10016. if (tmpNode && domUtils.isBr(tmpNode)) {
  10017. range.setEndAfter(tmpNode);
  10018. }
  10019. }
  10020. if (range.startOffset == 0) {
  10021. tmpNode = range.startContainer;
  10022. if (domUtils.isBoundaryNode(tmpNode, 'firstChild')) {
  10023. tmpNode = range.endContainer;
  10024. if (range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode, 'lastChild')) {
  10025. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  10026. range.setStart(me.body.firstChild, 0).collapse(true)
  10027. }
  10028. }
  10029. }
  10030. !range.collapsed && range.deleteContents();
  10031. if (range.startContainer.nodeType == 1) {
  10032. var child = range.startContainer.childNodes[range.startOffset], pre;
  10033. if (child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)) {
  10034. range.setEnd(pre, pre.childNodes.length).collapse();
  10035. while (child.firstChild) {
  10036. pre.appendChild(child.firstChild);
  10037. }
  10038. domUtils.remove(child);
  10039. }
  10040. }
  10041. }
  10042. var child, parent, pre, tmp, hadBreak = 0, nextNode;
  10043. //如果当前位置选中了fillchar要干掉,要不会产生空行
  10044. if (range.inFillChar()) {
  10045. child = range.startContainer;
  10046. if (domUtils.isFillChar(child)) {
  10047. range.setStartBefore(child).collapse(true);
  10048. domUtils.remove(child);
  10049. } else if (domUtils.isFillChar(child, true)) {
  10050. child.nodeValue = child.nodeValue.replace(fillCharReg, '');
  10051. range.startOffset--;
  10052. range.collapsed && range.collapse(true)
  10053. }
  10054. }
  10055. //列表单独处理
  10056. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  10057. if (li) {
  10058. var next, last;
  10059. while (child = div.firstChild) {
  10060. //针对hr单独处理一下先
  10061. while (child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName == 'HR')) {
  10062. next = child.nextSibling;
  10063. range.insertNode(child).collapse();
  10064. last = child;
  10065. child = next;
  10066. }
  10067. if (child) {
  10068. if (/^(ol|ul)$/i.test(child.tagName)) {
  10069. while (child.firstChild) {
  10070. last = child.firstChild;
  10071. domUtils.insertAfter(li, child.firstChild);
  10072. li = li.nextSibling;
  10073. }
  10074. domUtils.remove(child)
  10075. } else {
  10076. var tmpLi;
  10077. next = child.nextSibling;
  10078. tmpLi = me.document.createElement('li');
  10079. domUtils.insertAfter(li, tmpLi);
  10080. tmpLi.appendChild(child);
  10081. last = child;
  10082. child = next;
  10083. li = tmpLi;
  10084. }
  10085. }
  10086. }
  10087. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  10088. if (domUtils.isEmptyBlock(li)) {
  10089. domUtils.remove(li)
  10090. }
  10091. if (last) {
  10092. range.setStartAfter(last).collapse(true).select(true)
  10093. }
  10094. } else {
  10095. while (child = div.firstChild) {
  10096. if (hadBreak) {
  10097. var p = me.document.createElement('p');
  10098. while (child && (child.nodeType == 3 || !dtd.$block[child.tagName])) {
  10099. nextNode = child.nextSibling;
  10100. p.appendChild(child);
  10101. child = nextNode;
  10102. }
  10103. if (p.firstChild) {
  10104. child = p
  10105. }
  10106. }
  10107. range.insertNode(child);
  10108. nextNode = child.nextSibling;
  10109. if (!hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm(child)) {
  10110. parent = domUtils.findParent(child, function(node) {
  10111. return domUtils.isBlockElm(node);
  10112. });
  10113. if (parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)) {
  10114. if (!dtd[parent.tagName][child.nodeName]) {
  10115. pre = parent;
  10116. } else {
  10117. tmp = child.parentNode;
  10118. while (tmp !== parent) {
  10119. pre = tmp;
  10120. tmp = tmp.parentNode;
  10121. }
  10122. }
  10123. domUtils.breakParent(child, pre || tmp);
  10124. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  10125. var pre = child.previousSibling;
  10126. domUtils.trimWhiteTextNode(pre);
  10127. if (!pre.childNodes.length) {
  10128. domUtils.remove(pre);
  10129. }
  10130. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  10131. if (!browser.ie &&
  10132. (next = child.nextSibling) &&
  10133. domUtils.isBlockElm(next) &&
  10134. next.lastChild &&
  10135. !domUtils.isBr(next.lastChild)) {
  10136. next.appendChild(me.document.createElement('br'));
  10137. }
  10138. hadBreak = 1;
  10139. }
  10140. }
  10141. var next = child.nextSibling;
  10142. if (!div.firstChild && next && domUtils.isBlockElm(next)) {
  10143. range.setStart(next, 0).collapse(true);
  10144. break;
  10145. }
  10146. range.setEndAfter(child).collapse();
  10147. }
  10148. child = range.startContainer;
  10149. if (nextNode && domUtils.isBr(nextNode)) {
  10150. domUtils.remove(nextNode)
  10151. }
  10152. //用chrome可能有空白展位符
  10153. if (domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)) {
  10154. if (nextNode = child.nextSibling) {
  10155. domUtils.remove(child);
  10156. if (nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]) {
  10157. range.setStart(nextNode, 0).collapse(true).shrinkBoundary()
  10158. }
  10159. } else {
  10160. try {
  10161. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  10162. } catch (e) {
  10163. range.setStartBefore(child);
  10164. domUtils.remove(child)
  10165. }
  10166. }
  10167. }
  10168. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  10169. try {
  10170. range.select(true);
  10171. } catch (e) {
  10172. }
  10173. }
  10174. setTimeout(function () {
  10175. range = me.selection.getRange();
  10176. range.scrollToView(me.autoHeightEnabled, me.autoHeightEnabled ? domUtils.getXY(me.iframe).y : 0);
  10177. me.fireEvent('afterinserthtml', html);
  10178. }, 200);
  10179. }
  10180. };
  10181. // plugins/autotypeset.js
  10182. /**
  10183. * 自动排版
  10184. * @file
  10185. * @since 1.2.6.1
  10186. */
  10187. /**
  10188. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  10189. * @command autotypeset
  10190. * @method execCommand
  10191. * @param { String } cmd 命令字符串
  10192. * @example
  10193. * ```javascript
  10194. * editor.execCommand( 'autotypeset' );
  10195. * ```
  10196. */
  10197. UE.plugins['autotypeset'] = function() {
  10198. this.setOpt({
  10199. 'autotypeset': {
  10200. mergeEmptyline: true, //合并空行
  10201. removeClass: true, //去掉冗余的class
  10202. removeEmptyline: false, //去掉空行
  10203. textAlign: "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  10204. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  10205. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  10206. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  10207. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  10208. removeEmptyNode: false, // 去掉空节点
  10209. //可以去掉的标签
  10210. removeTagNames: utils.extend({div: 1}, dtd.$removeEmpty),
  10211. indent: false, // 行首缩进
  10212. indentValue: '2em', //行首缩进的大小
  10213. bdc2sb: false,
  10214. tobdc: false
  10215. }
  10216. });
  10217. var me = this,
  10218. opt = me.options.autotypeset,
  10219. remainClass = {
  10220. 'selectTdClass': 1,
  10221. 'pagebreak': 1,
  10222. 'anchorclass': 1
  10223. },
  10224. remainTag = {
  10225. 'li': 1
  10226. },
  10227. tags = {
  10228. div: 1,
  10229. p: 1,
  10230. //trace:2183 这些也认为是行
  10231. blockquote: 1, center: 1, h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1,
  10232. span: 1
  10233. },
  10234. highlightCont;
  10235. //升级了版本,但配置项目里没有autotypeset
  10236. if (!opt) {
  10237. return;
  10238. }
  10239. readLocalOpts();
  10240. function isLine(node, notEmpty) {
  10241. if (!node || node.nodeType == 3)
  10242. return 0;
  10243. if (domUtils.isBr(node))
  10244. return 1;
  10245. if (node && node.parentNode && tags[node.tagName.toLowerCase()]) {
  10246. if (highlightCont && highlightCont.contains(node)
  10247. ||
  10248. node.getAttribute('pagebreak')
  10249. ) {
  10250. return 0;
  10251. }
  10252. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node, new RegExp('[\\s' + domUtils.fillChar
  10253. + ']', 'g'));
  10254. }
  10255. }
  10256. function removeNotAttributeSpan(node) {
  10257. if (!node.style.cssText) {
  10258. domUtils.removeAttributes(node, ['style']);
  10259. if (node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)) {
  10260. domUtils.remove(node, true);
  10261. }
  10262. }
  10263. }
  10264. function autotype(type, html) {
  10265. var me = this, cont;
  10266. if (html) {
  10267. if (!opt.pasteFilter) {
  10268. return;
  10269. }
  10270. cont = me.document.createElement('div');
  10271. cont.innerHTML = html.html;
  10272. } else {
  10273. cont = me.document.body;
  10274. }
  10275. var nodes = domUtils.getElementsByTagName(cont, '*');
  10276. // 行首缩进,段落方向,段间距,段内间距
  10277. for (var i = 0, ci; ci = nodes[i++];) {
  10278. if (me.fireEvent('excludeNodeinautotype', ci) === true) {
  10279. continue;
  10280. }
  10281. //font-size
  10282. if (opt.clearFontSize && ci.style.fontSize) {
  10283. domUtils.removeStyle(ci, 'font-size');
  10284. removeNotAttributeSpan(ci);
  10285. }
  10286. //font-family
  10287. if (opt.clearFontFamily && ci.style.fontFamily) {
  10288. domUtils.removeStyle(ci, 'font-family');
  10289. removeNotAttributeSpan(ci);
  10290. }
  10291. if (isLine(ci)) {
  10292. //合并空行
  10293. if (opt.mergeEmptyline) {
  10294. var next = ci.nextSibling, tmpNode, isBr = domUtils.isBr(ci);
  10295. while (isLine(next)) {
  10296. tmpNode = next;
  10297. next = tmpNode.nextSibling;
  10298. if (isBr && (!next || next && !domUtils.isBr(next))) {
  10299. break;
  10300. }
  10301. domUtils.remove(tmpNode);
  10302. }
  10303. }
  10304. //去掉空行,保留占位的空行
  10305. if (opt.removeEmptyline && domUtils.inDoc(ci, cont) && !remainTag[ci.parentNode.tagName.toLowerCase()]) {
  10306. if (domUtils.isBr(ci)) {
  10307. next = ci.nextSibling;
  10308. if (next && !domUtils.isBr(next)) {
  10309. continue;
  10310. }
  10311. }
  10312. domUtils.remove(ci);
  10313. continue;
  10314. }
  10315. }
  10316. if (isLine(ci, true) && ci.tagName != 'SPAN') {
  10317. if (opt.indent) {
  10318. ci.style.textIndent = opt.indentValue;
  10319. }
  10320. if (opt.textAlign) {
  10321. ci.style.textAlign = opt.textAlign;
  10322. }
  10323. // if(opt.lineHeight)
  10324. // ci.style.lineHeight = opt.lineHeight + 'cm';
  10325. }
  10326. //去掉class,保留的class不去掉
  10327. if (opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]) {
  10328. if (highlightCont && highlightCont.contains(ci)) {
  10329. continue;
  10330. }
  10331. domUtils.removeAttributes(ci, ['class']);
  10332. }
  10333. //表情不处理
  10334. if (opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')) {
  10335. if (html) {
  10336. var img = ci;
  10337. switch (opt.imageBlockLine) {
  10338. case 'left':
  10339. case 'right':
  10340. case 'none':
  10341. var pN = img.parentNode, tmpNode, pre, next;
  10342. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10343. pN = pN.parentNode;
  10344. }
  10345. tmpNode = pN;
  10346. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10347. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10348. return !domUtils.isBr(node) && !domUtils.isWhitespace(node)
  10349. }) == 1) {
  10350. pre = tmpNode.previousSibling;
  10351. next = tmpNode.nextSibling;
  10352. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10353. pre.appendChild(tmpNode.firstChild);
  10354. while (next.firstChild) {
  10355. pre.appendChild(next.firstChild);
  10356. }
  10357. domUtils.remove(tmpNode);
  10358. domUtils.remove(next);
  10359. } else {
  10360. domUtils.setStyle(tmpNode, 'text-align', '');
  10361. }
  10362. }
  10363. }
  10364. domUtils.setStyle(img, 'float', opt.imageBlockLine);
  10365. break;
  10366. case 'center':
  10367. if (me.queryCommandValue('imagefloat') != 'center') {
  10368. pN = img.parentNode;
  10369. domUtils.setStyle(img, 'float', 'none');
  10370. tmpNode = img;
  10371. while (pN && domUtils.getChildCount(pN, function (node) {
  10372. return !domUtils.isBr(node) && !domUtils.isWhitespace(node)
  10373. }) == 1
  10374. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10375. tmpNode = pN;
  10376. pN = pN.parentNode;
  10377. }
  10378. var pNode = me.document.createElement('p');
  10379. domUtils.setAttributes(pNode, {
  10380. style: 'text-align:center'
  10381. });
  10382. tmpNode.parentNode.insertBefore(pNode, tmpNode);
  10383. pNode.appendChild(tmpNode);
  10384. domUtils.setStyle(tmpNode, 'float', '');
  10385. }
  10386. }
  10387. } else {
  10388. var range = me.selection.getRange();
  10389. range.selectNode(ci).select();
  10390. me.execCommand('imagefloat', opt.imageBlockLine);
  10391. }
  10392. }
  10393. //去掉冗余的标签
  10394. if (opt.removeEmptyNode) {
  10395. if (opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)) {
  10396. domUtils.remove(ci);
  10397. }
  10398. }
  10399. }
  10400. if (opt.tobdc) {
  10401. var root = UE.htmlparser(cont.innerHTML);
  10402. root.traversal(function (node) {
  10403. if (node.type == 'text') {
  10404. node.data = ToDBC(node.data)
  10405. }
  10406. });
  10407. cont.innerHTML = root.toHtml()
  10408. }
  10409. if (opt.bdc2sb) {
  10410. var root = UE.htmlparser(cont.innerHTML);
  10411. root.traversal(function (node) {
  10412. if (node.type == 'text') {
  10413. node.data = DBC2SB(node.data)
  10414. }
  10415. });
  10416. cont.innerHTML = root.toHtml()
  10417. }
  10418. if (html) {
  10419. html.html = cont.innerHTML;
  10420. }
  10421. }
  10422. if (opt.pasteFilter) {
  10423. me.addListener('beforepaste', autotype);
  10424. }
  10425. function DBC2SB(str) {
  10426. var result = '';
  10427. for (var i = 0; i < str.length; i++) {
  10428. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10429. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10430. {
  10431. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10432. } else if (code == 12288)//空格
  10433. {
  10434. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10435. } else {
  10436. result += str.charAt(i);
  10437. }
  10438. }
  10439. return result;
  10440. }
  10441. function ToDBC(txtstring) {
  10442. txtstring = utils.html(txtstring);
  10443. var tmp = "";
  10444. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10445. for (var i = 0; i < txtstring.length; i++) {
  10446. if (txtstring.charCodeAt(i) == 32) {
  10447. tmp = tmp + String.fromCharCode(12288);
  10448. } else if (txtstring.charCodeAt(i) < 127) {
  10449. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10450. } else {
  10451. tmp += txtstring.charAt(i);
  10452. }
  10453. }
  10454. return tmp;
  10455. }
  10456. function readLocalOpts() {
  10457. var cookieOpt = me.getPreferences('autotypeset');
  10458. utils.extend(me.options.autotypeset, cookieOpt);
  10459. }
  10460. me.commands['autotypeset'] = {
  10461. execCommand: function () {
  10462. me.removeListener('beforepaste', autotype);
  10463. if (opt.pasteFilter) {
  10464. me.addListener('beforepaste', autotype);
  10465. }
  10466. autotype.call(me)
  10467. }
  10468. };
  10469. };
  10470. // plugins/autosubmit.js
  10471. /**
  10472. * 快捷键提交
  10473. * @file
  10474. * @since 1.2.6.1
  10475. */
  10476. /**
  10477. * 提交表单
  10478. * @command autosubmit
  10479. * @method execCommand
  10480. * @param { String } cmd 命令字符串
  10481. * @example
  10482. * ```javascript
  10483. * editor.execCommand( 'autosubmit' );
  10484. * ```
  10485. */
  10486. UE.plugin.register('autosubmit', function () {
  10487. return {
  10488. shortcutkey: {
  10489. "autosubmit": "ctrl+13" //手动提交
  10490. },
  10491. commands: {
  10492. 'autosubmit': {
  10493. execCommand: function () {
  10494. var me = this,
  10495. form = domUtils.findParentByTagName(me.iframe, "form", false);
  10496. if (form) {
  10497. if (me.fireEvent("beforesubmit") === false) {
  10498. return;
  10499. }
  10500. me.sync();
  10501. form.submit();
  10502. }
  10503. }
  10504. }
  10505. }
  10506. }
  10507. });
  10508. // plugins/background.js
  10509. /**
  10510. * 背景插件,为UEditor提供设置背景功能
  10511. * @file
  10512. * @since 1.2.6.1
  10513. */
  10514. UE.plugin.register('background', function () {
  10515. var me = this,
  10516. cssRuleId = 'editor_background',
  10517. isSetColored,
  10518. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10519. function stringToObj(str) {
  10520. var obj = {}, styles = str.split(';');
  10521. utils.each(styles, function (v) {
  10522. var index = v.indexOf(':'),
  10523. key = utils.trim(v.substr(0, index)).toLowerCase();
  10524. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10525. });
  10526. return obj;
  10527. }
  10528. function setBackground(obj) {
  10529. if (obj) {
  10530. var styles = [];
  10531. for (var name in obj) {
  10532. if (obj.hasOwnProperty(name)) {
  10533. styles.push(name + ":" + obj[name] + '; ');
  10534. }
  10535. }
  10536. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10537. } else {
  10538. utils.cssRule(cssRuleId, '', me.document)
  10539. }
  10540. }
  10541. //重写editor.hasContent方法
  10542. var orgFn = me.hasContents;
  10543. me.hasContents = function () {
  10544. if (me.queryCommandValue('background')) {
  10545. return true
  10546. }
  10547. return orgFn.apply(me, arguments);
  10548. };
  10549. return {
  10550. bindEvents: {
  10551. 'getAllHtml': function (type, headHtml) {
  10552. var body = this.body,
  10553. su = domUtils.getComputedStyle(body, "background-image"),
  10554. url = "";
  10555. if (su.indexOf(me.options.imagePath) > 0) {
  10556. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10557. } else {
  10558. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10559. }
  10560. var html = '<style type="text/css">body{';
  10561. var bgObj = {
  10562. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10563. 'background-image': url ? 'url(' + url + ')' : '',
  10564. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10565. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10566. 'height': domUtils.getComputedStyle(body, "height")
  10567. };
  10568. for (var name in bgObj) {
  10569. if (bgObj.hasOwnProperty(name)) {
  10570. html += name + ":" + bgObj[name] + "; ";
  10571. }
  10572. }
  10573. html += '}</style> ';
  10574. headHtml.push(html);
  10575. },
  10576. 'aftersetcontent': function () {
  10577. if (isSetColored == false) setBackground();
  10578. }
  10579. },
  10580. inputRule: function (root) {
  10581. isSetColored = false;
  10582. utils.each(root.getNodesByTagName('p'), function (p) {
  10583. var styles = p.getAttr('data-background');
  10584. if (styles) {
  10585. isSetColored = true;
  10586. setBackground(stringToObj(styles));
  10587. p.parentNode.removeChild(p);
  10588. }
  10589. })
  10590. },
  10591. outputRule: function (root) {
  10592. var me = this,
  10593. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10594. if (styles) {
  10595. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10596. }
  10597. },
  10598. commands: {
  10599. 'background': {
  10600. execCommand: function (cmd, obj) {
  10601. setBackground(obj);
  10602. },
  10603. queryCommandValue: function () {
  10604. var me = this,
  10605. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10606. return styles ? stringToObj(styles[1]) : null;
  10607. },
  10608. notNeedUndo: true
  10609. }
  10610. }
  10611. }
  10612. });
  10613. // plugins/image.js
  10614. /**
  10615. * 图片插入、排版插件
  10616. * @file
  10617. * @since 1.2.6.1
  10618. */
  10619. /**
  10620. * 图片对齐方式
  10621. * @command imagefloat
  10622. * @method execCommand
  10623. * @remind 值center为独占一行居中
  10624. * @param { String } cmd 命令字符串
  10625. * @param { String } align 对齐方式,可传left、right、none、center
  10626. * @remaind center表示图片独占一行
  10627. * @example
  10628. * ```javascript
  10629. * editor.execCommand( 'imagefloat', 'center' );
  10630. * ```
  10631. */
  10632. /**
  10633. * 如果选区所在位置是图片区域
  10634. * @command imagefloat
  10635. * @method queryCommandValue
  10636. * @param { String } cmd 命令字符串
  10637. * @return { String } 返回图片对齐方式
  10638. * @example
  10639. * ```javascript
  10640. * editor.queryCommandValue( 'imagefloat' );
  10641. * ```
  10642. */
  10643. UE.commands['imagefloat'] = {
  10644. execCommand: function (cmd, align) {
  10645. var me = this,
  10646. range = me.selection.getRange();
  10647. if (!range.collapsed) {
  10648. var img = range.getClosedNode();
  10649. if (img && img.tagName == 'IMG') {
  10650. switch (align) {
  10651. case 'left':
  10652. case 'right':
  10653. case 'none':
  10654. var pN = img.parentNode, tmpNode, pre, next;
  10655. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10656. pN = pN.parentNode;
  10657. }
  10658. tmpNode = pN;
  10659. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10660. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10661. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10662. }) == 1) {
  10663. pre = tmpNode.previousSibling;
  10664. next = tmpNode.nextSibling;
  10665. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10666. pre.appendChild(tmpNode.firstChild);
  10667. while (next.firstChild) {
  10668. pre.appendChild(next.firstChild);
  10669. }
  10670. domUtils.remove(tmpNode);
  10671. domUtils.remove(next);
  10672. } else {
  10673. domUtils.setStyle(tmpNode, 'text-align', '');
  10674. }
  10675. }
  10676. range.selectNode(img).select();
  10677. }
  10678. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10679. if (align == 'none') {
  10680. domUtils.removeAttributes(img, 'align');
  10681. }
  10682. break;
  10683. case 'center':
  10684. if (me.queryCommandValue('imagefloat') != 'center') {
  10685. pN = img.parentNode;
  10686. domUtils.setStyle(img, 'float', '');
  10687. domUtils.removeAttributes(img, 'align');
  10688. tmpNode = img;
  10689. while (pN && domUtils.getChildCount(pN, function (node) {
  10690. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10691. }) == 1
  10692. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10693. tmpNode = pN;
  10694. pN = pN.parentNode;
  10695. }
  10696. range.setStartBefore(tmpNode).setCursor(false);
  10697. pN = me.document.createElement('div');
  10698. pN.appendChild(tmpNode);
  10699. domUtils.setStyle(tmpNode, 'float', '');
  10700. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10701. tmpNode = me.document.getElementById('_img_parent_tmp');
  10702. tmpNode.removeAttribute('id');
  10703. tmpNode = tmpNode.firstChild;
  10704. range.selectNode(tmpNode).select();
  10705. //去掉后边多余的元素
  10706. next = tmpNode.parentNode.nextSibling;
  10707. if (next && domUtils.isEmptyNode(next)) {
  10708. domUtils.remove(next);
  10709. }
  10710. }
  10711. break;
  10712. }
  10713. }
  10714. }
  10715. },
  10716. queryCommandValue: function () {
  10717. var range = this.selection.getRange(),
  10718. startNode, floatStyle;
  10719. if (range.collapsed) {
  10720. return 'none';
  10721. }
  10722. startNode = range.getClosedNode();
  10723. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10724. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10725. if (floatStyle == 'none') {
  10726. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10727. }
  10728. return {
  10729. left: 1,
  10730. right: 1,
  10731. center: 1
  10732. }[floatStyle] ? floatStyle : 'none';
  10733. }
  10734. return 'none';
  10735. },
  10736. queryCommandState: function () {
  10737. var range = this.selection.getRange(),
  10738. startNode;
  10739. if (range.collapsed) return -1;
  10740. startNode = range.getClosedNode();
  10741. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10742. return 0;
  10743. }
  10744. return -1;
  10745. }
  10746. };
  10747. /**
  10748. * 插入图片
  10749. * @command insertimage
  10750. * @method execCommand
  10751. * @param { String } cmd 命令字符串
  10752. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10753. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10754. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10755. * @example
  10756. * ```javascript
  10757. * editor.execCommand( 'insertimage', {
  10758. * src:'a/b/c.jpg',
  10759. * width:'100',
  10760. * height:'100'
  10761. * } );
  10762. * ```
  10763. * @example
  10764. * ```javascript
  10765. * editor.execCommand( 'insertimage', [{
  10766. * src:'a/b/c.jpg',
  10767. * width:'100',
  10768. * height:'100'
  10769. * },{
  10770. * src:'a/b/d.jpg',
  10771. * width:'100',
  10772. * height:'100'
  10773. * }] );
  10774. * ```
  10775. */
  10776. UE.commands['insertimage'] = {
  10777. execCommand: function (cmd, opt) {
  10778. opt = utils.isArray(opt) ? opt : [opt];
  10779. if (!opt.length) {
  10780. return;
  10781. }
  10782. var me = this,
  10783. range = me.selection.getRange(),
  10784. img = range.getClosedNode();
  10785. if (me.fireEvent('beforeinsertimage', opt) === true) {
  10786. return;
  10787. }
  10788. function unhtmlData(imgCi) {
  10789. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10790. if (imgCi[item]) {
  10791. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10792. }
  10793. });
  10794. utils.each('src,_src'.split(','), function (item) {
  10795. if (imgCi[item]) {
  10796. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10797. }
  10798. });
  10799. utils.each('title,alt'.split(','), function (item) {
  10800. if (imgCi[item]) {
  10801. imgCi[item] = utils.unhtml(imgCi[item]);
  10802. }
  10803. });
  10804. }
  10805. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video") != -1) && !img.getAttribute("word_img")) {
  10806. var first = opt.shift();
  10807. var floatStyle = first['floatStyle'];
  10808. delete first['floatStyle'];
  10809. //// img.style.border = (first.border||0) +"px solid #000";
  10810. //// img.style.margin = (first.margin||0) +"px";
  10811. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10812. domUtils.setAttributes(img, first);
  10813. me.execCommand('imagefloat', floatStyle);
  10814. if (opt.length > 0) {
  10815. range.setStartAfter(img).setCursor(false, true);
  10816. me.execCommand('insertimage', opt);
  10817. }
  10818. } else {
  10819. var html = [], str = '', ci;
  10820. ci = opt[0];
  10821. if (opt.length == 1) {
  10822. unhtmlData(ci);
  10823. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10824. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10825. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10826. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10827. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10828. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10829. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10830. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10831. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10832. if (ci['floatStyle'] == 'center') {
  10833. str = '<p style="text-align: center">' + str + '</p>';
  10834. }
  10835. html.push(str);
  10836. } else {
  10837. for (var i = 0; ci = opt[i++];) {
  10838. unhtmlData(ci);
  10839. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10840. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10841. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10842. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10843. (ci.border || '') + '" ' +
  10844. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10845. html.push(str);
  10846. }
  10847. }
  10848. me.execCommand('insertHtml', html.join(''));
  10849. }
  10850. me.fireEvent('afterinsertimage', opt)
  10851. }
  10852. };
  10853. // plugins/justify.js
  10854. /**
  10855. * 段落格式
  10856. * @file
  10857. * @since 1.2.6.1
  10858. */
  10859. /**
  10860. * 段落对齐方式
  10861. * @command justify
  10862. * @method execCommand
  10863. * @param { String } cmd 命令字符串
  10864. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10865. * @example
  10866. * ```javascript
  10867. * editor.execCommand( 'justify', 'center' );
  10868. * ```
  10869. */
  10870. /**
  10871. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10872. * @command justify
  10873. * @method queryCommandValue
  10874. * @param { String } cmd 命令字符串
  10875. * @return { String } 返回段落对齐方式
  10876. * @example
  10877. * ```javascript
  10878. * editor.queryCommandValue( 'justify' );
  10879. * ```
  10880. */
  10881. UE.plugins['justify'] = function () {
  10882. var me = this,
  10883. block = domUtils.isBlockElm,
  10884. defaultValue = {
  10885. left: 1,
  10886. right: 1,
  10887. center: 1,
  10888. justify: 1
  10889. },
  10890. doJustify = function (range, style) {
  10891. var bookmark = range.createBookmark(),
  10892. filterFn = function (node) {
  10893. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10894. };
  10895. range.enlarge(true);
  10896. var bookmark2 = range.createBookmark(),
  10897. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10898. tmpRange = range.cloneRange(),
  10899. tmpNode;
  10900. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10901. if (current.nodeType == 3 || !block(current)) {
  10902. tmpRange.setStartBefore(current);
  10903. while (current && current !== bookmark2.end && !block(current)) {
  10904. tmpNode = current;
  10905. current = domUtils.getNextDomNode(current, false, null, function(node) {
  10906. return !block(node);
  10907. });
  10908. }
  10909. tmpRange.setEndAfter(tmpNode);
  10910. var common = tmpRange.getCommonAncestor();
  10911. if (!domUtils.isBody(common) && block(common)) {
  10912. domUtils.setStyles(common, utils.isString(style) ? { 'text-align': style } : style);
  10913. current = common;
  10914. } else {
  10915. var p = range.document.createElement('p');
  10916. domUtils.setStyles(p, utils.isString(style) ? { 'text-align': style } : style);
  10917. var frag = tmpRange.extractContents();
  10918. p.appendChild(frag);
  10919. tmpRange.insertNode(p);
  10920. current = p;
  10921. }
  10922. current = domUtils.getNextDomNode(current, false, filterFn);
  10923. } else {
  10924. current = domUtils.getNextDomNode(current, true, filterFn);
  10925. }
  10926. }
  10927. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10928. };
  10929. UE.commands['justify'] = {
  10930. execCommand: function (cmdName, align) {
  10931. var range = this.selection.getRange(),
  10932. txt;
  10933. //闭合时单独处理
  10934. if (range.collapsed) {
  10935. txt = this.document.createTextNode('p');
  10936. range.insertNode(txt);
  10937. }
  10938. doJustify(range, align);
  10939. if (txt) {
  10940. range.setStartBefore(txt).collapse(true);
  10941. domUtils.remove(txt);
  10942. }
  10943. range.select();
  10944. return true;
  10945. },
  10946. queryCommandValue: function () {
  10947. var startNode = this.selection.getStart(),
  10948. value = domUtils.getComputedStyle(startNode, 'text-align');
  10949. return defaultValue[value] ? value : 'left';
  10950. },
  10951. queryCommandState: function () {
  10952. var start = this.selection.getStart(),
  10953. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  10954. return cell ? -1 : 0;
  10955. }
  10956. };
  10957. };
  10958. // plugins/font.js
  10959. /**
  10960. * 字体颜色,背景色,字号,字体,下划线,删除线
  10961. * @file
  10962. * @since 1.2.6.1
  10963. */
  10964. /**
  10965. * 字体颜色
  10966. * @command forecolor
  10967. * @method execCommand
  10968. * @param { String } cmd 命令字符串
  10969. * @param { String } value 色值(必须十六进制)
  10970. * @example
  10971. * ```javascript
  10972. * editor.execCommand( 'forecolor', '#000' );
  10973. * ```
  10974. */
  10975. /**
  10976. * 返回选区字体颜色
  10977. * @command forecolor
  10978. * @method queryCommandValue
  10979. * @param { String } cmd 命令字符串
  10980. * @return { String } 返回字体颜色
  10981. * @example
  10982. * ```javascript
  10983. * editor.queryCommandValue( 'forecolor' );
  10984. * ```
  10985. */
  10986. /**
  10987. * 字体背景颜色
  10988. * @command backcolor
  10989. * @method execCommand
  10990. * @param { String } cmd 命令字符串
  10991. * @param { String } value 色值(必须十六进制)
  10992. * @example
  10993. * ```javascript
  10994. * editor.execCommand( 'backcolor', '#000' );
  10995. * ```
  10996. */
  10997. /**
  10998. * 返回选区字体颜色
  10999. * @command backcolor
  11000. * @method queryCommandValue
  11001. * @param { String } cmd 命令字符串
  11002. * @return { String } 返回字体背景颜色
  11003. * @example
  11004. * ```javascript
  11005. * editor.queryCommandValue( 'backcolor' );
  11006. * ```
  11007. */
  11008. /**
  11009. * 字体大小
  11010. * @command fontsize
  11011. * @method execCommand
  11012. * @param { String } cmd 命令字符串
  11013. * @param { String } value 字体大小
  11014. * @example
  11015. * ```javascript
  11016. * editor.execCommand( 'fontsize', '14px' );
  11017. * ```
  11018. */
  11019. /**
  11020. * 返回选区字体大小
  11021. * @command fontsize
  11022. * @method queryCommandValue
  11023. * @param { String } cmd 命令字符串
  11024. * @return { String } 返回字体大小
  11025. * @example
  11026. * ```javascript
  11027. * editor.queryCommandValue( 'fontsize' );
  11028. * ```
  11029. */
  11030. /**
  11031. * 字体样式
  11032. * @command fontfamily
  11033. * @method execCommand
  11034. * @param { String } cmd 命令字符串
  11035. * @param { String } value 字体样式
  11036. * @example
  11037. * ```javascript
  11038. * editor.execCommand( 'fontfamily', '微软雅黑' );
  11039. * ```
  11040. */
  11041. /**
  11042. * 返回选区字体样式
  11043. * @command fontfamily
  11044. * @method queryCommandValue
  11045. * @param { String } cmd 命令字符串
  11046. * @return { String } 返回字体样式
  11047. * @example
  11048. * ```javascript
  11049. * editor.queryCommandValue( 'fontfamily' );
  11050. * ```
  11051. */
  11052. /**
  11053. * 字体下划线,与删除线互斥
  11054. * @command underline
  11055. * @method execCommand
  11056. * @param { String } cmd 命令字符串
  11057. * @example
  11058. * ```javascript
  11059. * editor.execCommand( 'underline' );
  11060. * ```
  11061. */
  11062. /**
  11063. * 字体删除线,与下划线互斥
  11064. * @command strikethrough
  11065. * @method execCommand
  11066. * @param { String } cmd 命令字符串
  11067. * @example
  11068. * ```javascript
  11069. * editor.execCommand( 'strikethrough' );
  11070. * ```
  11071. */
  11072. /**
  11073. * 字体边框
  11074. * @command fontborder
  11075. * @method execCommand
  11076. * @param { String } cmd 命令字符串
  11077. * @example
  11078. * ```javascript
  11079. * editor.execCommand( 'fontborder' );
  11080. * ```
  11081. */
  11082. UE.plugins['font'] = function () {
  11083. var me = this,
  11084. fonts = {
  11085. 'forecolor': 'color',
  11086. 'backcolor': 'background-color',
  11087. 'fontsize': 'font-size',
  11088. 'fontfamily': 'font-family',
  11089. 'underline': 'text-decoration',
  11090. 'strikethrough': 'text-decoration',
  11091. 'fontborder': 'border'
  11092. },
  11093. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  11094. needSetChild = {
  11095. 'forecolor': 'color',
  11096. 'backcolor': 'background-color',
  11097. 'fontsize': 'font-size',
  11098. 'fontfamily': 'font-family'
  11099. };
  11100. me.setOpt({
  11101. 'fontfamily': [
  11102. {name: 'songti', val: '宋体,SimSun'},
  11103. {name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  11104. {name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  11105. {name: 'heiti', val: '黑体, SimHei'},
  11106. {name: 'lishu', val: '隶书, SimLi'},
  11107. {name: 'andaleMono', val: 'andale mono'},
  11108. {name: 'arial', val: 'arial, helvetica,sans-serif'},
  11109. {name: 'arialBlack', val: 'arial black,avant garde'},
  11110. {name: 'comicSansMs', val: 'comic sans ms'},
  11111. {name: 'impact', val: 'impact,chicago'},
  11112. {name: 'timesNewRoman', val: 'times new roman'}
  11113. ],
  11114. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  11115. });
  11116. function mergeWithParent(node) {
  11117. var parent;
  11118. while (parent = node.parentNode) {
  11119. if (parent.tagName == 'SPAN' && domUtils.getChildCount(parent, function(child) {
  11120. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child);
  11121. }) == 1) {
  11122. parent.style.cssText += node.style.cssText;
  11123. domUtils.remove(node, true);
  11124. node = parent;
  11125. } else {
  11126. break;
  11127. }
  11128. }
  11129. }
  11130. function mergeChild(rng, cmdName, value) {
  11131. if (needSetChild[cmdName]) {
  11132. rng.adjustmentBoundary();
  11133. if (!rng.collapsed && rng.startContainer.nodeType == 1) {
  11134. var start = rng.startContainer.childNodes[rng.startOffset];
  11135. if (start && domUtils.isTagNode(start, 'span')) {
  11136. var bk = rng.createBookmark();
  11137. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  11138. if (!span.parentNode || domUtils.isBookmarkNode(span)) return;
  11139. if (cmdName == 'backcolor' && domUtils.getComputedStyle(span, 'background-color').toLowerCase() === value) {
  11140. return;
  11141. }
  11142. domUtils.removeStyle(span, needSetChild[cmdName]);
  11143. if (span.style.cssText.replace(/^\s+$/, '').length == 0) {
  11144. domUtils.remove(span, true)
  11145. }
  11146. });
  11147. rng.moveToBookmark(bk)
  11148. }
  11149. }
  11150. }
  11151. }
  11152. function mergesibling(rng, cmdName, value) {
  11153. var collapsed = rng.collapsed,
  11154. bk = rng.createBookmark(), common;
  11155. if (collapsed) {
  11156. common = bk.start.parentNode;
  11157. while (dtd.$inline[common.tagName]) {
  11158. common = common.parentNode;
  11159. }
  11160. } else {
  11161. common = domUtils.getCommonAncestor(bk.start, bk.end);
  11162. }
  11163. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  11164. if (!span.parentNode || domUtils.isBookmarkNode(span)) return;
  11165. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  11166. if (/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)) {
  11167. domUtils.remove(span, true);
  11168. } else {
  11169. domUtils.removeStyle(span, 'border');
  11170. }
  11171. return
  11172. }
  11173. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  11174. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  11175. }
  11176. if (!(cmdName == 'fontborder' && value == 'none')) {
  11177. var next = span.nextSibling;
  11178. while (next && next.nodeType == 1 && next.tagName == 'SPAN') {
  11179. if (domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  11180. span.appendChild(next);
  11181. next = span.nextSibling;
  11182. continue;
  11183. }
  11184. if (next.style.cssText == span.style.cssText) {
  11185. domUtils.moveChild(next, span);
  11186. domUtils.remove(next);
  11187. }
  11188. if (span.nextSibling === next)
  11189. break;
  11190. next = span.nextSibling;
  11191. }
  11192. }
  11193. mergeWithParent(span);
  11194. if (browser.ie && browser.version > 8) {
  11195. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  11196. var parent = domUtils.findParent(span, function (n) {
  11197. return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)
  11198. });
  11199. if (parent && !/background-color/.test(span.style.cssText)) {
  11200. span.style.backgroundColor = parent.style.backgroundColor;
  11201. }
  11202. }
  11203. });
  11204. rng.moveToBookmark(bk);
  11205. mergeChild(rng, cmdName, value)
  11206. }
  11207. me.addInputRule(function (root) {
  11208. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  11209. if (node.tagName == 'font') {
  11210. var cssStyle = [];
  11211. for (var p in node.attrs) {
  11212. switch (p) {
  11213. case 'size':
  11214. cssStyle.push('font-size:' +
  11215. ({
  11216. '1': '10',
  11217. '2': '12',
  11218. '3': '16',
  11219. '4': '18',
  11220. '5': '24',
  11221. '6': '32',
  11222. '7': '48'
  11223. }[node.attrs[p]] || node.attrs[p]) + 'px');
  11224. break;
  11225. case 'color':
  11226. cssStyle.push('color:' + node.attrs[p]);
  11227. break;
  11228. case 'face':
  11229. cssStyle.push('font-family:' + node.attrs[p]);
  11230. break;
  11231. case 'style':
  11232. cssStyle.push(node.attrs[p]);
  11233. }
  11234. }
  11235. node.attrs = {
  11236. 'style': cssStyle.join(';')
  11237. };
  11238. } else {
  11239. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  11240. node.attrs = {
  11241. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  11242. }
  11243. }
  11244. node.tagName = 'span';
  11245. });
  11246. // utils.each(root.getNodesByTagName('span'), function (node) {
  11247. // var val;
  11248. // if(val = node.getAttr('class')){
  11249. // if(/fontstrikethrough/.test(val)){
  11250. // node.setStyle('text-decoration','line-through');
  11251. // if(node.attrs['class']){
  11252. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  11253. // }else{
  11254. // node.setAttr('class')
  11255. // }
  11256. // }
  11257. // if(/fontborder/.test(val)){
  11258. // node.setStyle('border','1px solid #000');
  11259. // if(node.attrs['class']){
  11260. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  11261. // }else{
  11262. // node.setAttr('class')
  11263. // }
  11264. // }
  11265. // }
  11266. // });
  11267. });
  11268. // me.addOutputRule(function(root){
  11269. // utils.each(root.getNodesByTagName('span'), function (node) {
  11270. // var val;
  11271. // if(val = node.getStyle('text-decoration')){
  11272. // if(/line-through/.test(val)){
  11273. // if(node.attrs['class']){
  11274. // node.attrs['class'] += ' fontstrikethrough';
  11275. // }else{
  11276. // node.setAttr('class','fontstrikethrough')
  11277. // }
  11278. // }
  11279. //
  11280. // node.setStyle('text-decoration')
  11281. // }
  11282. // if(val = node.getStyle('border')){
  11283. // if(/1px/.test(val) && /solid/.test(val)){
  11284. // if(node.attrs['class']){
  11285. // node.attrs['class'] += ' fontborder';
  11286. //
  11287. // }else{
  11288. // node.setAttr('class','fontborder')
  11289. // }
  11290. // }
  11291. // node.setStyle('border')
  11292. //
  11293. // }
  11294. // });
  11295. // });
  11296. for (var p in fonts) {
  11297. (function (cmd, style) {
  11298. UE.commands[cmd] = {
  11299. execCommand: function (cmdName, value) {
  11300. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  11301. cmdName == 'fontborder' ? '1px solid #000' :
  11302. 'line-through');
  11303. var me = this,
  11304. range = this.selection.getRange(),
  11305. text;
  11306. if (value == 'default') {
  11307. if (range.collapsed) {
  11308. text = me.document.createTextNode('font');
  11309. range.insertNode(text).select();
  11310. }
  11311. me.execCommand('removeFormat', 'span,a', style);
  11312. if (text) {
  11313. range.setStartBefore(text).collapse(true);
  11314. domUtils.remove(text);
  11315. }
  11316. mergesibling(range, cmdName, value);
  11317. range.select()
  11318. } else {
  11319. if (!range.collapsed) {
  11320. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  11321. me.execCommand('removeFormat', 'span,a', style);
  11322. }
  11323. range = me.selection.getRange();
  11324. range.applyInlineStyle('span', {'style': style + ':' + value});
  11325. mergesibling(range, cmdName, value);
  11326. range.select();
  11327. } else {
  11328. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  11329. text = me.document.createTextNode('font');
  11330. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  11331. //for ie hack when enter
  11332. range.insertNode(text);
  11333. if (needCmd[cmd]) {
  11334. range.selectNode(text).select();
  11335. me.execCommand('removeFormat', 'span,a', style, null);
  11336. span = domUtils.findParentByTagName(text, 'span', true);
  11337. range.setStartBefore(text);
  11338. }
  11339. span && (span.style.cssText += ';' + style + ':' + value);
  11340. range.collapse(true).select();
  11341. } else {
  11342. range.insertNode(text);
  11343. range.selectNode(text).select();
  11344. span = range.document.createElement('span');
  11345. if (needCmd[cmd]) {
  11346. //a标签内的不处理跳过
  11347. if (domUtils.findParentByTagName(text, 'a', true)) {
  11348. range.setStartBefore(text).setCursor();
  11349. domUtils.remove(text);
  11350. return;
  11351. }
  11352. me.execCommand('removeFormat', 'span,a', style);
  11353. }
  11354. span.style.cssText = style + ':' + value;
  11355. text.parentNode.insertBefore(span, text);
  11356. //修复,span套span 但样式不继承的问题
  11357. if (!browser.ie || browser.ie && browser.version == 9) {
  11358. var spanParent = span.parentNode;
  11359. while (!domUtils.isBlockElm(spanParent)) {
  11360. if (spanParent.tagName == 'SPAN') {
  11361. //opera合并style不会加入";"
  11362. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  11363. }
  11364. spanParent = spanParent.parentNode;
  11365. }
  11366. }
  11367. if (opera) {
  11368. setTimeout(function () {
  11369. range.setStart(span, 0).collapse(true);
  11370. mergesibling(range, cmdName, value);
  11371. range.select();
  11372. });
  11373. } else {
  11374. range.setStart(span, 0).collapse(true);
  11375. mergesibling(range, cmdName, value);
  11376. range.select();
  11377. }
  11378. //trace:981
  11379. //domUtils.mergeToParent(span)
  11380. }
  11381. domUtils.remove(text);
  11382. }
  11383. }
  11384. return true;
  11385. },
  11386. queryCommandValue: function (cmdName) {
  11387. var startNode = this.selection.getStart();
  11388. //trace:946
  11389. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11390. var tmpNode = startNode, value;
  11391. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11392. if (tmpNode.nodeType == 1) {
  11393. value = domUtils.getComputedStyle(tmpNode, style);
  11394. if (value != 'none') {
  11395. return value;
  11396. }
  11397. }
  11398. tmpNode = tmpNode.parentNode;
  11399. }
  11400. return 'none';
  11401. }
  11402. if (cmdName == 'fontborder') {
  11403. var tmp = startNode, val;
  11404. while (tmp && dtd.$inline[tmp.tagName]) {
  11405. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11406. if (/1px/.test(val) && /solid/.test(val)) {
  11407. return val;
  11408. }
  11409. }
  11410. tmp = tmp.parentNode;
  11411. }
  11412. return ''
  11413. }
  11414. if (cmdName == 'FontSize') {
  11415. var styleVal = domUtils.getComputedStyle(startNode, style),
  11416. tmp = /^([\d\.]+)(\w+)$/.exec(styleVal);
  11417. if (tmp) {
  11418. return Math.floor(tmp[1]) + tmp[2];
  11419. }
  11420. return styleVal;
  11421. }
  11422. return domUtils.getComputedStyle(startNode, style);
  11423. },
  11424. queryCommandState: function (cmdName) {
  11425. if (!needCmd[cmdName])
  11426. return 0;
  11427. var val = this.queryCommandValue(cmdName);
  11428. if (cmdName == 'fontborder') {
  11429. return /1px/.test(val) && /solid/.test(val)
  11430. } else {
  11431. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11432. }
  11433. }
  11434. };
  11435. })(p, fonts[p]);
  11436. }
  11437. };
  11438. // plugins/link.js
  11439. /**
  11440. * 超链接
  11441. * @file
  11442. * @since 1.2.6.1
  11443. */
  11444. /**
  11445. * 插入超链接
  11446. * @command link
  11447. * @method execCommand
  11448. * @param { String } cmd 命令字符串
  11449. * @param { Object } options 设置自定义属性,例如:url、title、target
  11450. * @example
  11451. * ```javascript
  11452. * editor.execCommand( 'link', '{
  11453. * url:'ueditor.baidu.com',
  11454. * title:'ueditor',
  11455. * target:'_blank'
  11456. * }' );
  11457. * ```
  11458. */
  11459. /**
  11460. * 返回当前选中的第一个超链接节点
  11461. * @command link
  11462. * @method queryCommandValue
  11463. * @param { String } cmd 命令字符串
  11464. * @return { Element } 超链接节点
  11465. * @example
  11466. * ```javascript
  11467. * editor.queryCommandValue( 'link' );
  11468. * ```
  11469. */
  11470. /**
  11471. * 取消超链接
  11472. * @command unlink
  11473. * @method execCommand
  11474. * @param { String } cmd 命令字符串
  11475. * @example
  11476. * ```javascript
  11477. * editor.execCommand( 'unlink');
  11478. * ```
  11479. */
  11480. UE.plugins['link'] = function () {
  11481. function optimize(range) {
  11482. var start = range.startContainer, end = range.endContainer;
  11483. if (start = domUtils.findParentByTagName(start, 'a', true)) {
  11484. range.setStartBefore(start);
  11485. }
  11486. if (end = domUtils.findParentByTagName(end, 'a', true)) {
  11487. range.setEndAfter(end);
  11488. }
  11489. }
  11490. UE.commands['unlink'] = {
  11491. execCommand: function () {
  11492. var range = this.selection.getRange(),
  11493. bookmark;
  11494. if (range.collapsed && !domUtils.findParentByTagName(range.startContainer, 'a', true)) {
  11495. return;
  11496. }
  11497. bookmark = range.createBookmark();
  11498. optimize(range);
  11499. range.removeInlineStyle('a').moveToBookmark(bookmark).select();
  11500. },
  11501. queryCommandState: function () {
  11502. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11503. }
  11504. };
  11505. function doLink(range, opt, me) {
  11506. var rngClone = range.cloneRange(),
  11507. link = me.queryCommandValue('link');
  11508. optimize(range = range.adjustmentBoundary());
  11509. var start = range.startContainer;
  11510. if (start.nodeType == 1 && link) {
  11511. start = start.childNodes[range.startOffset];
  11512. if (start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie ? 'innerText' : 'textContent'])) {
  11513. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue || opt.href);
  11514. }
  11515. }
  11516. if (!rngClone.collapsed || link) {
  11517. range.removeInlineStyle('a');
  11518. rngClone = range.cloneRange();
  11519. }
  11520. if (rngClone.collapsed) {
  11521. var a = range.document.createElement('a'),
  11522. text = '';
  11523. if (opt.textValue) {
  11524. text = utils.html(opt.textValue);
  11525. delete opt.textValue;
  11526. } else {
  11527. text = utils.html(opt.href);
  11528. }
  11529. domUtils.setAttributes(a, opt);
  11530. start = domUtils.findParentByTagName(rngClone.startContainer, 'a', true);
  11531. if (start && domUtils.isInNodeEndBoundary(rngClone, start)) {
  11532. range.setStartAfter(start).collapse(true);
  11533. }
  11534. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11535. range.insertNode(a).selectNode(a);
  11536. } else {
  11537. range.applyInlineStyle('a', opt);
  11538. }
  11539. }
  11540. UE.commands['link'] = {
  11541. execCommand: function (cmdName, opt) {
  11542. var range;
  11543. opt._href && (opt._href = utils.unhtml(opt._href, /[<">]/g));
  11544. opt.href && (opt.href = utils.unhtml(opt.href, /[<">]/g));
  11545. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue, /[<">]/g));
  11546. doLink(range = this.selection.getRange(), opt, this);
  11547. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11548. range.collapse().select(true);
  11549. },
  11550. queryCommandValue: function () {
  11551. var range = this.selection.getRange(),
  11552. node;
  11553. if (range.collapsed) {
  11554. // node = this.selection.getStart();
  11555. //在ie下getstart()取值偏上了
  11556. node = range.startContainer;
  11557. node = node.nodeType == 1 ? node : node.parentNode;
  11558. if (node && (node = domUtils.findParentByTagName(node, 'a', true)) && !domUtils.isInNodeEndBoundary(range, node)) {
  11559. return node;
  11560. }
  11561. } else {
  11562. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11563. range.shrinkBoundary();
  11564. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11565. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset - 1],
  11566. common = range.getCommonAncestor();
  11567. node = domUtils.findParentByTagName(common, 'a', true);
  11568. if (!node && common.nodeType == 1) {
  11569. var as = common.getElementsByTagName('a'),
  11570. ps, pe;
  11571. for (var i = 0, ci; ci = as[i++];) {
  11572. ps = domUtils.getPosition(ci, start), pe = domUtils.getPosition(ci, end);
  11573. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11574. &&
  11575. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11576. ) {
  11577. node = ci;
  11578. break;
  11579. }
  11580. }
  11581. }
  11582. return node;
  11583. }
  11584. },
  11585. queryCommandState: function () {
  11586. //判断如果是视频的话连接不可用
  11587. //fix 853
  11588. var img = this.selection.getRange().getClosedNode(),
  11589. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video") != -1);
  11590. return flag ? -1 : 0;
  11591. }
  11592. };
  11593. };
  11594. // plugins/iframe.js
  11595. ///import core
  11596. ///import plugins\inserthtml.js
  11597. ///commands 插入框架
  11598. ///commandsName InsertFrame
  11599. ///commandsTitle 插入Iframe
  11600. ///commandsDialog dialogs\insertframe
  11601. UE.plugins['insertframe'] = function () {
  11602. var me = this;
  11603. function deleteIframe() {
  11604. me._iframe && delete me._iframe;
  11605. }
  11606. me.addListener("selectionchange", function () {
  11607. deleteIframe();
  11608. });
  11609. };
  11610. // plugins/scrawl.js
  11611. ///import core
  11612. ///commands 涂鸦
  11613. ///commandsName Scrawl
  11614. ///commandsTitle 涂鸦
  11615. ///commandsDialog dialogs\scrawl
  11616. UE.commands['scrawl'] = {
  11617. queryCommandState: function () {
  11618. return (browser.ie && browser.version <= 8) ? -1 : 0;
  11619. }
  11620. };
  11621. // plugins/removeformat.js
  11622. /**
  11623. * 清除格式
  11624. * @file
  11625. * @since 1.2.6.1
  11626. */
  11627. /**
  11628. * 清除文字样式
  11629. * @command removeformat
  11630. * @method execCommand
  11631. * @param { String } cmd 命令字符串
  11632. * @param {String} tags 以逗号隔开的标签。如:strong
  11633. * @param {String} style 样式如:color
  11634. * @param {String} attrs 属性如:width
  11635. * @example
  11636. * ```javascript
  11637. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11638. * ```
  11639. */
  11640. UE.plugins['removeformat'] = function () {
  11641. var me = this;
  11642. me.setOpt({
  11643. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11644. 'removeFormatAttributes': 'class,style,lang,width,height,align,hspace,valign'
  11645. });
  11646. me.commands['removeformat'] = {
  11647. execCommand: function (cmdName, tags, style, attrs, notIncludeA) {
  11648. var tagReg = new RegExp('^(?:' + (tags || this.options.removeFormatTags).replace(/,/g, '|') + ')$', 'i'),
  11649. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split(','),
  11650. range = new dom.Range(this.document),
  11651. bookmark, node, parent,
  11652. filter = function (node) {
  11653. return node.nodeType == 1;
  11654. };
  11655. function isRedundantSpan(node) {
  11656. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span') {
  11657. return 0;
  11658. }
  11659. if (browser.ie) {
  11660. //ie 下判断实效,所以只能简单用style来判断
  11661. //return node.style.cssText == '' ? 1 : 0;
  11662. var attrs = node.attributes;
  11663. if (attrs.length) {
  11664. for (var i = 0, l = attrs.length; i < l; i++) {
  11665. if (attrs[i].specified) {
  11666. return 0;
  11667. }
  11668. }
  11669. return 1;
  11670. }
  11671. }
  11672. return !node.attributes.length;
  11673. }
  11674. function doRemove(range) {
  11675. var bookmark1 = range.createBookmark();
  11676. if (range.collapsed) {
  11677. range.enlarge(true);
  11678. }
  11679. //不能把a标签切了
  11680. if (!notIncludeA) {
  11681. var aNode = domUtils.findParentByTagName(range.startContainer, 'a', true);
  11682. if (aNode) {
  11683. range.setStartBefore(aNode);
  11684. }
  11685. aNode = domUtils.findParentByTagName(range.endContainer, 'a', true);
  11686. if (aNode) {
  11687. range.setEndAfter(aNode);
  11688. }
  11689. }
  11690. bookmark = range.createBookmark();
  11691. node = bookmark.start;
  11692. //切开始
  11693. while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
  11694. domUtils.breakParent(node, parent);
  11695. domUtils.clearEmptySibling(node);
  11696. }
  11697. if (bookmark.end) {
  11698. //切结束
  11699. node = bookmark.end;
  11700. while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
  11701. domUtils.breakParent(node, parent);
  11702. domUtils.clearEmptySibling(node);
  11703. }
  11704. //开始去除样式
  11705. var current = domUtils.getNextDomNode(bookmark.start, false, filter),
  11706. next;
  11707. while (current) {
  11708. if (current == bookmark.end) {
  11709. break;
  11710. }
  11711. next = domUtils.getNextDomNode(current, true, filter);
  11712. if (!dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode(current)) {
  11713. if (tagReg.test(current.tagName)) {
  11714. if (style) {
  11715. domUtils.removeStyle(current, style);
  11716. if (isRedundantSpan(current) && style != 'text-decoration') {
  11717. domUtils.remove(current, true);
  11718. }
  11719. } else {
  11720. domUtils.remove(current, true);
  11721. }
  11722. } else {
  11723. //trace:939 不能把list上的样式去掉
  11724. if (!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]) {
  11725. domUtils.removeAttributes(current, removeFormatAttributes);
  11726. if (isRedundantSpan(current)) {
  11727. domUtils.remove(current, true);
  11728. }
  11729. }
  11730. }
  11731. }
  11732. current = next;
  11733. }
  11734. }
  11735. //trace:1035
  11736. //trace:1096 不能把td上的样式去掉,比如边框
  11737. var pN = bookmark.start.parentNode;
  11738. if (domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]) {
  11739. domUtils.removeAttributes(pN, removeFormatAttributes);
  11740. }
  11741. pN = bookmark.end.parentNode;
  11742. if (bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]) {
  11743. domUtils.removeAttributes(pN, removeFormatAttributes);
  11744. }
  11745. range.moveToBookmark(bookmark).moveToBookmark(bookmark1);
  11746. //清除冗余的代码 <b><bookmark></b>
  11747. var node = range.startContainer,
  11748. tmp,
  11749. collapsed = range.collapsed;
  11750. while (node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]) {
  11751. tmp = node.parentNode;
  11752. range.setStartBefore(node);
  11753. //trace:937
  11754. //更新结束边界
  11755. if (range.startContainer === range.endContainer) {
  11756. range.endOffset--;
  11757. }
  11758. domUtils.remove(node);
  11759. node = tmp;
  11760. }
  11761. if (!collapsed) {
  11762. node = range.endContainer;
  11763. while (node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]) {
  11764. tmp = node.parentNode;
  11765. range.setEndBefore(node);
  11766. domUtils.remove(node);
  11767. node = tmp;
  11768. }
  11769. }
  11770. }
  11771. range = this.selection.getRange();
  11772. doRemove(range);
  11773. range.select();
  11774. }
  11775. };
  11776. };
  11777. // plugins/blockquote.js
  11778. /**
  11779. * 添加引用
  11780. * @file
  11781. * @since 1.2.6.1
  11782. */
  11783. /**
  11784. * 添加引用
  11785. * @command blockquote
  11786. * @method execCommand
  11787. * @param { String } cmd 命令字符串
  11788. * @example
  11789. * ```javascript
  11790. * editor.execCommand( 'blockquote' );
  11791. * ```
  11792. */
  11793. /**
  11794. * 添加引用
  11795. * @command blockquote
  11796. * @method execCommand
  11797. * @param { String } cmd 命令字符串
  11798. * @param { Object } attrs 节点属性
  11799. * @example
  11800. * ```javascript
  11801. * editor.execCommand( 'blockquote',{
  11802. * style: "color: red;"
  11803. * } );
  11804. * ```
  11805. */
  11806. UE.plugins['blockquote'] = function () {
  11807. var me = this;
  11808. function getObj(editor) {
  11809. return domUtils.filterNodeList(editor.selection.getStartElementPath(), 'blockquote');
  11810. }
  11811. me.commands['blockquote'] = {
  11812. execCommand: function (cmdName, attrs) {
  11813. var range = this.selection.getRange(),
  11814. obj = getObj(this),
  11815. blockquote = dtd.blockquote,
  11816. bookmark = range.createBookmark();
  11817. if (obj) {
  11818. var start = range.startContainer,
  11819. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start, function (node) {
  11820. return domUtils.isBlockElm(node)
  11821. }),
  11822. end = range.endContainer,
  11823. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end, function (node) {
  11824. return domUtils.isBlockElm(node)
  11825. });
  11826. //处理一下li
  11827. startBlock = domUtils.findParentByTagName(startBlock, 'li', true) || startBlock;
  11828. endBlock = domUtils.findParentByTagName(endBlock, 'li', true) || endBlock;
  11829. if (startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)) {
  11830. domUtils.remove(obj, true);
  11831. } else {
  11832. domUtils.breakParent(startBlock, obj);
  11833. }
  11834. if (startBlock !== endBlock) {
  11835. obj = domUtils.findParentByTagName(endBlock, 'blockquote');
  11836. if (obj) {
  11837. if (endBlock.tagName == 'LI' || endBlock.tagName == 'TD' || domUtils.isBody(endBlock)) {
  11838. obj.parentNode && domUtils.remove(obj, true);
  11839. } else {
  11840. domUtils.breakParent(endBlock, obj);
  11841. }
  11842. }
  11843. }
  11844. var blockquotes = domUtils.getElementsByTagName(this.document, 'blockquote');
  11845. for (var i = 0, bi; bi = blockquotes[i++];) {
  11846. if (!bi.childNodes.length) {
  11847. domUtils.remove(bi);
  11848. } else if (domUtils.getPosition(bi, startBlock) & domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi, endBlock) & domUtils.POSITION_PRECEDING) {
  11849. domUtils.remove(bi, true);
  11850. }
  11851. }
  11852. } else {
  11853. var tmpRange = range.cloneRange(),
  11854. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11855. preNode = node,
  11856. doEnd = 1;
  11857. //调整开始
  11858. while (1) {
  11859. if (domUtils.isBody(node)) {
  11860. if (preNode !== node) {
  11861. if (range.collapsed) {
  11862. tmpRange.selectNode(preNode);
  11863. doEnd = 0;
  11864. } else {
  11865. tmpRange.setStartBefore(preNode);
  11866. }
  11867. } else {
  11868. tmpRange.setStart(node, 0);
  11869. }
  11870. break;
  11871. }
  11872. if (!blockquote[node.tagName]) {
  11873. if (range.collapsed) {
  11874. tmpRange.selectNode(preNode);
  11875. } else {
  11876. tmpRange.setStartBefore(preNode);
  11877. }
  11878. break;
  11879. }
  11880. preNode = node;
  11881. node = node.parentNode;
  11882. }
  11883. //调整结束
  11884. if (doEnd) {
  11885. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11886. while (1) {
  11887. if (domUtils.isBody(node)) {
  11888. if (preNode !== node) {
  11889. tmpRange.setEndAfter(preNode);
  11890. } else {
  11891. tmpRange.setEnd(node, node.childNodes.length);
  11892. }
  11893. break;
  11894. }
  11895. if (!blockquote[node.tagName]) {
  11896. tmpRange.setEndAfter(preNode);
  11897. break;
  11898. }
  11899. preNode = node;
  11900. node = node.parentNode;
  11901. }
  11902. }
  11903. node = range.document.createElement('blockquote');
  11904. domUtils.setAttributes(node, attrs);
  11905. node.appendChild(tmpRange.extractContents());
  11906. tmpRange.insertNode(node);
  11907. //去除重复的
  11908. var childs = domUtils.getElementsByTagName(node, 'blockquote');
  11909. for (var i = 0, ci; ci = childs[i++];) {
  11910. if (ci.parentNode) {
  11911. domUtils.remove(ci, true);
  11912. }
  11913. }
  11914. }
  11915. range.moveToBookmark(bookmark).select();
  11916. },
  11917. queryCommandState: function () {
  11918. return getObj(this) ? 1 : 0;
  11919. }
  11920. };
  11921. };
  11922. // plugins/convertcase.js
  11923. /**
  11924. * 大小写转换
  11925. * @file
  11926. * @since 1.2.6.1
  11927. */
  11928. /**
  11929. * 把选区内文本变大写,与“tolowercase”命令互斥
  11930. * @command touppercase
  11931. * @method execCommand
  11932. * @param { String } cmd 命令字符串
  11933. * @example
  11934. * ```javascript
  11935. * editor.execCommand( 'touppercase' );
  11936. * ```
  11937. */
  11938. /**
  11939. * 把选区内文本变小写,与“touppercase”命令互斥
  11940. * @command tolowercase
  11941. * @method execCommand
  11942. * @param { String } cmd 命令字符串
  11943. * @example
  11944. * ```javascript
  11945. * editor.execCommand( 'tolowercase' );
  11946. * ```
  11947. */
  11948. UE.commands['touppercase'] =
  11949. UE.commands['tolowercase'] = {
  11950. execCommand: function (cmd) {
  11951. var me = this;
  11952. var rng = me.selection.getRange();
  11953. if (rng.collapsed) {
  11954. return rng;
  11955. }
  11956. var bk = rng.createBookmark(),
  11957. bkEnd = bk.end,
  11958. filterFn = function (node) {
  11959. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  11960. },
  11961. curNode = domUtils.getNextDomNode(bk.start, false, filterFn);
  11962. while (curNode && (domUtils.getPosition(curNode, bkEnd) & domUtils.POSITION_PRECEDING)) {
  11963. if (curNode.nodeType == 3) {
  11964. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11965. }
  11966. curNode = domUtils.getNextDomNode(curNode, true, filterFn);
  11967. if (curNode === bkEnd) {
  11968. break;
  11969. }
  11970. }
  11971. rng.moveToBookmark(bk).select();
  11972. }
  11973. };
  11974. // plugins/indent.js
  11975. /**
  11976. * 首行缩进
  11977. * @file
  11978. * @since 1.2.6.1
  11979. */
  11980. /**
  11981. * 缩进
  11982. * @command indent
  11983. * @method execCommand
  11984. * @param { String } cmd 命令字符串
  11985. * @example
  11986. * ```javascript
  11987. * editor.execCommand( 'indent' );
  11988. * ```
  11989. */
  11990. UE.commands['indent'] = {
  11991. execCommand: function () {
  11992. var me = this, value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11993. me.execCommand('Paragraph', 'p', {style: 'text-indent:' + value});
  11994. },
  11995. queryCommandState: function () {
  11996. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), 'p h1 h2 h3 h4 h5 h6');
  11997. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11998. }
  11999. };
  12000. // plugins/print.js
  12001. /**
  12002. * 打印
  12003. * @file
  12004. * @since 1.2.6.1
  12005. */
  12006. /**
  12007. * 打印
  12008. * @command print
  12009. * @method execCommand
  12010. * @param { String } cmd 命令字符串
  12011. * @example
  12012. * ```javascript
  12013. * editor.execCommand( 'print' );
  12014. * ```
  12015. */
  12016. UE.commands['print'] = {
  12017. execCommand: function () {
  12018. this.window.print();
  12019. },
  12020. notNeedUndo: 1
  12021. };
  12022. // plugins/preview.js
  12023. /**
  12024. * 预览
  12025. * @file
  12026. * @since 1.2.6.1
  12027. */
  12028. /**
  12029. * 预览
  12030. * @command preview
  12031. * @method execCommand
  12032. * @param { String } cmd 命令字符串
  12033. * @example
  12034. * ```javascript
  12035. * editor.execCommand( 'preview' );
  12036. * ```
  12037. */
  12038. UE.commands['preview'] = {
  12039. execCommand: function() {
  12040. var w = window.open('', '_blank', ''),
  12041. d = w.document;
  12042. d.open();
  12043. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="' + this.options.UEDITOR_HOME_URL + 'ueditor.parse.js"></script><script>' +
  12044. 'setTimeout(function(){uParse(\'div\',{rootPath: \'' + this.options.UEDITOR_HOME_URL + '\'})},300)' +
  12045. '</script></head><body><div>' + this.getContent(null, null, true) + '</div></body></html>');
  12046. d.close();
  12047. },
  12048. notNeedUndo: 1,
  12049. };
  12050. // plugins/selectall.js
  12051. /**
  12052. * 全选
  12053. * @file
  12054. * @since 1.2.6.1
  12055. */
  12056. /**
  12057. * 选中所有内容
  12058. * @command selectall
  12059. * @method execCommand
  12060. * @param { String } cmd 命令字符串
  12061. * @example
  12062. * ```javascript
  12063. * editor.execCommand( 'selectall' );
  12064. * ```
  12065. */
  12066. UE.plugins['selectall'] = function () {
  12067. var me = this;
  12068. me.commands['selectall'] = {
  12069. execCommand: function () {
  12070. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  12071. var me = this, body = me.body,
  12072. range = me.selection.getRange();
  12073. range.selectNodeContents(body);
  12074. if (domUtils.isEmptyBlock(body)) {
  12075. //opera不能自动合并到元素的里边,要手动处理一下
  12076. if (browser.opera && body.firstChild && body.firstChild.nodeType == 1) {
  12077. range.setStartAtFirst(body.firstChild);
  12078. }
  12079. range.collapse(true);
  12080. }
  12081. range.select(true);
  12082. },
  12083. notNeedUndo: 1
  12084. };
  12085. //快捷键
  12086. me.addshortcutkey({
  12087. "selectAll": "ctrl+65"
  12088. });
  12089. };
  12090. // plugins/paragraph.js
  12091. /**
  12092. * 段落样式
  12093. * @file
  12094. * @since 1.2.6.1
  12095. */
  12096. /**
  12097. * 段落格式
  12098. * @command paragraph
  12099. * @method execCommand
  12100. * @param { String } cmd 命令字符串
  12101. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  12102. * @param {Object} attrs 标签的属性
  12103. * @example
  12104. * ```javascript
  12105. * editor.execCommand( 'Paragraph','h1','{
  12106. * class:'test'
  12107. * }' );
  12108. * ```
  12109. */
  12110. /**
  12111. * 返回选区内节点标签名
  12112. * @command paragraph
  12113. * @method queryCommandValue
  12114. * @param { String } cmd 命令字符串
  12115. * @return { String } 节点标签名
  12116. * @example
  12117. * ```javascript
  12118. * editor.queryCommandValue( 'Paragraph' );
  12119. * ```
  12120. */
  12121. UE.plugins['paragraph'] = function () {
  12122. var me = this,
  12123. block = domUtils.isBlockElm,
  12124. notExchange = ['TD', 'LI', 'PRE'],
  12125. doParagraph = function (range, style, attrs, sourceCmdName) {
  12126. var bookmark = range.createBookmark(),
  12127. filterFn = function (node) {
  12128. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  12129. },
  12130. para;
  12131. range.enlarge(true);
  12132. var bookmark2 = range.createBookmark(),
  12133. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  12134. tmpRange = range.cloneRange(),
  12135. tmpNode;
  12136. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  12137. if (current.nodeType == 3 || !block(current)) {
  12138. tmpRange.setStartBefore(current);
  12139. while (current && current !== bookmark2.end && !block(current)) {
  12140. tmpNode = current;
  12141. current = domUtils.getNextDomNode(current, false, null, function (node) {
  12142. return !block(node);
  12143. });
  12144. }
  12145. tmpRange.setEndAfter(tmpNode);
  12146. para = range.document.createElement(style);
  12147. if (attrs) {
  12148. domUtils.setAttributes(para, attrs);
  12149. if (sourceCmdName && sourceCmdName == 'customstyle' && attrs.style) {
  12150. para.style.cssText = attrs.style;
  12151. }
  12152. }
  12153. para.appendChild(tmpRange.extractContents());
  12154. //需要内容占位
  12155. if (domUtils.isEmptyNode(para)) {
  12156. domUtils.fillChar(range.document, para);
  12157. }
  12158. tmpRange.insertNode(para);
  12159. var parent = para.parentNode;
  12160. //如果para上一级是一个block元素且不是body,td就删除它
  12161. if (block(parent) && !domUtils.isBody(para.parentNode) && utils.indexOf(notExchange, parent.tagName) == -1) {
  12162. //存储dir,style
  12163. if (!(sourceCmdName && sourceCmdName == 'customstyle')) {
  12164. parent.getAttribute('dir') && para.setAttribute('dir', parent.getAttribute('dir'));
  12165. //trace:1070
  12166. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  12167. //trace:1030
  12168. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  12169. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  12170. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  12171. }
  12172. //trace:1706 选择的就是h1-6要删除
  12173. if (attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName)) {
  12174. domUtils.setAttributes(parent, attrs);
  12175. if (sourceCmdName && sourceCmdName == 'customstyle' && attrs.style) {
  12176. parent.style.cssText = attrs.style;
  12177. }
  12178. domUtils.remove(para, true);
  12179. para = parent;
  12180. } else {
  12181. domUtils.remove(para.parentNode, true);
  12182. }
  12183. }
  12184. if (utils.indexOf(notExchange, parent.tagName) != -1) {
  12185. current = parent;
  12186. } else {
  12187. current = para;
  12188. }
  12189. current = domUtils.getNextDomNode(current, false, filterFn);
  12190. } else {
  12191. current = domUtils.getNextDomNode(current, true, filterFn);
  12192. }
  12193. }
  12194. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  12195. };
  12196. me.setOpt('paragraph', {'p': '', 'h1': '', 'h2': '', 'h3': '', 'h4': '', 'h5': '', 'h6': ''});
  12197. me.commands['paragraph'] = {
  12198. execCommand: function (cmdName, style, attrs, sourceCmdName) {
  12199. var range = this.selection.getRange();
  12200. //闭合时单独处理
  12201. if (range.collapsed) {
  12202. var txt = this.document.createTextNode('p');
  12203. range.insertNode(txt);
  12204. //去掉冗余的fillchar
  12205. if (browser.ie) {
  12206. var node = txt.previousSibling;
  12207. if (node && domUtils.isWhitespace(node)) {
  12208. domUtils.remove(node);
  12209. }
  12210. node = txt.nextSibling;
  12211. if (node && domUtils.isWhitespace(node)) {
  12212. domUtils.remove(node);
  12213. }
  12214. }
  12215. }
  12216. range = doParagraph(range, style, attrs, sourceCmdName);
  12217. if (txt) {
  12218. range.setStartBefore(txt).collapse(true);
  12219. pN = txt.parentNode;
  12220. domUtils.remove(txt);
  12221. if (domUtils.isBlockElm(pN) && domUtils.isEmptyNode(pN)) {
  12222. domUtils.fillNode(this.document, pN);
  12223. }
  12224. }
  12225. if (browser.gecko && range.collapsed && range.startContainer.nodeType == 1) {
  12226. var child = range.startContainer.childNodes[range.startOffset];
  12227. if (child && child.nodeType == 1 && child.tagName.toLowerCase() == style) {
  12228. range.setStart(child, 0).collapse(true);
  12229. }
  12230. }
  12231. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  12232. range.select();
  12233. return true;
  12234. },
  12235. queryCommandValue: function () {
  12236. var node = domUtils.filterNodeList(this.selection.getStartElementPath(), 'p h1 h2 h3 h4 h5 h6');
  12237. return node ? node.tagName.toLowerCase() : '';
  12238. }
  12239. };
  12240. };
  12241. // plugins/directionality.js
  12242. /**
  12243. * 设置文字输入的方向的插件
  12244. * @file
  12245. * @since 1.2.6.1
  12246. */
  12247. (function () {
  12248. var block = domUtils.isBlockElm,
  12249. getObj = function (editor) {
  12250. // var startNode = editor.selection.getStart(),
  12251. // parents;
  12252. // if ( startNode ) {
  12253. // //查找所有的是block的父亲节点
  12254. // parents = domUtils.findParents( startNode, true, block, true );
  12255. // for ( var i = 0,ci; ci = parents[i++]; ) {
  12256. // if ( ci.getAttribute( 'dir' ) ) {
  12257. // return ci;
  12258. // }
  12259. // }
  12260. // }
  12261. return domUtils.filterNodeList(editor.selection.getStartElementPath(), function (n) {
  12262. return n && n.nodeType == 1 && n.getAttribute('dir')
  12263. });
  12264. },
  12265. doDirectionality = function (range, editor, forward) {
  12266. var bookmark,
  12267. filterFn = function (node) {
  12268. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  12269. },
  12270. obj = getObj(editor);
  12271. if (obj && range.collapsed) {
  12272. obj.setAttribute('dir', forward);
  12273. return range;
  12274. }
  12275. bookmark = range.createBookmark();
  12276. range.enlarge(true);
  12277. var bookmark2 = range.createBookmark(),
  12278. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  12279. tmpRange = range.cloneRange(),
  12280. tmpNode;
  12281. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  12282. if (current.nodeType == 3 || !block(current)) {
  12283. tmpRange.setStartBefore(current);
  12284. while (current && current !== bookmark2.end && !block(current)) {
  12285. tmpNode = current;
  12286. current = domUtils.getNextDomNode(current, false, null, function (node) {
  12287. return !block(node);
  12288. });
  12289. }
  12290. tmpRange.setEndAfter(tmpNode);
  12291. var common = tmpRange.getCommonAncestor();
  12292. if (!domUtils.isBody(common) && block(common)) {
  12293. //遍历到了block节点
  12294. common.setAttribute('dir', forward);
  12295. current = common;
  12296. } else {
  12297. //没有遍历到,添加一个block节点
  12298. var p = range.document.createElement('p');
  12299. p.setAttribute('dir', forward);
  12300. var frag = tmpRange.extractContents();
  12301. p.appendChild(frag);
  12302. tmpRange.insertNode(p);
  12303. current = p;
  12304. }
  12305. current = domUtils.getNextDomNode(current, false, filterFn);
  12306. } else {
  12307. current = domUtils.getNextDomNode(current, true, filterFn);
  12308. }
  12309. }
  12310. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  12311. };
  12312. /**
  12313. * 文字输入方向
  12314. * @command directionality
  12315. * @method execCommand
  12316. * @param { String } cmdName 命令字符串
  12317. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  12318. * @example
  12319. * ```javascript
  12320. * editor.execCommand( 'directionality', 'ltr');
  12321. * ```
  12322. */
  12323. /**
  12324. * 查询当前选区的文字输入方向
  12325. * @command directionality
  12326. * @method queryCommandValue
  12327. * @param { String } cmdName 命令字符串
  12328. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  12329. * @example
  12330. * ```javascript
  12331. * editor.queryCommandValue( 'directionality');
  12332. * ```
  12333. */
  12334. UE.commands['directionality'] = {
  12335. execCommand: function (cmdName, forward) {
  12336. var range = this.selection.getRange();
  12337. //闭合时单独处理
  12338. if (range.collapsed) {
  12339. var txt = this.document.createTextNode('d');
  12340. range.insertNode(txt);
  12341. }
  12342. doDirectionality(range, this, forward);
  12343. if (txt) {
  12344. range.setStartBefore(txt).collapse(true);
  12345. domUtils.remove(txt);
  12346. }
  12347. range.select();
  12348. return true;
  12349. },
  12350. queryCommandValue: function () {
  12351. var node = getObj(this);
  12352. return node ? node.getAttribute('dir') : 'ltr';
  12353. }
  12354. };
  12355. })();
  12356. // plugins/horizontal.js
  12357. /**
  12358. * 插入分割线插件
  12359. * @file
  12360. * @since 1.2.6.1
  12361. */
  12362. /**
  12363. * 插入分割线
  12364. * @command horizontal
  12365. * @method execCommand
  12366. * @param { String } cmdName 命令字符串
  12367. * @example
  12368. * ```javascript
  12369. * editor.execCommand( 'horizontal' );
  12370. * ```
  12371. */
  12372. UE.plugins['horizontal'] = function () {
  12373. var me = this;
  12374. me.commands['horizontal'] = {
  12375. execCommand: function (cmdName) {
  12376. var me = this;
  12377. if (me.queryCommandState(cmdName) !== -1) {
  12378. me.execCommand('insertHtml', '<hr>');
  12379. var range = me.selection.getRange(),
  12380. start = range.startContainer;
  12381. if (start.nodeType == 1 && !start.childNodes[range.startOffset]) {
  12382. var tmp;
  12383. if (tmp = start.childNodes[range.startOffset - 1]) {
  12384. if (tmp.nodeType == 1 && tmp.tagName == 'HR') {
  12385. if (me.options.enterTag == 'p') {
  12386. tmp = me.document.createElement('p');
  12387. range.insertNode(tmp);
  12388. range.setStart(tmp, 0).setCursor();
  12389. } else {
  12390. tmp = me.document.createElement('br');
  12391. range.insertNode(tmp);
  12392. range.setStartBefore(tmp).setCursor();
  12393. }
  12394. }
  12395. }
  12396. }
  12397. return true;
  12398. }
  12399. },
  12400. //边界在table里不能加分隔线
  12401. queryCommandState: function () {
  12402. return domUtils.filterNodeList(this.selection.getStartElementPath(), 'table') ? -1 : 0;
  12403. }
  12404. };
  12405. // me.addListener('delkeyup',function(){
  12406. // var rng = this.selection.getRange();
  12407. // if(browser.ie && browser.version > 8){
  12408. // rng.txtToElmBoundary(true);
  12409. // if(domUtils.isStartInblock(rng)){
  12410. // var tmpNode = rng.startContainer;
  12411. // var pre = tmpNode.previousSibling;
  12412. // if(pre && domUtils.isTagNode(pre,'hr')){
  12413. // domUtils.remove(pre);
  12414. // rng.select();
  12415. // return;
  12416. // }
  12417. // }
  12418. // }
  12419. // if(domUtils.isBody(rng.startContainer)){
  12420. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12421. // if(hr && hr.nodeName == 'HR'){
  12422. // var next = hr.nextSibling;
  12423. // if(next){
  12424. // rng.setStart(next,0)
  12425. // }else if(hr.previousSibling){
  12426. // rng.setStartAtLast(hr.previousSibling)
  12427. // }else{
  12428. // var p = this.document.createElement('p');
  12429. // hr.parentNode.insertBefore(p,hr);
  12430. // domUtils.fillNode(this.document,p);
  12431. // rng.setStart(p,0);
  12432. // }
  12433. // domUtils.remove(hr);
  12434. // rng.setCursor(false,true);
  12435. // }
  12436. // }
  12437. // })
  12438. me.addListener('delkeydown', function (name, evt) {
  12439. var rng = this.selection.getRange();
  12440. rng.txtToElmBoundary(true);
  12441. if (domUtils.isStartInblock(rng)) {
  12442. var tmpNode = rng.startContainer;
  12443. var pre = tmpNode.previousSibling;
  12444. if (pre && domUtils.isTagNode(pre, 'hr')) {
  12445. domUtils.remove(pre);
  12446. rng.select();
  12447. domUtils.preventDefault(evt);
  12448. return true;
  12449. }
  12450. }
  12451. })
  12452. };
  12453. // plugins/time.js
  12454. /**
  12455. * 插入时间和日期
  12456. * @file
  12457. * @since 1.2.6.1
  12458. */
  12459. /**
  12460. * 插入时间,默认格式:12:59:59
  12461. * @command time
  12462. * @method execCommand
  12463. * @param { String } cmd 命令字符串
  12464. * @example
  12465. * ```javascript
  12466. * editor.execCommand( 'time');
  12467. * ```
  12468. */
  12469. /**
  12470. * 插入日期,默认格式:2013-08-30
  12471. * @command date
  12472. * @method execCommand
  12473. * @param { String } cmd 命令字符串
  12474. * @example
  12475. * ```javascript
  12476. * editor.execCommand( 'date');
  12477. * ```
  12478. */
  12479. UE.commands['time'] = UE.commands["date"] = {
  12480. execCommand: function (cmd, format) {
  12481. var date = new Date;
  12482. function formatTime(date, format) {
  12483. var hh = ('0' + date.getHours()).slice(-2),
  12484. ii = ('0' + date.getMinutes()).slice(-2),
  12485. ss = ('0' + date.getSeconds()).slice(-2);
  12486. format = format || 'hh:ii:ss';
  12487. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12488. }
  12489. function formatDate(date, format) {
  12490. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12491. yy = yyyy.slice(-2),
  12492. mm = ('0' + (date.getMonth() + 1)).slice(-2),
  12493. dd = ('0' + date.getDate()).slice(-2);
  12494. format = format || 'yyyy-mm-dd';
  12495. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12496. }
  12497. this.execCommand('insertHtml', cmd == "time" ? formatTime(date, format) : formatDate(date, format));
  12498. }
  12499. };
  12500. // plugins/rowspacing.js
  12501. /**
  12502. * 段前段后间距插件
  12503. * @file
  12504. * @since 1.2.6.1
  12505. */
  12506. /**
  12507. * 设置段间距
  12508. * @command rowspacing
  12509. * @method execCommand
  12510. * @param { String } cmd 命令字符串
  12511. * @param { String } value 段间距的值,以px为单位
  12512. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12513. * @example
  12514. * ```javascript
  12515. * editor.execCommand( 'rowspacing', '10', 'top' );
  12516. * ```
  12517. */
  12518. UE.plugins['rowspacing'] = function () {
  12519. var me = this;
  12520. me.setOpt({
  12521. 'rowspacingtop': ['5', '10', '15', '20', '25'],
  12522. 'rowspacingbottom': ['5', '10', '15', '20', '25']
  12523. });
  12524. me.commands['rowspacing'] = {
  12525. execCommand: function (cmdName, value, dir) {
  12526. this.execCommand('paragraph', 'p', {style: 'margin-' + dir + ':' + value + 'px'});
  12527. return true;
  12528. },
  12529. queryCommandValue: function (cmdName, dir) {
  12530. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), function (node) {
  12531. return domUtils.isBlockElm(node)
  12532. }),
  12533. value;
  12534. //trace:1026
  12535. if (pN) {
  12536. value = domUtils.getComputedStyle(pN, 'margin-' + dir).replace(/[^\d]/g, '');
  12537. return !value ? 0 : value;
  12538. }
  12539. return 0;
  12540. }
  12541. };
  12542. };
  12543. // plugins/lineheight.js
  12544. /**
  12545. * 设置行内间距
  12546. * @file
  12547. * @since 1.2.6.1
  12548. */
  12549. UE.plugins['lineheight'] = function () {
  12550. var me = this;
  12551. me.setOpt({'lineheight': ['1', '1.5', '1.75', '2', '3', '4', '5']});
  12552. /**
  12553. * 行距
  12554. * @command lineheight
  12555. * @method execCommand
  12556. * @param { String } cmdName 命令字符串
  12557. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12558. * @example
  12559. * ```javascript
  12560. * editor.execCommand( 'lineheight', 1.5);
  12561. * ```
  12562. */
  12563. /**
  12564. * 查询当前选区内容的行高大小
  12565. * @command lineheight
  12566. * @method queryCommandValue
  12567. * @param { String } cmd 命令字符串
  12568. * @return { String } 返回当前行高大小
  12569. * @example
  12570. * ```javascript
  12571. * editor.queryCommandValue( 'lineheight' );
  12572. * ```
  12573. */
  12574. me.commands['lineheight'] = {
  12575. execCommand: function (cmdName, value) {
  12576. this.execCommand('paragraph', 'p', {style: 'line-height:' + (value == "1" ? "normal" : value + 'em')});
  12577. return true;
  12578. },
  12579. queryCommandValue: function () {
  12580. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), function (node) {
  12581. return domUtils.isBlockElm(node)
  12582. });
  12583. if (pN) {
  12584. var value = domUtils.getComputedStyle(pN, 'line-height');
  12585. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig, "");
  12586. }
  12587. }
  12588. };
  12589. };
  12590. // plugins/insertcode.js
  12591. /**
  12592. * 插入代码插件
  12593. * @file
  12594. * @since 1.2.6.1
  12595. */
  12596. UE.plugins['insertcode'] = function () {
  12597. var me = this;
  12598. me.ready(function () {
  12599. utils.cssRule('pre', 'pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12600. me.document)
  12601. });
  12602. me.setOpt('insertcode', {
  12603. 'as3': 'ActionScript3',
  12604. 'bash': 'Bash/Shell',
  12605. 'cpp': 'C/C++',
  12606. 'css': 'Css',
  12607. 'cf': 'CodeFunction',
  12608. 'c#': 'C#',
  12609. 'delphi': 'Delphi',
  12610. 'diff': 'Diff',
  12611. 'erlang': 'Erlang',
  12612. 'groovy': 'Groovy',
  12613. 'html': 'Html',
  12614. 'java': 'Java',
  12615. 'jfx': 'JavaFx',
  12616. 'js': 'Javascript',
  12617. 'pl': 'Perl',
  12618. 'php': 'Php',
  12619. 'plain': 'Plain Text',
  12620. 'ps': 'PowerShell',
  12621. 'python': 'Python',
  12622. 'ruby': 'Ruby',
  12623. 'scala': 'Scala',
  12624. 'sql': 'Sql',
  12625. 'vb': 'Vb',
  12626. 'xml': 'Xml'
  12627. });
  12628. /**
  12629. * 插入代码
  12630. * @command insertcode
  12631. * @method execCommand
  12632. * @param { String } cmd 命令字符串
  12633. * @param { String } lang 插入代码的语言
  12634. * @example
  12635. * ```javascript
  12636. * editor.execCommand( 'insertcode', 'javascript' );
  12637. * ```
  12638. */
  12639. /**
  12640. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12641. * @command insertcode
  12642. * @method queryCommandValue
  12643. * @param { String } cmd 命令字符串
  12644. * @return { String } 返回代码的语言
  12645. * @example
  12646. * ```javascript
  12647. * editor.queryCommandValue( 'insertcode' );
  12648. * ```
  12649. */
  12650. me.commands['insertcode'] = {
  12651. execCommand: function(cmd, lang) {
  12652. var me = this,
  12653. rng = me.selection.getRange(),
  12654. pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12655. if (pre) {
  12656. pre.className = 'brush:' + lang + ';toolbar:false;';
  12657. } else {
  12658. var code = '';
  12659. if (rng.collapsed) {
  12660. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;' : '') : '<br/>';
  12661. } else {
  12662. var frag = rng.extractContents();
  12663. var div = me.document.createElement('div');
  12664. div.appendChild(frag);
  12665. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g, '')), me.options.filterTxtRules).children, function(node) {
  12666. if (browser.ie && browser.ie11below && browser.version > 8) {
  12667. if (node.type == 'element') {
  12668. if (node.tagName == 'br') {
  12669. code += '\n'
  12670. } else if (!dtd.$empty[node.tagName]) {
  12671. utils.each(node.children, function (cn) {
  12672. if (cn.type == 'element') {
  12673. if (cn.tagName == 'br') {
  12674. code += '\n'
  12675. } else if (!dtd.$empty[node.tagName]) {
  12676. code += cn.innerText();
  12677. }
  12678. } else {
  12679. code += cn.data
  12680. }
  12681. })
  12682. if (!/\n$/.test(code)) {
  12683. code += '\n';
  12684. }
  12685. }
  12686. } else {
  12687. code += node.data + '\n'
  12688. }
  12689. if (!node.nextSibling() && /\n$/.test(code)) {
  12690. code = code.replace(/\n$/, '');
  12691. }
  12692. } else {
  12693. if (browser.ie && browser.ie11below) {
  12694. if (node.type == 'element') {
  12695. if (node.tagName == 'br') {
  12696. code += '<br>'
  12697. } else if (!dtd.$empty[node.tagName]) {
  12698. utils.each(node.children, function (cn) {
  12699. if (cn.type == 'element') {
  12700. if (cn.tagName == 'br') {
  12701. code += '<br>'
  12702. } else if (!dtd.$empty[node.tagName]) {
  12703. code += cn.innerText();
  12704. }
  12705. } else {
  12706. code += cn.data
  12707. }
  12708. });
  12709. if (!/br>$/.test(code)) {
  12710. code += '<br>';
  12711. }
  12712. }
  12713. } else {
  12714. code += node.data + '<br>'
  12715. }
  12716. if (!node.nextSibling() && /<br>$/.test(code)) {
  12717. code = code.replace(/<br>$/, '');
  12718. }
  12719. } else {
  12720. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12721. if (!/br\/?\s*>$/.test(code)) {
  12722. if (!node.nextSibling())
  12723. return;
  12724. code += '<br>'
  12725. }
  12726. }
  12727. }
  12728. });
  12729. }
  12730. me.execCommand('inserthtml', '<pre id="coder"class="brush:' + lang + ';toolbar:false">' + code + '</pre>', true);
  12731. pre = me.document.getElementById('coder');
  12732. domUtils.removeAttributes(pre, 'id');
  12733. var tmpNode = pre.previousSibling;
  12734. if (tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))) {
  12735. domUtils.remove(tmpNode)
  12736. }
  12737. var rng = me.selection.getRange();
  12738. if (domUtils.isEmptyBlock(pre)) {
  12739. rng.setStart(pre, 0).setCursor(false, true)
  12740. } else {
  12741. rng.selectNodeContents(pre).select()
  12742. }
  12743. }
  12744. },
  12745. queryCommandValue: function () {
  12746. var path = this.selection.getStartElementPath();
  12747. var lang = '';
  12748. utils.each(path, function (node) {
  12749. if (node.nodeName == 'PRE') {
  12750. var match = node.className.match(/brush:([^;]+)/);
  12751. lang = match && match[1] ? match[1] : '';
  12752. return false;
  12753. }
  12754. });
  12755. return lang;
  12756. }
  12757. };
  12758. me.addInputRule(function (root) {
  12759. utils.each(root.getNodesByTagName('pre'), function (pre) {
  12760. var brs = pre.getNodesByTagName('br');
  12761. if (brs.length) {
  12762. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs, function (br) {
  12763. var txt = UE.uNode.createText('\n');
  12764. br.parentNode.insertBefore(txt, br);
  12765. br.parentNode.removeChild(br);
  12766. });
  12767. return;
  12768. }
  12769. if (browser.ie && browser.ie11below && browser.version > 8)
  12770. return;
  12771. var code = pre.innerText().split(/\n/);
  12772. pre.innerHTML('');
  12773. utils.each(code, function (c) {
  12774. if (c.length) {
  12775. pre.appendChild(UE.uNode.createText(c));
  12776. }
  12777. pre.appendChild(UE.uNode.createElement('br'))
  12778. })
  12779. })
  12780. });
  12781. me.addOutputRule(function (root) {
  12782. utils.each(root.getNodesByTagName('pre'), function (pre) {
  12783. var code = '';
  12784. utils.each(pre.children, function (n) {
  12785. if (n.type == 'text') {
  12786. //在ie下文本内容有可能末尾带有\n要去掉
  12787. //trace:3396
  12788. code += n.data.replace(/[ ]/g, '&nbsp;').replace(/\n$/, '');
  12789. } else {
  12790. if (n.tagName == 'br') {
  12791. code += '\n'
  12792. } else {
  12793. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12794. }
  12795. }
  12796. });
  12797. pre.innerText(code.replace(/(&nbsp;|\n)+$/, ''))
  12798. })
  12799. });
  12800. //不需要判断highlight的command列表
  12801. me.notNeedCodeQuery = {
  12802. help: 1,
  12803. undo: 1,
  12804. redo: 1,
  12805. source: 1,
  12806. print: 1,
  12807. searchreplace: 1,
  12808. fullscreen: 1,
  12809. preview: 1,
  12810. insertparagraph: 1,
  12811. elementpath: 1,
  12812. insertcode: 1,
  12813. inserthtml: 1,
  12814. selectall: 1
  12815. };
  12816. //将queyCommamndState重置
  12817. var orgQuery = me.queryCommandState;
  12818. me.queryCommandState = function (cmd) {
  12819. var me = this;
  12820. if (!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')) {
  12821. return -1;
  12822. }
  12823. return UE.Editor.prototype.queryCommandState.apply(this, arguments)
  12824. };
  12825. me.addListener('beforeenterkeydown', function () {
  12826. var rng = me.selection.getRange();
  12827. var pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12828. if (pre) {
  12829. me.fireEvent('saveScene');
  12830. if (!rng.collapsed) {
  12831. rng.deleteContents();
  12832. }
  12833. if (!browser.ie || browser.ie9above) {
  12834. var tmpNode = me.document.createElement('br'), pre;
  12835. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12836. var next = tmpNode.nextSibling;
  12837. if (!next && (!browser.ie || browser.version > 10)) {
  12838. rng.insertNode(tmpNode.cloneNode(false));
  12839. } else {
  12840. rng.setStartAfter(tmpNode);
  12841. }
  12842. pre = tmpNode.previousSibling;
  12843. var tmp;
  12844. while (pre) {
  12845. tmp = pre;
  12846. pre = pre.previousSibling;
  12847. if (!pre || pre.nodeName == 'BR') {
  12848. pre = tmp;
  12849. break;
  12850. }
  12851. }
  12852. if (pre) {
  12853. var str = '';
  12854. while (pre && pre.nodeName != 'BR' && new RegExp('^[\\s' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  12855. str += pre.nodeValue;
  12856. pre = pre.nextSibling;
  12857. }
  12858. if (pre.nodeName != 'BR') {
  12859. var match = pre.nodeValue.match(new RegExp('^([\\s' + domUtils.fillChar + ']+)'));
  12860. if (match && match[1]) {
  12861. str += match[1]
  12862. }
  12863. }
  12864. if (str) {
  12865. str = me.document.createTextNode(str);
  12866. rng.insertNode(str).setStartAfter(str);
  12867. }
  12868. }
  12869. rng.collapse(true).select(true);
  12870. } else {
  12871. if (browser.version > 8) {
  12872. var txt = me.document.createTextNode('\n');
  12873. var start = rng.startContainer;
  12874. if (rng.startOffset == 0) {
  12875. var preNode = start.previousSibling;
  12876. if (preNode) {
  12877. rng.insertNode(txt);
  12878. var fillchar = me.document.createTextNode(' ');
  12879. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar, 0).collapse(true).select(true)
  12880. }
  12881. } else {
  12882. rng.insertNode(txt).setStartAfter(txt);
  12883. var fillchar = me.document.createTextNode(' ');
  12884. start = rng.startContainer.childNodes[rng.startOffset];
  12885. if (start && !/^\n/.test(start.nodeValue)) {
  12886. rng.setStartBefore(txt)
  12887. }
  12888. rng.insertNode(fillchar).setStart(fillchar, 0).collapse(true).select(true)
  12889. }
  12890. } else {
  12891. var tmpNode = me.document.createElement('br');
  12892. rng.insertNode(tmpNode);
  12893. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12894. rng.setStartAfter(tmpNode);
  12895. pre = tmpNode.previousSibling;
  12896. var tmp;
  12897. while (pre) {
  12898. tmp = pre;
  12899. pre = pre.previousSibling;
  12900. if (!pre || pre.nodeName == 'BR') {
  12901. pre = tmp;
  12902. break;
  12903. }
  12904. }
  12905. if (pre) {
  12906. var str = '';
  12907. while (pre && pre.nodeName != 'BR' && new RegExp('^[ ' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  12908. str += pre.nodeValue;
  12909. pre = pre.nextSibling;
  12910. }
  12911. if (pre.nodeName != 'BR') {
  12912. var match = pre.nodeValue.match(new RegExp('^([ ' + domUtils.fillChar + ']+)'));
  12913. if (match && match[1]) {
  12914. str += match[1]
  12915. }
  12916. }
  12917. str = me.document.createTextNode(str);
  12918. rng.insertNode(str).setStartAfter(str);
  12919. }
  12920. rng.collapse(true).select();
  12921. }
  12922. }
  12923. me.fireEvent('saveScene');
  12924. return true;
  12925. }
  12926. });
  12927. me.addListener('tabkeydown', function (cmd, evt) {
  12928. var rng = me.selection.getRange();
  12929. var pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12930. if (pre) {
  12931. me.fireEvent('saveScene');
  12932. if (evt.shiftKey) {
  12933. } else {
  12934. if (!rng.collapsed) {
  12935. var bk = rng.createBookmark();
  12936. var start = bk.start.previousSibling;
  12937. while (start) {
  12938. if (pre.firstChild === start && !domUtils.isBr(start)) {
  12939. pre.insertBefore(me.document.createTextNode(' '), start);
  12940. break;
  12941. }
  12942. if (domUtils.isBr(start)) {
  12943. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling);
  12944. break;
  12945. }
  12946. start = start.previousSibling;
  12947. }
  12948. var end = bk.end;
  12949. start = bk.start.nextSibling;
  12950. if (pre.firstChild === bk.start) {
  12951. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling)
  12952. }
  12953. while (start && start !== end) {
  12954. if (domUtils.isBr(start) && start.nextSibling) {
  12955. if (start.nextSibling === end) {
  12956. break;
  12957. }
  12958. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling)
  12959. }
  12960. start = start.nextSibling;
  12961. }
  12962. rng.moveToBookmark(bk).select();
  12963. } else {
  12964. var tmpNode = me.document.createTextNode(' ');
  12965. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12966. }
  12967. }
  12968. me.fireEvent('saveScene');
  12969. return true;
  12970. }
  12971. });
  12972. me.addListener('beforeinserthtml', function (evtName, html) {
  12973. var me = this,
  12974. rng = me.selection.getRange(),
  12975. pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12976. if (pre) {
  12977. if (!rng.collapsed) {
  12978. rng.deleteContents()
  12979. }
  12980. var htmlstr = '';
  12981. if (browser.ie && browser.version > 8) {
  12982. utils.each(UE.filterNode(UE.htmlparser(html), me.options.filterTxtRules).children, function (node) {
  12983. if (node.type == 'element') {
  12984. if (node.tagName == 'br') {
  12985. htmlstr += '\n'
  12986. } else if (!dtd.$empty[node.tagName]) {
  12987. utils.each(node.children, function (cn) {
  12988. if (cn.type == 'element') {
  12989. if (cn.tagName == 'br') {
  12990. htmlstr += '\n'
  12991. } else if (!dtd.$empty[node.tagName]) {
  12992. htmlstr += cn.innerText();
  12993. }
  12994. } else {
  12995. htmlstr += cn.data
  12996. }
  12997. })
  12998. if (!/\n$/.test(htmlstr)) {
  12999. htmlstr += '\n';
  13000. }
  13001. }
  13002. } else {
  13003. htmlstr += node.data + '\n'
  13004. }
  13005. if (!node.nextSibling() && /\n$/.test(htmlstr)) {
  13006. htmlstr = htmlstr.replace(/\n$/, '');
  13007. }
  13008. });
  13009. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g, ' ')));
  13010. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  13011. } else {
  13012. var frag = me.document.createDocumentFragment();
  13013. utils.each(UE.filterNode(UE.htmlparser(html), me.options.filterTxtRules).children, function (node) {
  13014. if (node.type == 'element') {
  13015. if (node.tagName == 'br') {
  13016. frag.appendChild(me.document.createElement('br'))
  13017. } else if (!dtd.$empty[node.tagName]) {
  13018. utils.each(node.children, function (cn) {
  13019. if (cn.type == 'element') {
  13020. if (cn.tagName == 'br') {
  13021. frag.appendChild(me.document.createElement('br'))
  13022. } else if (!dtd.$empty[node.tagName]) {
  13023. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g, ' '))));
  13024. }
  13025. } else {
  13026. frag.appendChild(me.document.createTextNode(utils.html(cn.data.replace(/&nbsp;/g, ' '))));
  13027. }
  13028. })
  13029. if (frag.lastChild.nodeName != 'BR') {
  13030. frag.appendChild(me.document.createElement('br'))
  13031. }
  13032. }
  13033. } else {
  13034. frag.appendChild(me.document.createTextNode(utils.html(node.data.replace(/&nbsp;/g, ' '))));
  13035. }
  13036. if (!node.nextSibling() && frag.lastChild.nodeName == 'BR') {
  13037. frag.removeChild(frag.lastChild)
  13038. }
  13039. });
  13040. rng.insertNode(frag).select();
  13041. }
  13042. return true;
  13043. }
  13044. });
  13045. //方向键的处理
  13046. me.addListener('keydown', function (cmd, evt) {
  13047. var me = this, keyCode = evt.keyCode || evt.which;
  13048. if (keyCode == 40) {
  13049. var rng = me.selection.getRange(), pre, start = rng.startContainer;
  13050. if (rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true)) && !pre.nextSibling) {
  13051. var last = pre.lastChild
  13052. while (last && last.nodeName == 'BR') {
  13053. last = last.previousSibling;
  13054. }
  13055. if (last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length) {
  13056. me.execCommand('insertparagraph');
  13057. domUtils.preventDefault(evt)
  13058. }
  13059. }
  13060. }
  13061. });
  13062. //trace:3395
  13063. me.addListener('delkeydown', function (type, evt) {
  13064. var rng = this.selection.getRange();
  13065. rng.txtToElmBoundary(true);
  13066. var start = rng.startContainer;
  13067. if (domUtils.isTagNode(start, 'pre') && rng.collapsed && domUtils.isStartInblock(rng)) {
  13068. var p = me.document.createElement('p');
  13069. domUtils.fillNode(me.document, p);
  13070. start.parentNode.insertBefore(p, start);
  13071. domUtils.remove(start);
  13072. rng.setStart(p, 0).setCursor(false, true);
  13073. domUtils.preventDefault(evt);
  13074. return true;
  13075. }
  13076. })
  13077. };
  13078. // plugins/cleardoc.js
  13079. /**
  13080. * 清空文档插件
  13081. * @file
  13082. * @since 1.2.6.1
  13083. */
  13084. /**
  13085. * 清空文档
  13086. * @command cleardoc
  13087. * @method execCommand
  13088. * @param { String } cmd 命令字符串
  13089. * @example
  13090. * ```javascript
  13091. * //editor 是编辑器实例
  13092. * editor.execCommand('cleardoc');
  13093. * ```
  13094. */
  13095. UE.commands['cleardoc'] = {
  13096. execCommand: function (cmdName) {
  13097. var me = this,
  13098. enterTag = me.options.enterTag,
  13099. range = me.selection.getRange();
  13100. if (enterTag == "br") {
  13101. me.body.innerHTML = "<br/>";
  13102. range.setStart(me.body, 0).setCursor();
  13103. } else {
  13104. me.body.innerHTML = "<p>" + (ie ? "" : "<br/>") + "</p>";
  13105. range.setStart(me.body.firstChild, 0).setCursor(false, true);
  13106. }
  13107. setTimeout(function () {
  13108. me.fireEvent("clearDoc");
  13109. }, 0);
  13110. }
  13111. };
  13112. // plugins/anchor.js
  13113. /**
  13114. * 锚点插件,为UEditor提供插入锚点支持
  13115. * @file
  13116. * @since 1.2.6.1
  13117. */
  13118. UE.plugin.register('anchor', function () {
  13119. return {
  13120. bindEvents: {
  13121. 'ready': function () {
  13122. utils.cssRule('anchor',
  13123. '.anchorclass{background: url(\''
  13124. + this.options.themePath
  13125. + this.options.theme + '/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  13126. this.document);
  13127. }
  13128. },
  13129. outputRule: function (root) {
  13130. utils.each(root.getNodesByTagName('img'), function (a) {
  13131. var val;
  13132. if (val = a.getAttr('anchorname')) {
  13133. a.tagName = 'a';
  13134. a.setAttr({
  13135. anchorname: '',
  13136. name: val,
  13137. 'class': ''
  13138. })
  13139. }
  13140. })
  13141. },
  13142. inputRule: function (root) {
  13143. utils.each(root.getNodesByTagName('a'), function (a) {
  13144. var val;
  13145. if ((val = a.getAttr('name')) && !a.getAttr('href')) {
  13146. a.tagName = 'img';
  13147. a.setAttr({
  13148. anchorname: a.getAttr('name'),
  13149. 'class': 'anchorclass'
  13150. });
  13151. a.setAttr('name')
  13152. }
  13153. })
  13154. },
  13155. commands: {
  13156. /**
  13157. * 插入锚点
  13158. * @command anchor
  13159. * @method execCommand
  13160. * @param { String } cmd 命令字符串
  13161. * @param { String } name 锚点名称字符串
  13162. * @example
  13163. * ```javascript
  13164. * //editor 是编辑器实例
  13165. * editor.execCommand('anchor', 'anchor1');
  13166. * ```
  13167. */
  13168. 'anchor': {
  13169. execCommand: function (cmd, name) {
  13170. var range = this.selection.getRange(), img = range.getClosedNode();
  13171. if (img && img.getAttribute('anchorname')) {
  13172. if (name) {
  13173. img.setAttribute('anchorname', name);
  13174. } else {
  13175. range.setStartBefore(img).setCursor();
  13176. domUtils.remove(img);
  13177. }
  13178. } else {
  13179. if (name) {
  13180. //只在选区的开始插入
  13181. var anchor = this.document.createElement('img');
  13182. range.collapse(true);
  13183. domUtils.setAttributes(anchor, {
  13184. 'anchorname': name,
  13185. 'class': 'anchorclass'
  13186. });
  13187. range.insertNode(anchor).setStartAfter(anchor).setCursor(false, true);
  13188. }
  13189. }
  13190. }
  13191. }
  13192. }
  13193. }
  13194. });
  13195. // plugins/wordcount.js
  13196. ///import core
  13197. ///commands 字数统计
  13198. ///commandsName WordCount,wordCount
  13199. ///commandsTitle 字数统计
  13200. /*
  13201. * Created by JetBrains WebStorm.
  13202. * User: taoqili
  13203. * Date: 11-9-7
  13204. * Time: 下午8:18
  13205. * To change this template use File | Settings | File Templates.
  13206. */
  13207. UE.plugins['wordcount'] = function () {
  13208. var me = this;
  13209. me.setOpt('wordCount', true);
  13210. me.addListener('contentchange', function () {
  13211. me.fireEvent('wordcount');
  13212. });
  13213. var timer;
  13214. me.addListener('ready', function () {
  13215. var me = this;
  13216. domUtils.on(me.body, "keyup", function (evt) {
  13217. var code = evt.keyCode || evt.which,
  13218. //忽略的按键,ctr,alt,shift,方向键
  13219. ignores = {"16": 1, "18": 1, "20": 1, "37": 1, "38": 1, "39": 1, "40": 1};
  13220. if (code in ignores) return;
  13221. clearTimeout(timer);
  13222. timer = setTimeout(function () {
  13223. me.fireEvent('wordcount');
  13224. }, 200)
  13225. })
  13226. });
  13227. };
  13228. // plugins/pagebreak.js
  13229. /**
  13230. * 分页功能插件
  13231. * @file
  13232. * @since 1.2.6.1
  13233. */
  13234. UE.plugins['pagebreak'] = function () {
  13235. var me = this,
  13236. notBreakTags = ['td'];
  13237. me.setOpt('pageBreakTag', '_ueditor_page_break_tag_');
  13238. function fillNode(node) {
  13239. if (domUtils.isEmptyBlock(node)) {
  13240. var firstChild = node.firstChild, tmpNode;
  13241. while (firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)) {
  13242. tmpNode = firstChild;
  13243. firstChild = firstChild.firstChild;
  13244. }
  13245. !tmpNode && (tmpNode = node);
  13246. domUtils.fillNode(me.document, tmpNode);
  13247. }
  13248. }
  13249. //分页符样式添加
  13250. me.ready(function () {
  13251. utils.cssRule('pagebreak', '.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}', me.document);
  13252. });
  13253. function isHr(node) {
  13254. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  13255. }
  13256. me.addInputRule(function (root) {
  13257. root.traversal(function (node) {
  13258. if (node.type == 'text' && node.data == me.options.pageBreakTag) {
  13259. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  13260. node.parentNode.insertBefore(hr, node);
  13261. node.parentNode.removeChild(node)
  13262. }
  13263. })
  13264. });
  13265. me.addOutputRule(function (node) {
  13266. utils.each(node.getNodesByTagName('hr'), function (n) {
  13267. if (n.getAttr('class') == 'pagebreak') {
  13268. var txt = UE.uNode.createText(me.options.pageBreakTag);
  13269. n.parentNode.insertBefore(txt, n);
  13270. n.parentNode.removeChild(n);
  13271. }
  13272. })
  13273. });
  13274. /**
  13275. * 插入分页符
  13276. * @command pagebreak
  13277. * @method execCommand
  13278. * @param { String } cmd 命令字符串
  13279. * @remind 在表格中插入分页符会把表格切分成两部分
  13280. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  13281. * 以便于提交数据到服务器端后处理分页。
  13282. * @example
  13283. * ```javascript
  13284. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  13285. * ```
  13286. */
  13287. me.commands['pagebreak'] = {
  13288. execCommand: function () {
  13289. var range = me.selection.getRange(), hr = me.document.createElement('hr');
  13290. domUtils.setAttributes(hr, {
  13291. 'class': 'pagebreak',
  13292. noshade: "noshade",
  13293. size: "5"
  13294. });
  13295. domUtils.unSelectable(hr);
  13296. //table单独处理
  13297. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  13298. parents = [], pN;
  13299. if (node) {
  13300. switch (node.tagName) {
  13301. case 'TD':
  13302. pN = node.parentNode;
  13303. if (!pN.previousSibling) {
  13304. var table = domUtils.findParentByTagName(pN, 'table');
  13305. // var tableWrapDiv = table.parentNode;
  13306. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  13307. // && tableWrapDiv.tagName == 'DIV'
  13308. // && tableWrapDiv.getAttribute('dropdrag')
  13309. // ){
  13310. // domUtils.remove(tableWrapDiv,true);
  13311. // }
  13312. table.parentNode.insertBefore(hr, table);
  13313. parents = domUtils.findParents(hr, true);
  13314. } else {
  13315. pN.parentNode.insertBefore(hr, pN);
  13316. parents = domUtils.findParents(hr);
  13317. }
  13318. pN = parents[1];
  13319. if (hr !== pN) {
  13320. domUtils.breakParent(hr, pN);
  13321. }
  13322. //table要重写绑定一下拖拽
  13323. me.fireEvent('afteradjusttable', me.document);
  13324. }
  13325. } else {
  13326. if (!range.collapsed) {
  13327. range.deleteContents();
  13328. var start = range.startContainer;
  13329. while (!domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  13330. range.setStartBefore(start).collapse(true);
  13331. domUtils.remove(start);
  13332. start = range.startContainer;
  13333. }
  13334. }
  13335. range.insertNode(hr);
  13336. var pN = hr.parentNode, nextNode;
  13337. while (!domUtils.isBody(pN)) {
  13338. domUtils.breakParent(hr, pN);
  13339. nextNode = hr.nextSibling;
  13340. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  13341. domUtils.remove(nextNode);
  13342. }
  13343. pN = hr.parentNode;
  13344. }
  13345. nextNode = hr.nextSibling;
  13346. var pre = hr.previousSibling;
  13347. if (isHr(pre)) {
  13348. domUtils.remove(pre);
  13349. } else {
  13350. pre && fillNode(pre);
  13351. }
  13352. if (!nextNode) {
  13353. var p = me.document.createElement('p');
  13354. hr.parentNode.appendChild(p);
  13355. domUtils.fillNode(me.document, p);
  13356. range.setStart(p, 0).collapse(true);
  13357. } else {
  13358. if (isHr(nextNode)) {
  13359. domUtils.remove(nextNode);
  13360. } else {
  13361. fillNode(nextNode);
  13362. }
  13363. range.setEndAfter(hr).collapse(false);
  13364. }
  13365. range.select(true);
  13366. }
  13367. }
  13368. };
  13369. };
  13370. // plugins/wordimage.js
  13371. ///import core
  13372. ///commands 本地图片引导上传
  13373. ///commandsName WordImage
  13374. ///commandsTitle 本地图片引导上传
  13375. ///commandsDialog dialogs\wordimage
  13376. UE.plugin.register('wordimage', function () {
  13377. var me = this,
  13378. images = [];
  13379. return {
  13380. commands: {
  13381. 'wordimage': {
  13382. execCommand: function () {
  13383. var images = domUtils.getElementsByTagName(me.body, "img");
  13384. var urlList = [];
  13385. for (var i = 0, ci; ci = images[i++];) {
  13386. var url = ci.getAttribute("word_img");
  13387. url && urlList.push(url);
  13388. }
  13389. return urlList;
  13390. },
  13391. queryCommandState: function () {
  13392. images = domUtils.getElementsByTagName(me.body, "img");
  13393. for (var i = 0, ci; ci = images[i++];) {
  13394. if (ci.getAttribute("word_img")) {
  13395. return 1;
  13396. }
  13397. }
  13398. return -1;
  13399. },
  13400. notNeedUndo: true
  13401. }
  13402. },
  13403. inputRule: function (root) {
  13404. utils.each(root.getNodesByTagName('img'), function (img) {
  13405. var attrs = img.attrs,
  13406. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13407. opt = me.options,
  13408. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13409. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13410. img.setAttr({
  13411. width: attrs.width,
  13412. height: attrs.height,
  13413. alt: attrs.alt,
  13414. word_img: attrs.src,
  13415. src: src,
  13416. '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'
  13417. })
  13418. }
  13419. })
  13420. }
  13421. }
  13422. });
  13423. // plugins/dragdrop.js
  13424. UE.plugins['dragdrop'] = function() {
  13425. var me = this;
  13426. me.ready(function() {
  13427. domUtils.on(this.body, 'dragend', function() {
  13428. var rng = me.selection.getRange();
  13429. var node = rng.getClosedNode() || me.selection.getStart();
  13430. if (node && node.tagName == 'IMG') {
  13431. var pre = node.previousSibling, next;
  13432. while (next = node.nextSibling) {
  13433. if (next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild) {
  13434. domUtils.remove(next)
  13435. } else {
  13436. break;
  13437. }
  13438. }
  13439. if ((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))) {
  13440. if (pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)) {
  13441. pre.appendChild(node);
  13442. domUtils.moveChild(next, pre);
  13443. domUtils.remove(next);
  13444. } else if (next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)) {
  13445. next.insertBefore(node, next.firstChild);
  13446. }
  13447. if (pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)) {
  13448. domUtils.remove(pre)
  13449. }
  13450. if (next && next.tagName == 'P' && domUtils.isEmptyBlock(next)) {
  13451. domUtils.remove(next)
  13452. }
  13453. rng.selectNode(node).select();
  13454. me.fireEvent('saveScene');
  13455. }
  13456. }
  13457. })
  13458. });
  13459. me.addListener('keyup', function (type, evt) {
  13460. var keyCode = evt.keyCode || evt.which;
  13461. if (keyCode == 13) {
  13462. var rng = me.selection.getRange(), node;
  13463. if (node = domUtils.findParentByTagName(rng.startContainer, 'p', true)) {
  13464. if (domUtils.getComputedStyle(node, 'text-align') == 'center') {
  13465. domUtils.removeStyle(node, 'text-align')
  13466. }
  13467. }
  13468. }
  13469. })
  13470. };
  13471. // plugins/undo.js
  13472. /**
  13473. * undo redo
  13474. * @file
  13475. * @since 1.2.6.1
  13476. */
  13477. /**
  13478. * 撤销上一次执行的命令
  13479. * @command undo
  13480. * @method execCommand
  13481. * @param { String } cmd 命令字符串
  13482. * @example
  13483. * ```javascript
  13484. * editor.execCommand( 'undo' );
  13485. * ```
  13486. */
  13487. /**
  13488. * 重做上一次执行的命令
  13489. * @command redo
  13490. * @method execCommand
  13491. * @param { String } cmd 命令字符串
  13492. * @example
  13493. * ```javascript
  13494. * editor.execCommand( 'redo' );
  13495. * ```
  13496. */
  13497. UE.plugins['undo'] = function () {
  13498. var saveSceneTimer;
  13499. var me = this,
  13500. maxUndoCount = me.options.maxUndoCount || 20,
  13501. maxInputCount = me.options.maxInputCount || 20,
  13502. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13503. var noNeedFillCharTags = {
  13504. ol: 1, ul: 1, table: 1, tbody: 1, tr: 1, body: 1
  13505. };
  13506. var orgState = me.options.autoClearEmptyNode;
  13507. function compareAddr(indexA, indexB) {
  13508. if (indexA.length != indexB.length)
  13509. return 0;
  13510. for (var i = 0, l = indexA.length; i < l; i++) {
  13511. if (indexA[i] != indexB[i])
  13512. return 0
  13513. }
  13514. return 1;
  13515. }
  13516. function compareRangeAddress(rngAddrA, rngAddrB) {
  13517. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13518. return 0;
  13519. }
  13520. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13521. return 0;
  13522. }
  13523. return 1;
  13524. }
  13525. function UndoManager() {
  13526. this.list = [];
  13527. this.index = 0;
  13528. this.hasUndo = false;
  13529. this.hasRedo = false;
  13530. this.undo = function () {
  13531. if (this.hasUndo) {
  13532. if (!this.list[this.index - 1] && this.list.length == 1) {
  13533. this.reset();
  13534. return;
  13535. }
  13536. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13537. this.index--;
  13538. if (this.index == 0) {
  13539. return this.restore(0);
  13540. }
  13541. }
  13542. this.restore(--this.index);
  13543. }
  13544. };
  13545. this.redo = function () {
  13546. if (this.hasRedo) {
  13547. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13548. this.index++;
  13549. if (this.index == this.list.length - 1) {
  13550. return this.restore(this.index);
  13551. }
  13552. }
  13553. this.restore(++this.index);
  13554. }
  13555. };
  13556. this.restore = function () {
  13557. var me = this.editor;
  13558. var scene = this.list[this.index];
  13559. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13560. me.options.autoClearEmptyNode = false;
  13561. me.filterInputRule(root);
  13562. me.options.autoClearEmptyNode = orgState;
  13563. //trace:873
  13564. //去掉展位符
  13565. me.document.body.innerHTML = root.toHtml();
  13566. me.fireEvent('afterscencerestore');
  13567. //处理undo后空格不展位的问题
  13568. if (browser.ie) {
  13569. utils.each(domUtils.getElementsByTagName(me.document, 'td th caption p'), function (node) {
  13570. if (domUtils.isEmptyNode(node)) {
  13571. domUtils.fillNode(me.document, node);
  13572. }
  13573. })
  13574. }
  13575. try {
  13576. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13577. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13578. } catch (e) {
  13579. }
  13580. this.update();
  13581. this.clearKey();
  13582. //不能把自己reset了
  13583. me.fireEvent('reset', true);
  13584. };
  13585. this.getScene = function () {
  13586. var me = this.editor;
  13587. var rng = me.selection.getRange(),
  13588. rngAddress = rng.createAddress(false, true);
  13589. me.fireEvent('beforegetscene');
  13590. var root = UE.htmlparser(me.body.innerHTML);
  13591. me.options.autoClearEmptyNode = false;
  13592. me.filterOutputRule(root);
  13593. me.options.autoClearEmptyNode = orgState;
  13594. var cont = root.toHtml();
  13595. //trace:3461
  13596. //这个会引起回退时导致空格丢失的情况
  13597. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13598. me.fireEvent('aftergetscene');
  13599. return {
  13600. address: rngAddress,
  13601. content: cont
  13602. }
  13603. };
  13604. this.save = function (notCompareRange, notSetCursor) {
  13605. clearTimeout(saveSceneTimer);
  13606. var currentScene = this.getScene(notSetCursor),
  13607. lastScene = this.list[this.index];
  13608. if (lastScene && lastScene.content != currentScene.content) {
  13609. me.trigger('contentchange')
  13610. }
  13611. //内容相同位置相同不存
  13612. if (lastScene && lastScene.content == currentScene.content &&
  13613. (notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address))
  13614. ) {
  13615. return;
  13616. }
  13617. this.list = this.list.slice(0, this.index + 1);
  13618. this.list.push(currentScene);
  13619. //如果大于最大数量了,就把最前的剔除
  13620. if (this.list.length > maxUndoCount) {
  13621. this.list.shift();
  13622. }
  13623. this.index = this.list.length - 1;
  13624. this.clearKey();
  13625. //跟新undo/redo状态
  13626. this.update();
  13627. };
  13628. this.update = function () {
  13629. this.hasRedo = !!this.list[this.index + 1];
  13630. this.hasUndo = !!this.list[this.index - 1];
  13631. };
  13632. this.reset = function () {
  13633. this.list = [];
  13634. this.index = 0;
  13635. this.hasUndo = false;
  13636. this.hasRedo = false;
  13637. this.clearKey();
  13638. };
  13639. this.clearKey = function () {
  13640. keycont = 0;
  13641. lastKeyCode = null;
  13642. };
  13643. }
  13644. me.undoManger = new UndoManager();
  13645. me.undoManger.editor = me;
  13646. function saveScene() {
  13647. this.undoManger.save();
  13648. }
  13649. me.addListener('saveScene', function () {
  13650. var args = Array.prototype.splice.call(arguments, 1);
  13651. this.undoManger.save.apply(this.undoManger, args);
  13652. });
  13653. // me.addListener('beforeexeccommand', saveScene);
  13654. // me.addListener('afterexeccommand', saveScene);
  13655. me.addListener('reset', function (type, exclude) {
  13656. if (!exclude) {
  13657. this.undoManger.reset();
  13658. }
  13659. });
  13660. me.commands['redo'] = me.commands['undo'] = {
  13661. execCommand: function (cmdName) {
  13662. this.undoManger[cmdName]();
  13663. },
  13664. queryCommandState: function (cmdName) {
  13665. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13666. },
  13667. notNeedUndo: 1
  13668. };
  13669. var keys = {
  13670. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13671. /*Shift*/ 16: 1, /*Ctrl*/ 17: 1, /*Alt*/ 18: 1,
  13672. 37: 1, 38: 1, 39: 1, 40: 1
  13673. },
  13674. keycont = 0,
  13675. lastKeyCode;
  13676. //输入法状态下不计算字符数
  13677. var inputType = false;
  13678. me.addListener('ready', function () {
  13679. domUtils.on(this.body, 'compositionstart', function () {
  13680. inputType = true;
  13681. });
  13682. domUtils.on(this.body, 'compositionend', function () {
  13683. inputType = false;
  13684. })
  13685. });
  13686. //快捷键
  13687. me.addshortcutkey({
  13688. "Undo": "ctrl+90", //undo
  13689. "Redo": "ctrl+89" //redo
  13690. });
  13691. var isCollapsed = true;
  13692. me.addListener('keydown', function (type, evt) {
  13693. var me = this;
  13694. var keyCode = evt.keyCode || evt.which;
  13695. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13696. if (inputType)
  13697. return;
  13698. if (!me.selection.getRange().collapsed) {
  13699. me.undoManger.save(false, true);
  13700. isCollapsed = false;
  13701. return;
  13702. }
  13703. if (me.undoManger.list.length == 0) {
  13704. me.undoManger.save(true);
  13705. }
  13706. clearTimeout(saveSceneTimer);
  13707. function save(cont) {
  13708. cont.undoManger.save(false, true);
  13709. cont.fireEvent('selectionchange');
  13710. }
  13711. saveSceneTimer = setTimeout(function () {
  13712. if (inputType) {
  13713. var interalTimer = setInterval(function () {
  13714. if (!inputType) {
  13715. save(me);
  13716. clearInterval(interalTimer)
  13717. }
  13718. }, 300)
  13719. return;
  13720. }
  13721. save(me);
  13722. }, 200);
  13723. lastKeyCode = keyCode;
  13724. keycont++;
  13725. if (keycont >= maxInputCount) {
  13726. save(me)
  13727. }
  13728. }
  13729. });
  13730. me.addListener('keyup', function (type, evt) {
  13731. var keyCode = evt.keyCode || evt.which;
  13732. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13733. if (inputType)
  13734. return;
  13735. if (!isCollapsed) {
  13736. this.undoManger.save(false, true);
  13737. isCollapsed = true;
  13738. }
  13739. }
  13740. });
  13741. //扩展实例,添加关闭和开启命令undo
  13742. me.stopCmdUndo = function () {
  13743. me.__hasEnterExecCommand = true;
  13744. };
  13745. me.startCmdUndo = function () {
  13746. me.__hasEnterExecCommand = false;
  13747. }
  13748. };
  13749. // plugins/copy.js
  13750. UE.plugin.register('copy', function () {
  13751. var me = this;
  13752. function initZeroClipboard() {
  13753. ZeroClipboard.config({
  13754. debug: false,
  13755. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13756. });
  13757. var client = me.zeroclipboard = new ZeroClipboard();
  13758. // 复制内容
  13759. client.on('copy', function (e) {
  13760. var client = e.client,
  13761. rng = me.selection.getRange(),
  13762. div = document.createElement('div');
  13763. div.appendChild(rng.cloneContents());
  13764. client.setText(div.innerText || div.textContent);
  13765. client.setHtml(div.innerHTML);
  13766. rng.select();
  13767. });
  13768. // hover事件传递到target
  13769. client.on('mouseover mouseout', function (e) {
  13770. var target = e.target;
  13771. if (e.type == 'mouseover') {
  13772. domUtils.addClass(target, 'edui-state-hover');
  13773. } else if (e.type == 'mouseout') {
  13774. domUtils.removeClasses(target, 'edui-state-hover');
  13775. }
  13776. });
  13777. // flash加载不成功
  13778. client.on('wrongflash noflash', function () {
  13779. ZeroClipboard.destroy();
  13780. });
  13781. }
  13782. return {
  13783. bindEvents: {
  13784. 'ready': function () {
  13785. if (!browser.ie) {
  13786. if (window.ZeroClipboard) {
  13787. initZeroClipboard();
  13788. } else {
  13789. utils.loadFile(document, {
  13790. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13791. tag: "script",
  13792. type: "text/javascript",
  13793. defer: "defer"
  13794. }, function () {
  13795. initZeroClipboard();
  13796. });
  13797. }
  13798. }
  13799. }
  13800. },
  13801. commands: {
  13802. 'copy': {
  13803. execCommand: function (cmd) {
  13804. if (!me.document.execCommand('copy')) {
  13805. alert(me.getLang('copymsg'));
  13806. }
  13807. }
  13808. }
  13809. }
  13810. }
  13811. });
  13812. // plugins/paste.js
  13813. ///import core
  13814. ///import plugins/inserthtml.js
  13815. ///import plugins/undo.js
  13816. ///import plugins/serialize.js
  13817. ///commands 粘贴
  13818. ///commandsName PastePlain
  13819. ///commandsTitle 纯文本粘贴模式
  13820. /**
  13821. * @description 粘贴
  13822. * @author zhanyi
  13823. */
  13824. UE.plugins['paste'] = function () {
  13825. // function getClipboardData(callback, e) {
  13826. /*
  13827. *0428
  13828. *modify:添加事件参数 e
  13829. *************************************************************/
  13830. function getClipboardData(callback, e, editor) {
  13831. var doc = this.document;
  13832. if (doc.getElementById('baidu_pastebin')) {
  13833. return;
  13834. }
  13835. var range = this.selection.getRange(),
  13836. bk = range.createBookmark(),
  13837. //创建剪贴的容器div
  13838. pastebin = doc.createElement('div');
  13839. pastebin.id = 'baidu_pastebin';
  13840. // Safari 要求div必须有内容,才能粘贴内容进来
  13841. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13842. doc.body.appendChild(pastebin);
  13843. //trace:717 隐藏的span不能得到top
  13844. //bk.start.innerHTML = '&nbsp;';
  13845. bk.start.style.display = '';
  13846. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13847. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13848. domUtils.getXY(bk.start).y + 'px';
  13849. range.selectNodeContents(pastebin).select(true);
  13850. /*
  13851. *20220624 by zjf
  13852. *add:添加判断是否是从Excel表格复制的内容,如果是还原Excel的格式
  13853. * ************************************************************/
  13854. if (typeof (e) != 'undefined' && typeof (CKEDITOR) != 'undefined') {
  13855. // if office content set officecontent to new var officeHtml
  13856. var mswordHtml = e.clipboardData.getData('text/html');
  13857. var generatorName = CKEDITOR.plugins.pastetools.getContentGeneratorName(mswordHtml);
  13858. // var generatorName= UE.office.getContentGeneratorName( mswordHtml );
  13859. var wordRegexp = /(class="?Mso|style=["'][^"]*?\bmso\-|w:WordDocument|<o:\w+>|<\/font>)/;
  13860. // Use wordRegexp only when there is no meta generator tag in the content
  13861. var isOfficeContent = generatorName ? generatorName === 'microsoft' : wordRegexp.test(mswordHtml);
  13862. var excelRegexp = /<meta\s.*content=.*excel?(\w+)/gi;
  13863. var isExcel = excelRegexp.test(mswordHtml);
  13864. //只转换Excel,Word的效果用原来的
  13865. if (isOfficeContent && isExcel) {
  13866. var officeHtml = CKEDITOR.plugins.pastetools.filters.common.styles.inliner.inline(mswordHtml).getBody().getHtml();
  13867. officeHtml = officeHtml.replace(/<!\[/g, '<!--[').replace(/\]>/g, ']-->');
  13868. editor.config = editor.config || CKEDITOR.config;
  13869. editor.plugins = editor.plugins || CKEDITOR.plugins;
  13870. var writer = new CKEDITOR.htmlParser.basicWriter(),
  13871. filter = new CKEDITOR.htmlParser.filter(),
  13872. fragment;
  13873. var rules = [CKEDITOR.plugins.pastetools.filters.common.rules, CKEDITOR.plugins.pastefromword.rules];
  13874. CKEDITOR.tools.array.forEach(rules, function (rule) {
  13875. filter.addRules(rule(officeHtml, editor, filter));
  13876. });
  13877. fragment = CKEDITOR.htmlParser.fragment.fromHtml(officeHtml);
  13878. filter.applyTo(fragment);
  13879. fragment.writeHtml(writer);
  13880. var finalHtml = writer.getHtml();
  13881. //去掉td上的 white-space: nowrap;
  13882. if (finalHtml.indexOf('white-space:nowrap;') > -1) {
  13883. finalHtml = finalHtml.replace(/white-space:nowrap;/gi, 'white-space: pre-wrap;')
  13884. }
  13885. pastebin.isOfficeContent = true;
  13886. pastebin.officeHtml = finalHtml
  13887. }
  13888. }
  13889. /******************************************************************* */
  13890. setTimeout(function() {
  13891. if (browser.webkit) {
  13892. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13893. if (domUtils.isEmptyNode(pi)) {
  13894. domUtils.remove(pi);
  13895. } else {
  13896. pastebin = pi;
  13897. /*
  13898. *20220624 by zjf
  13899. *add:是否从excel复制过来的,如果取还原后的html
  13900. ***************************************/
  13901. if (pastebin.isOfficeContent) {
  13902. pastebin.innerHTML = pastebin.officeHtml;
  13903. }
  13904. break;
  13905. }
  13906. }
  13907. }
  13908. try {
  13909. pastebin.parentNode.removeChild(pastebin);
  13910. } catch (e) {
  13911. }
  13912. range.moveToBookmark(bk).select(true);
  13913. callback(pastebin);
  13914. }, 0);
  13915. }
  13916. var me = this;
  13917. me.setOpt({
  13918. retainOnlyLabelPasted: false
  13919. });
  13920. var txtContent, htmlContent, address;
  13921. function getPureHtml(html) {
  13922. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13923. tagName = tagName.toLowerCase();
  13924. if ({img: 1}[tagName]) {
  13925. return a;
  13926. }
  13927. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13928. if ({
  13929. 'src': 1,
  13930. 'href': 1,
  13931. 'name': 1
  13932. }[atr.toLowerCase()]) {
  13933. return atr + '=' + val + ' '
  13934. }
  13935. return ''
  13936. });
  13937. if ({
  13938. 'span': 1,
  13939. 'div': 1
  13940. }[tagName]) {
  13941. return ''
  13942. } else {
  13943. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13944. }
  13945. });
  13946. }
  13947. function filter(div) {
  13948. var html;
  13949. if (div.firstChild) {
  13950. //去掉cut中添加的边界值
  13951. var nodes = domUtils.getElementsByTagName(div, 'span');
  13952. for (var i = 0, ni; ni = nodes[i++];) {
  13953. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13954. domUtils.remove(ni);
  13955. }
  13956. }
  13957. if (browser.webkit) {
  13958. var brs = div.querySelectorAll('div br');
  13959. for (var i = 0, bi; bi = brs[i++];) {
  13960. var pN = bi.parentNode;
  13961. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13962. pN.innerHTML = '<p><br/></p>';
  13963. domUtils.remove(pN);
  13964. }
  13965. }
  13966. var divs = div.querySelectorAll('#baidu_pastebin');
  13967. for (var i = 0, di; di = divs[i++];) {
  13968. var tmpP = me.document.createElement('p');
  13969. di.parentNode.insertBefore(tmpP, di);
  13970. while (di.firstChild) {
  13971. tmpP.appendChild(di.firstChild);
  13972. }
  13973. domUtils.remove(di);
  13974. }
  13975. var metas = div.querySelectorAll('meta');
  13976. for (var i = 0, ci; ci = metas[i++];) {
  13977. domUtils.remove(ci);
  13978. }
  13979. var brs = div.querySelectorAll('br');
  13980. for (i = 0; ci = brs[i++];) {
  13981. if (/^apple-/i.test(ci.className)) {
  13982. domUtils.remove(ci);
  13983. }
  13984. }
  13985. }
  13986. if (browser.gecko) {
  13987. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13988. for (i = 0; ci = dirtyNodes[i++];) {
  13989. ci.removeAttribute('_moz_dirty');
  13990. }
  13991. }
  13992. if (!browser.ie) {
  13993. var spans = div.querySelectorAll('span.Apple-style-span');
  13994. for (var i = 0, ci; ci = spans[i++];) {
  13995. domUtils.remove(ci, true);
  13996. }
  13997. }
  13998. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13999. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  14000. //过滤word粘贴过来的冗余属性
  14001. html = UE.filterWord(html);
  14002. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  14003. var root = UE.htmlparser(html);
  14004. //如果给了过滤规则就先进行过滤
  14005. if (me.options.filterRules) {
  14006. UE.filterNode(root, me.options.filterRules);
  14007. }
  14008. //执行默认的处理
  14009. me.filterInputRule(root);
  14010. //针对chrome的处理
  14011. if (browser.webkit) {
  14012. var br = root.lastChild();
  14013. if (br && br.type == 'element' && br.tagName == 'br') {
  14014. root.removeChild(br)
  14015. }
  14016. utils.each(me.body.querySelectorAll('div'), function (node) {
  14017. if (domUtils.isEmptyBlock(node)) {
  14018. domUtils.remove(node, true)
  14019. }
  14020. })
  14021. }
  14022. html = {'html': root.toHtml()};
  14023. me.fireEvent('beforepaste', html, root);
  14024. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  14025. if (!html.html) {
  14026. return;
  14027. }
  14028. root = UE.htmlparser(html.html, true);
  14029. //如果开启了纯文本模式
  14030. if (me.queryCommandState('pasteplain') === 1) {
  14031. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  14032. } else {
  14033. //文本模式
  14034. UE.filterNode(root, me.options.filterTxtRules);
  14035. txtContent = root.toHtml();
  14036. //完全模式
  14037. htmlContent = html.html;
  14038. address = me.selection.getRange().createAddress(true);
  14039. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  14040. /**
  14041. * 0428
  14042. * add:粘贴后,如果是从excel过来为后续按百分比调整作标记
  14043. */
  14044. if (div && div.isOfficeContent && div.officeHtml) {
  14045. html.isOfficeContent = div.isOfficeContent
  14046. html.officeHtml = div.officeHtml
  14047. }
  14048. /****************** */
  14049. }
  14050. me.fireEvent("afterpaste", html);
  14051. }
  14052. }
  14053. me.addListener('pasteTransfer', function (cmd, plainType) {
  14054. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  14055. var range = me.selection.getRange();
  14056. range.moveToAddress(address, true);
  14057. if (!range.collapsed) {
  14058. while (!domUtils.isBody(range.startContainer)
  14059. ) {
  14060. var start = range.startContainer;
  14061. if (start.nodeType == 1) {
  14062. start = start.childNodes[range.startOffset];
  14063. if (!start) {
  14064. range.setStartBefore(range.startContainer);
  14065. continue;
  14066. }
  14067. var pre = start.previousSibling;
  14068. if (pre && pre.nodeType == 3 && new RegExp('^[\n\r\t ' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  14069. range.setStartBefore(pre)
  14070. }
  14071. }
  14072. if (range.startOffset == 0) {
  14073. range.setStartBefore(range.startContainer);
  14074. } else {
  14075. break;
  14076. }
  14077. }
  14078. while (!domUtils.isBody(range.endContainer)
  14079. ) {
  14080. var end = range.endContainer;
  14081. if (end.nodeType == 1) {
  14082. end = end.childNodes[range.endOffset];
  14083. if (!end) {
  14084. range.setEndAfter(range.endContainer);
  14085. continue;
  14086. }
  14087. var next = end.nextSibling;
  14088. if (next && next.nodeType == 3 && new RegExp('^[\n\r\t' + domUtils.fillChar + ']*$').test(next.nodeValue)) {
  14089. range.setEndAfter(next)
  14090. }
  14091. }
  14092. if (range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length) {
  14093. range.setEndAfter(range.endContainer);
  14094. } else {
  14095. break;
  14096. }
  14097. }
  14098. }
  14099. range.deleteContents();
  14100. range.select(true);
  14101. me.__hasEnterExecCommand = true;
  14102. var html = htmlContent;
  14103. if (plainType === 2) {
  14104. html = getPureHtml(html);
  14105. } else if (plainType) {
  14106. html = txtContent;
  14107. }
  14108. me.execCommand('inserthtml', html, true);
  14109. me.__hasEnterExecCommand = false;
  14110. var rng = me.selection.getRange();
  14111. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  14112. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  14113. ) {
  14114. rng.setStartBefore(rng.startContainer);
  14115. }
  14116. var tmpAddress = rng.createAddress(true);
  14117. address.endAddress = tmpAddress.startAddress;
  14118. }
  14119. });
  14120. me.addListener('ready', function () {
  14121. var editor = this;
  14122. domUtils.on(me.body, 'cut', function () {
  14123. var range = me.selection.getRange();
  14124. if (!range.collapsed && me.undoManger) {
  14125. me.undoManger.save();
  14126. }
  14127. });
  14128. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  14129. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  14130. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  14131. return;
  14132. }
  14133. // getClipboardData.call(me, function (div) {
  14134. // filter(div);
  14135. // });
  14136. /*
  14137. *20220624 by zjf
  14138. *modify:增加传递事件源 e
  14139. ***********************************/
  14140. getClipboardData.call(me, function (div) {
  14141. filter(div);
  14142. }, e, editor);
  14143. });
  14144. });
  14145. me.commands['paste'] = {
  14146. execCommand: function (cmd) {
  14147. if (browser.ie) {
  14148. getClipboardData.call(me, function (div) {
  14149. filter(div);
  14150. }, e);
  14151. me.document.execCommand('paste');
  14152. } else {
  14153. alert(me.getLang('pastemsg'));
  14154. }
  14155. }
  14156. }
  14157. };
  14158. // plugins/puretxtpaste.js
  14159. /**
  14160. * 纯文本粘贴插件
  14161. * @file
  14162. * @since 1.2.6.1
  14163. */
  14164. UE.plugins['pasteplain'] = function () {
  14165. var me = this;
  14166. me.setOpt({
  14167. 'pasteplain': false,
  14168. 'filterTxtRules': function () {
  14169. function transP(node) {
  14170. node.tagName = 'p';
  14171. node.setStyle();
  14172. }
  14173. function removeNode(node) {
  14174. node.parentNode.removeChild(node, true)
  14175. }
  14176. return {
  14177. //直接删除及其字节点内容
  14178. '-': 'script style object iframe embed input select',
  14179. 'p': {$: {}},
  14180. 'br': {$: {}},
  14181. div: function (node) {
  14182. var tmpNode, p = UE.uNode.createElement('p');
  14183. while (tmpNode = node.firstChild()) {
  14184. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  14185. p.appendChild(tmpNode);
  14186. } else {
  14187. if (p.firstChild()) {
  14188. node.parentNode.insertBefore(p, node);
  14189. p = UE.uNode.createElement('p');
  14190. } else {
  14191. node.parentNode.insertBefore(tmpNode, node);
  14192. }
  14193. }
  14194. }
  14195. if (p.firstChild()) {
  14196. node.parentNode.insertBefore(p, node);
  14197. }
  14198. node.parentNode.removeChild(node);
  14199. },
  14200. ol: removeNode,
  14201. ul: removeNode,
  14202. dl: removeNode,
  14203. dt: removeNode,
  14204. dd: removeNode,
  14205. 'li': removeNode,
  14206. 'caption': transP,
  14207. 'th': transP,
  14208. 'tr': transP,
  14209. 'h1': transP, 'h2': transP, 'h3': transP, 'h4': transP, 'h5': transP, 'h6': transP,
  14210. 'td': function (node) {
  14211. //没有内容的td直接删掉
  14212. var txt = !!node.innerText();
  14213. if (txt) {
  14214. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'), node);
  14215. }
  14216. node.parentNode.removeChild(node, node.innerText())
  14217. }
  14218. }
  14219. }()
  14220. });
  14221. //暂时这里支持一下老版本的属性
  14222. var pasteplain = me.options.pasteplain;
  14223. /**
  14224. * 启用或取消纯文本粘贴模式
  14225. * @command pasteplain
  14226. * @method execCommand
  14227. * @param { String } cmd 命令字符串
  14228. * @example
  14229. * ```javascript
  14230. * editor.queryCommandState( 'pasteplain' );
  14231. * ```
  14232. */
  14233. /**
  14234. * 查询当前是否处于纯文本粘贴模式
  14235. * @command pasteplain
  14236. * @method queryCommandState
  14237. * @param { String } cmd 命令字符串
  14238. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  14239. * @example
  14240. * ```javascript
  14241. * editor.queryCommandState( 'pasteplain' );
  14242. * ```
  14243. */
  14244. me.commands['pasteplain'] = {
  14245. queryCommandState: function () {
  14246. return pasteplain ? 1 : 0;
  14247. },
  14248. execCommand: function () {
  14249. pasteplain = !pasteplain | 0;
  14250. },
  14251. notNeedUndo: 1
  14252. };
  14253. };
  14254. // plugins/list.js
  14255. /**
  14256. * 有序列表,无序列表插件
  14257. * @file
  14258. * @since 1.2.6.1
  14259. */
  14260. UE.plugins['list'] = function () {
  14261. var me = this,
  14262. notExchange = {
  14263. 'TD': 1,
  14264. 'PRE': 1,
  14265. 'BLOCKQUOTE': 1
  14266. };
  14267. var customStyle = {
  14268. 'cn': 'cn-1-',
  14269. 'cn1': 'cn-2-',
  14270. 'cn2': 'cn-3-',
  14271. 'num': 'num-1-',
  14272. 'num1': 'num-2-',
  14273. 'num2': 'num-3-',
  14274. 'dash': 'dash',
  14275. 'dot': 'dot'
  14276. };
  14277. me.setOpt({
  14278. 'autoTransWordToList': false,
  14279. 'insertorderedlist': {
  14280. 'num': '',
  14281. 'num1': '',
  14282. 'num2': '',
  14283. 'cn': '',
  14284. 'cn1': '',
  14285. 'cn2': '',
  14286. 'decimal': '',
  14287. 'lower-alpha': '',
  14288. 'lower-roman': '',
  14289. 'upper-alpha': '',
  14290. 'upper-roman': ''
  14291. },
  14292. 'insertunorderedlist': {
  14293. 'circle': '',
  14294. 'disc': '',
  14295. 'square': '',
  14296. 'dash': '',
  14297. 'dot': ''
  14298. },
  14299. listDefaultPaddingLeft: '30',
  14300. listiconpath: 'http://bs.baidu.com/listicon/',
  14301. maxListLevel: -1,//-1不限制
  14302. disablePInList: false
  14303. });
  14304. function listToArray(list) {
  14305. var arr = [];
  14306. for (var p in list) {
  14307. arr.push(p)
  14308. }
  14309. return arr;
  14310. }
  14311. var listStyle = {
  14312. 'OL': listToArray(me.options.insertorderedlist),
  14313. 'UL': listToArray(me.options.insertunorderedlist)
  14314. };
  14315. var liiconpath = me.options.listiconpath;
  14316. //根据用户配置,调整customStyle
  14317. for (var s in customStyle) {
  14318. if (!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)) {
  14319. delete customStyle[s];
  14320. }
  14321. }
  14322. me.ready(function () {
  14323. var customCss = [];
  14324. for (var p in customStyle) {
  14325. if (p == 'dash' || p == 'dot') {
  14326. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath + customStyle[p] + '.gif)}');
  14327. customCss.push('ul.custom_' + p + '{list-style:none;}ul.custom_' + p + ' li{background-position:0 3px;background-repeat:no-repeat}');
  14328. } else {
  14329. for (var i = 0; i < 99; i++) {
  14330. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-' + customStyle[p] + i + '.gif)}')
  14331. }
  14332. customCss.push('ol.custom_' + p + '{list-style:none;}ol.custom_' + p + ' li{background-position:0 3px;background-repeat:no-repeat}');
  14333. }
  14334. switch (p) {
  14335. case 'cn':
  14336. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:25px}');
  14337. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  14338. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:55px}');
  14339. break;
  14340. case 'cn1':
  14341. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:30px}');
  14342. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  14343. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:55px}');
  14344. break;
  14345. case 'cn2':
  14346. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:40px}');
  14347. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:55px}');
  14348. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:68px}');
  14349. break;
  14350. case 'num':
  14351. case 'num1':
  14352. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:25px}');
  14353. break;
  14354. case 'num2':
  14355. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:35px}');
  14356. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  14357. break;
  14358. case 'dash':
  14359. customCss.push('li.list-' + p + '-paddingleft{padding-left:35px}');
  14360. break;
  14361. case 'dot':
  14362. customCss.push('li.list-' + p + '-paddingleft{padding-left:20px}');
  14363. }
  14364. }
  14365. customCss.push('.list-paddingleft-1{padding-left:0}');
  14366. customCss.push('.list-paddingleft-2{padding-left:' + me.options.listDefaultPaddingLeft + 'px}');
  14367. customCss.push('.list-paddingleft-3{padding-left:' + me.options.listDefaultPaddingLeft * 2 + 'px}');
  14368. //如果不给宽度会在自定应样式里出现滚动条
  14369. utils.cssRule('list', 'ol,ul{margin:0;pading:0;' + (browser.ie ? '' : 'width:95%') + '}li{clear:both;}' + customCss.join('\n'), me.document);
  14370. });
  14371. //单独处理剪切的问题
  14372. me.ready(function () {
  14373. domUtils.on(me.body, 'cut', function () {
  14374. setTimeout(function () {
  14375. var rng = me.selection.getRange(), li;
  14376. //trace:3416
  14377. if (!rng.collapsed) {
  14378. if (li = domUtils.findParentByTagName(rng.startContainer, 'li', true)) {
  14379. if (!li.nextSibling && domUtils.isEmptyBlock(li)) {
  14380. var pn = li.parentNode, node;
  14381. if (node = pn.previousSibling) {
  14382. domUtils.remove(pn);
  14383. rng.setStartAtLast(node).collapse(true);
  14384. rng.select(true);
  14385. } else if (node = pn.nextSibling) {
  14386. domUtils.remove(pn);
  14387. rng.setStartAtFirst(node).collapse(true);
  14388. rng.select(true);
  14389. } else {
  14390. var tmpNode = me.document.createElement('p');
  14391. domUtils.fillNode(me.document, tmpNode);
  14392. pn.parentNode.insertBefore(tmpNode, pn);
  14393. domUtils.remove(pn);
  14394. rng.setStart(tmpNode, 0).collapse(true);
  14395. rng.select(true);
  14396. }
  14397. }
  14398. }
  14399. }
  14400. })
  14401. })
  14402. });
  14403. function getStyle(node) {
  14404. var cls = node.className;
  14405. if (domUtils.hasClass(node, /custom_/)) {
  14406. return cls.match(/custom_(\w+)/)[1]
  14407. }
  14408. return domUtils.getStyle(node, 'list-style-type')
  14409. }
  14410. me.addListener('beforepaste', function (type, html) {
  14411. var me = this,
  14412. rng = me.selection.getRange(), li;
  14413. var root = UE.htmlparser(html.html, true);
  14414. if (li = domUtils.findParentByTagName(rng.startContainer, 'li', true)) {
  14415. var list = li.parentNode, tagName = list.tagName == 'OL' ? 'ul' : 'ol';
  14416. utils.each(root.getNodesByTagName(tagName), function (n) {
  14417. n.tagName = list.tagName;
  14418. n.setAttr();
  14419. if (n.parentNode === root) {
  14420. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  14421. } else {
  14422. var className = n.parentNode.getAttr('class');
  14423. if (className && /custom_/.test(className)) {
  14424. type = className.match(/custom_(\w+)/)[1]
  14425. } else {
  14426. type = n.parentNode.getStyle('list-style-type');
  14427. }
  14428. if (!type) {
  14429. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  14430. }
  14431. }
  14432. var index = utils.indexOf(listStyle[list.tagName], type);
  14433. if (n.parentNode !== root)
  14434. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14435. var currentStyle = listStyle[list.tagName][index];
  14436. if (customStyle[currentStyle]) {
  14437. n.setAttr('class', 'custom_' + currentStyle)
  14438. } else {
  14439. n.setStyle('list-style-type', currentStyle)
  14440. }
  14441. })
  14442. }
  14443. html.html = root.toHtml();
  14444. });
  14445. //导出时,去掉p标签
  14446. me.getOpt('disablePInList') === true && me.addOutputRule(function (root) {
  14447. utils.each(root.getNodesByTagName('li'), function (li) {
  14448. var newChildrens = [], index = 0;
  14449. utils.each(li.children, function (n) {
  14450. if (n.tagName == 'p') {
  14451. var tmpNode;
  14452. while (tmpNode = n.children.pop()) {
  14453. newChildrens.splice(index, 0, tmpNode);
  14454. tmpNode.parentNode = li;
  14455. lastNode = tmpNode;
  14456. }
  14457. tmpNode = newChildrens[newChildrens.length - 1];
  14458. if (!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br') {
  14459. var br = UE.uNode.createElement('br');
  14460. br.parentNode = li;
  14461. newChildrens.push(br);
  14462. }
  14463. index = newChildrens.length;
  14464. }
  14465. });
  14466. if (newChildrens.length) {
  14467. li.children = newChildrens;
  14468. }
  14469. });
  14470. });
  14471. //进入编辑器的li要套p标签
  14472. me.addInputRule(function (root) {
  14473. utils.each(root.getNodesByTagName('li'), function (li) {
  14474. var tmpP = UE.uNode.createElement('p');
  14475. for (var i = 0, ci; ci = li.children[i];) {
  14476. if (ci.type == 'text' || dtd.p[ci.tagName]) {
  14477. tmpP.appendChild(ci);
  14478. } else {
  14479. if (tmpP.firstChild()) {
  14480. li.insertBefore(tmpP, ci);
  14481. tmpP = UE.uNode.createElement('p');
  14482. i = i + 2;
  14483. } else {
  14484. i++;
  14485. }
  14486. }
  14487. }
  14488. if (tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()) {
  14489. li.appendChild(tmpP);
  14490. }
  14491. //trace:3357
  14492. //p不能为空
  14493. if (!tmpP.firstChild()) {
  14494. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14495. }
  14496. //去掉末尾的空白
  14497. var p = li.firstChild();
  14498. var lastChild = p.lastChild();
  14499. if (lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)) {
  14500. p.removeChild(lastChild)
  14501. }
  14502. });
  14503. if (me.options.autoTransWordToList) {
  14504. var orderlisttype = {
  14505. 'num1': /^\d+\)/,
  14506. 'decimal': /^\d+\./,
  14507. 'lower-alpha': /^[a-z]+\)/,
  14508. 'upper-alpha': /^[A-Z]+\./,
  14509. 'cn': /^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14510. 'cn2': /^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14511. },
  14512. unorderlisttype = {
  14513. 'square': 'n'
  14514. };
  14515. function checkListType(content, container) {
  14516. var span = container.firstChild();
  14517. if (span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))) {
  14518. for (var p in unorderlisttype) {
  14519. if (unorderlisttype[p] == span.data) {
  14520. return p
  14521. }
  14522. }
  14523. return 'disc'
  14524. }
  14525. for (var p in orderlisttype) {
  14526. if (orderlisttype[p].test(content)) {
  14527. return p;
  14528. }
  14529. }
  14530. }
  14531. utils.each(root.getNodesByTagName('p'), function (node) {
  14532. if (node.getAttr('class') != 'MsoListParagraph') {
  14533. return
  14534. }
  14535. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14536. node.setStyle('margin', '');
  14537. node.setStyle('margin-left', '');
  14538. node.setAttr('class', '');
  14539. function appendLi(list, p, type) {
  14540. if (list.tagName == 'ol') {
  14541. if (browser.ie) {
  14542. var first = p.firstChild();
  14543. if (first.type == 'element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())) {
  14544. p.removeChild(first);
  14545. }
  14546. } else {
  14547. p.innerHTML(p.innerHTML().replace(orderlisttype[type], ''));
  14548. }
  14549. } else {
  14550. p.removeChild(p.firstChild())
  14551. }
  14552. var li = UE.uNode.createElement('li');
  14553. li.appendChild(p);
  14554. list.appendChild(li);
  14555. }
  14556. var tmp = node, type, cacheNode = node;
  14557. if (node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(), node))) {
  14558. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14559. if (customStyle[type]) {
  14560. list.setAttr('class', 'custom_' + type)
  14561. } else {
  14562. list.setStyle('list-style-type', type)
  14563. }
  14564. while (node && node.parentNode.tagName != 'li' && checkListType(node.innerText(), node)) {
  14565. tmp = node.nextSibling();
  14566. if (!tmp) {
  14567. node.parentNode.insertBefore(list, node)
  14568. }
  14569. appendLi(list, node, type);
  14570. node = tmp;
  14571. }
  14572. if (!list.parentNode && node && node.parentNode) {
  14573. node.parentNode.insertBefore(list, node)
  14574. }
  14575. }
  14576. var span = cacheNode.firstChild();
  14577. if (span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())) {
  14578. span.parentNode.removeChild(span)
  14579. }
  14580. })
  14581. }
  14582. });
  14583. //调整索引标签
  14584. me.addListener('contentchange', function () {
  14585. adjustListStyle(me.document)
  14586. });
  14587. function adjustListStyle(doc, ignore) {
  14588. utils.each(domUtils.getElementsByTagName(doc, 'ol ul'), function(node) {
  14589. if (!domUtils.inDoc(node, doc))
  14590. return;
  14591. var parent = node.parentNode;
  14592. if (parent.tagName == node.tagName) {
  14593. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14594. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14595. if (nodeStyleType == parentStyleType) {
  14596. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14597. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14598. setListStyle(node, listStyle[node.tagName][styleIndex])
  14599. }
  14600. }
  14601. var index = 0, type = 2;
  14602. if (domUtils.hasClass(node, /custom_/)) {
  14603. if (!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent, /custom_/))) {
  14604. type = 1;
  14605. }
  14606. } else {
  14607. if (/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent, /custom_/)) {
  14608. type = 3;
  14609. }
  14610. }
  14611. var style = domUtils.getStyle(node, 'list-style-type');
  14612. style && (node.style.cssText = 'list-style-type:' + style);
  14613. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/, '')) + ' list-paddingleft-' + type;
  14614. utils.each(domUtils.getElementsByTagName(node, 'li'), function (li) {
  14615. li.style.cssText && (li.style.cssText = '');
  14616. if (!li.firstChild) {
  14617. domUtils.remove(li);
  14618. return;
  14619. }
  14620. if (li.parentNode !== node) {
  14621. return;
  14622. }
  14623. index++;
  14624. if (domUtils.hasClass(node, /custom_/)) {
  14625. var paddingLeft = 1, currentStyle = getStyle(node);
  14626. if (node.tagName == 'OL') {
  14627. if (currentStyle) {
  14628. switch (currentStyle) {
  14629. case 'cn':
  14630. case 'cn1':
  14631. case 'cn2':
  14632. if (index > 10 && (index % 10 == 0 || index > 10 && index < 20)) {
  14633. paddingLeft = 2
  14634. } else if (index > 20) {
  14635. paddingLeft = 3
  14636. }
  14637. break;
  14638. case 'num2':
  14639. if (index > 9) {
  14640. paddingLeft = 2
  14641. }
  14642. }
  14643. }
  14644. li.className = 'list-' + customStyle[currentStyle] + index + ' ' + 'list-' + currentStyle + '-paddingleft-' + paddingLeft;
  14645. } else {
  14646. li.className = 'list-' + customStyle[currentStyle] + ' ' + 'list-' + currentStyle + '-paddingleft';
  14647. }
  14648. } else {
  14649. li.className = li.className.replace(/list-[\w\-]+/gi, '');
  14650. }
  14651. var className = li.getAttribute('class');
  14652. if (className !== null && !className.replace(/\s/g, '')) {
  14653. domUtils.removeAttributes(li, 'class')
  14654. }
  14655. });
  14656. !ignore && adjustList(node, node.tagName.toLowerCase(), getStyle(node) || domUtils.getStyle(node, 'list-style-type'), true);
  14657. })
  14658. }
  14659. function adjustList(list, tag, style, ignoreEmpty) {
  14660. var nextList = list.nextSibling;
  14661. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14662. domUtils.moveChild(nextList, list);
  14663. if (nextList.childNodes.length == 0) {
  14664. domUtils.remove(nextList);
  14665. }
  14666. }
  14667. if (nextList && domUtils.isFillChar(nextList)) {
  14668. domUtils.remove(nextList);
  14669. }
  14670. var preList = list.previousSibling;
  14671. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14672. domUtils.moveChild(list, preList);
  14673. }
  14674. if (preList && domUtils.isFillChar(preList)) {
  14675. domUtils.remove(preList);
  14676. }
  14677. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14678. if (getStyle(list)) {
  14679. adjustListStyle(list.ownerDocument, true)
  14680. }
  14681. }
  14682. function setListStyle(list, style) {
  14683. if (customStyle[style]) {
  14684. list.className = 'custom_' + style;
  14685. }
  14686. try {
  14687. domUtils.setStyle(list, 'list-style-type', style);
  14688. } catch (e) {
  14689. }
  14690. }
  14691. function clearEmptySibling(node) {
  14692. var tmpNode = node.previousSibling;
  14693. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14694. domUtils.remove(tmpNode);
  14695. }
  14696. tmpNode = node.nextSibling;
  14697. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14698. domUtils.remove(tmpNode);
  14699. }
  14700. }
  14701. me.addListener('keydown', function (type, evt) {
  14702. function preventAndSave() {
  14703. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14704. me.fireEvent('contentchange');
  14705. me.undoManger && me.undoManger.save();
  14706. }
  14707. function findList(node, filterFn) {
  14708. while (node && !domUtils.isBody(node)) {
  14709. if (filterFn(node)) {
  14710. return null
  14711. }
  14712. if (node.nodeType == 1 && /[ou]l/i.test(node.tagName)) {
  14713. return node;
  14714. }
  14715. node = node.parentNode;
  14716. }
  14717. return null;
  14718. }
  14719. var keyCode = evt.keyCode || evt.which;
  14720. if (keyCode == 13 && !evt.shiftKey) {//回车
  14721. var rng = me.selection.getRange(),
  14722. parent = domUtils.findParent(rng.startContainer, function (node) {
  14723. return domUtils.isBlockElm(node)
  14724. }, true),
  14725. li = domUtils.findParentByTagName(rng.startContainer, 'li', true);
  14726. if (parent && parent.tagName != 'PRE' && !li) {
  14727. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'), '');
  14728. if (/^\s*1\s*\.[^\d]/.test(html)) {
  14729. parent.innerHTML = html.replace(/^\s*1\s*\./, '');
  14730. rng.setStartAtLast(parent).collapse(true).select();
  14731. me.__hasEnterExecCommand = true;
  14732. me.execCommand('insertorderedlist');
  14733. me.__hasEnterExecCommand = false;
  14734. }
  14735. }
  14736. var range = me.selection.getRange(),
  14737. start = findList(range.startContainer, function (node) {
  14738. return node.tagName == 'TABLE';
  14739. }),
  14740. end = range.collapsed ? start : findList(range.endContainer, function (node) {
  14741. return node.tagName == 'TABLE';
  14742. });
  14743. if (start && end && start === end) {
  14744. if (!range.collapsed) {
  14745. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14746. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14747. if (start && end && start === end) {
  14748. range.deleteContents();
  14749. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14750. if (li && domUtils.isEmptyBlock(li)) {
  14751. pre = li.previousSibling;
  14752. next = li.nextSibling;
  14753. p = me.document.createElement('p');
  14754. domUtils.fillNode(me.document, p);
  14755. parentList = li.parentNode;
  14756. if (pre && next) {
  14757. range.setStart(next, 0).collapse(true).select(true);
  14758. domUtils.remove(li);
  14759. } else {
  14760. if (!pre && !next || !pre) {
  14761. parentList.parentNode.insertBefore(p, parentList);
  14762. } else {
  14763. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14764. }
  14765. domUtils.remove(li);
  14766. if (!parentList.firstChild) {
  14767. domUtils.remove(parentList);
  14768. }
  14769. range.setStart(p, 0).setCursor();
  14770. }
  14771. preventAndSave();
  14772. return;
  14773. }
  14774. } else {
  14775. var tmpRange = range.cloneRange(),
  14776. bk = tmpRange.collapse(false).createBookmark();
  14777. range.deleteContents();
  14778. tmpRange.moveToBookmark(bk);
  14779. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14780. clearEmptySibling(li);
  14781. tmpRange.select();
  14782. preventAndSave();
  14783. return;
  14784. }
  14785. }
  14786. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14787. if (li) {
  14788. if (domUtils.isEmptyBlock(li)) {
  14789. bk = range.createBookmark();
  14790. var parentList = li.parentNode;
  14791. if (li !== parentList.lastChild) {
  14792. domUtils.breakParent(li, parentList);
  14793. clearEmptySibling(li);
  14794. } else {
  14795. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14796. if (domUtils.isEmptyNode(parentList)) {
  14797. domUtils.remove(parentList);
  14798. }
  14799. }
  14800. //嵌套不处理
  14801. if (!dtd.$list[li.parentNode.tagName]) {
  14802. if (!domUtils.isBlockElm(li.firstChild)) {
  14803. p = me.document.createElement('p');
  14804. li.parentNode.insertBefore(p, li);
  14805. while (li.firstChild) {
  14806. p.appendChild(li.firstChild);
  14807. }
  14808. domUtils.remove(li);
  14809. } else {
  14810. domUtils.remove(li, true);
  14811. }
  14812. }
  14813. range.moveToBookmark(bk).select();
  14814. } else {
  14815. var first = li.firstChild;
  14816. if (!first || !domUtils.isBlockElm(first)) {
  14817. var p = me.document.createElement('p');
  14818. !li.firstChild && domUtils.fillNode(me.document, p);
  14819. while (li.firstChild) {
  14820. p.appendChild(li.firstChild);
  14821. }
  14822. li.appendChild(p);
  14823. first = p;
  14824. }
  14825. var span = me.document.createElement('span');
  14826. range.insertNode(span);
  14827. domUtils.breakParent(span, li);
  14828. var nextLi = span.nextSibling;
  14829. first = nextLi.firstChild;
  14830. if (!first) {
  14831. p = me.document.createElement('p');
  14832. domUtils.fillNode(me.document, p);
  14833. nextLi.appendChild(p);
  14834. first = p;
  14835. }
  14836. if (domUtils.isEmptyNode(first)) {
  14837. first.innerHTML = '';
  14838. domUtils.fillNode(me.document, first);
  14839. }
  14840. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14841. domUtils.remove(span);
  14842. var pre = nextLi.previousSibling;
  14843. if (pre && domUtils.isEmptyBlock(pre)) {
  14844. pre.innerHTML = '<p></p>';
  14845. domUtils.fillNode(me.document, pre.firstChild);
  14846. }
  14847. }
  14848. // }
  14849. preventAndSave();
  14850. }
  14851. }
  14852. }
  14853. if (keyCode == 8) {
  14854. //修中ie中li下的问题
  14855. range = me.selection.getRange();
  14856. if (range.collapsed && domUtils.isStartInblock(range)) {
  14857. tmpRange = range.cloneRange().trimBoundary();
  14858. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14859. //要在li的最左边,才能处理
  14860. if (li && domUtils.isStartInblock(tmpRange)) {
  14861. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14862. if (start && start !== li.firstChild) {
  14863. var parentList = domUtils.findParentByTagName(start, ['ol', 'ul']);
  14864. domUtils.breakParent(start, parentList);
  14865. clearEmptySibling(start);
  14866. me.fireEvent('contentchange');
  14867. range.setStart(start, 0).setCursor(false, true);
  14868. me.fireEvent('saveScene');
  14869. domUtils.preventDefault(evt);
  14870. return;
  14871. }
  14872. if (li && (pre = li.previousSibling)) {
  14873. if (keyCode == 46 && li.childNodes.length) {
  14874. return;
  14875. }
  14876. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14877. if (dtd.$list[pre.tagName]) {
  14878. pre = pre.lastChild;
  14879. }
  14880. me.undoManger && me.undoManger.save();
  14881. first = li.firstChild;
  14882. if (domUtils.isBlockElm(first)) {
  14883. if (domUtils.isEmptyNode(first)) {
  14884. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14885. pre.appendChild(first);
  14886. range.setStart(first, 0).setCursor(false, true);
  14887. //first不是唯一的节点
  14888. while (li.firstChild) {
  14889. pre.appendChild(li.firstChild);
  14890. }
  14891. } else {
  14892. span = me.document.createElement('span');
  14893. range.insertNode(span);
  14894. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14895. if (domUtils.isEmptyBlock(pre)) {
  14896. pre.innerHTML = '';
  14897. }
  14898. domUtils.moveChild(li, pre);
  14899. range.setStartBefore(span).collapse(true).select(true);
  14900. domUtils.remove(span);
  14901. }
  14902. } else {
  14903. if (domUtils.isEmptyNode(li)) {
  14904. var p = me.document.createElement('p');
  14905. pre.appendChild(p);
  14906. range.setStart(p, 0).setCursor();
  14907. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14908. } else {
  14909. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14910. while (li.firstChild) {
  14911. pre.appendChild(li.firstChild);
  14912. }
  14913. }
  14914. }
  14915. domUtils.remove(li);
  14916. me.fireEvent('contentchange');
  14917. me.fireEvent('saveScene');
  14918. domUtils.preventDefault(evt);
  14919. return;
  14920. }
  14921. //trace:980
  14922. if (li && !li.previousSibling) {
  14923. var parentList = li.parentNode;
  14924. var bk = range.createBookmark();
  14925. if (domUtils.isTagNode(parentList.parentNode, 'ol ul')) {
  14926. parentList.parentNode.insertBefore(li, parentList);
  14927. if (domUtils.isEmptyNode(parentList)) {
  14928. domUtils.remove(parentList)
  14929. }
  14930. } else {
  14931. while (li.firstChild) {
  14932. parentList.parentNode.insertBefore(li.firstChild, parentList);
  14933. }
  14934. domUtils.remove(li);
  14935. if (domUtils.isEmptyNode(parentList)) {
  14936. domUtils.remove(parentList)
  14937. }
  14938. }
  14939. range.moveToBookmark(bk).setCursor(false, true);
  14940. me.fireEvent('contentchange');
  14941. me.fireEvent('saveScene');
  14942. domUtils.preventDefault(evt);
  14943. return;
  14944. }
  14945. }
  14946. }
  14947. }
  14948. });
  14949. me.addListener('keyup', function (type, evt) {
  14950. var keyCode = evt.keyCode || evt.which;
  14951. if (keyCode == 8) {
  14952. var rng = me.selection.getRange(), list;
  14953. if (list = domUtils.findParentByTagName(rng.startContainer, ['ol', 'ul'], true)) {
  14954. adjustList(list, list.tagName.toLowerCase(), getStyle(list) || domUtils.getComputedStyle(list, 'list-style-type'), true)
  14955. }
  14956. }
  14957. });
  14958. //处理tab键
  14959. me.addListener('tabkeydown', function () {
  14960. var range = me.selection.getRange();
  14961. //控制级数
  14962. function checkLevel(li) {
  14963. if (me.options.maxListLevel != -1) {
  14964. var level = li.parentNode, levelNum = 0;
  14965. while (/[ou]l/i.test(level.tagName)) {
  14966. levelNum++;
  14967. level = level.parentNode;
  14968. }
  14969. if (levelNum >= me.options.maxListLevel) {
  14970. return true;
  14971. }
  14972. }
  14973. }
  14974. //只以开始为准
  14975. //todo 后续改进
  14976. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14977. if (li) {
  14978. var bk;
  14979. if (range.collapsed) {
  14980. if (checkLevel(li))
  14981. return true;
  14982. var parentLi = li.parentNode,
  14983. list = me.document.createElement(parentLi.tagName),
  14984. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi) || domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14985. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14986. var currentStyle = listStyle[list.tagName][index];
  14987. setListStyle(list, currentStyle);
  14988. if (domUtils.isStartInblock(range)) {
  14989. me.fireEvent('saveScene');
  14990. bk = range.createBookmark();
  14991. parentLi.insertBefore(list, li);
  14992. list.appendChild(li);
  14993. adjustList(list, list.tagName.toLowerCase(), currentStyle);
  14994. me.fireEvent('contentchange');
  14995. range.moveToBookmark(bk).select(true);
  14996. return true;
  14997. }
  14998. } else {
  14999. me.fireEvent('saveScene');
  15000. bk = range.createBookmark();
  15001. for (var i = 0, closeList, parents = domUtils.findParents(li), ci; ci = parents[i++];) {
  15002. if (domUtils.isTagNode(ci, 'ol ul')) {
  15003. closeList = ci;
  15004. break;
  15005. }
  15006. }
  15007. var current = li;
  15008. if (bk.end) {
  15009. while (current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)) {
  15010. if (checkLevel(current)) {
  15011. current = domUtils.getNextDomNode(current, false, null, function (node) {
  15012. return node !== closeList
  15013. });
  15014. continue;
  15015. }
  15016. var parentLi = current.parentNode,
  15017. list = me.document.createElement(parentLi.tagName),
  15018. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi) || domUtils.getComputedStyle(parentLi, 'list-style-type'));
  15019. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  15020. var currentStyle = listStyle[list.tagName][currentIndex];
  15021. setListStyle(list, currentStyle);
  15022. parentLi.insertBefore(list, current);
  15023. while (current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)) {
  15024. li = current.nextSibling;
  15025. list.appendChild(current);
  15026. if (!li || domUtils.isTagNode(li, 'ol ul')) {
  15027. if (li) {
  15028. while (li = li.firstChild) {
  15029. if (li.tagName == 'LI') {
  15030. break;
  15031. }
  15032. }
  15033. } else {
  15034. li = domUtils.getNextDomNode(current, false, null, function (node) {
  15035. return node !== closeList
  15036. });
  15037. }
  15038. break;
  15039. }
  15040. current = li;
  15041. }
  15042. adjustList(list, list.tagName.toLowerCase(), currentStyle);
  15043. current = li;
  15044. }
  15045. }
  15046. me.fireEvent('contentchange');
  15047. range.moveToBookmark(bk).select();
  15048. return true;
  15049. }
  15050. }
  15051. });
  15052. function getLi(start) {
  15053. while (start && !domUtils.isBody(start)) {
  15054. if (start.nodeName == 'TABLE') {
  15055. return null;
  15056. }
  15057. if (start.nodeName == 'LI') {
  15058. return start
  15059. }
  15060. start = start.parentNode;
  15061. }
  15062. }
  15063. /**
  15064. * 有序列表,与“insertunorderedlist”命令互斥
  15065. * @command insertorderedlist
  15066. * @method execCommand
  15067. * @param { String } command 命令字符串
  15068. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  15069. * @example
  15070. * ```javascript
  15071. * editor.execCommand( 'insertorderedlist','decimal');
  15072. * ```
  15073. */
  15074. /**
  15075. * 查询当前选区内容是否有序列表
  15076. * @command insertorderedlist
  15077. * @method queryCommandState
  15078. * @param { String } cmd 命令字符串
  15079. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  15080. * @example
  15081. * ```javascript
  15082. * editor.queryCommandState( 'insertorderedlist' );
  15083. * ```
  15084. */
  15085. /**
  15086. * 查询当前选区内容是否有序列表
  15087. * @command insertorderedlist
  15088. * @method queryCommandValue
  15089. * @param { String } cmd 命令字符串
  15090. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  15091. * @example
  15092. * ```javascript
  15093. * editor.queryCommandValue( 'insertorderedlist' );
  15094. * ```
  15095. */
  15096. /**
  15097. * 无序列表,与“insertorderedlist”命令互斥
  15098. * @command insertunorderedlist
  15099. * @method execCommand
  15100. * @param { String } command 命令字符串
  15101. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  15102. * @example
  15103. * ```javascript
  15104. * editor.execCommand( 'insertunorderedlist','circle');
  15105. * ```
  15106. */
  15107. /**
  15108. * 查询当前是否有word文档粘贴进来的图片
  15109. * @command insertunorderedlist
  15110. * @method insertunorderedlist
  15111. * @param { String } command 命令字符串
  15112. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  15113. * @example
  15114. * ```javascript
  15115. * editor.queryCommandState( 'insertunorderedlist' );
  15116. * ```
  15117. */
  15118. /**
  15119. * 查询当前选区内容是否有序列表
  15120. * @command insertunorderedlist
  15121. * @method queryCommandValue
  15122. * @param { String } command 命令字符串
  15123. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  15124. * @example
  15125. * ```javascript
  15126. * editor.queryCommandValue( 'insertunorderedlist' );
  15127. * ```
  15128. */
  15129. me.commands['insertorderedlist'] =
  15130. me.commands['insertunorderedlist'] = {
  15131. execCommand: function (command, style) {
  15132. if (!style) {
  15133. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  15134. }
  15135. var me = this,
  15136. range = this.selection.getRange(),
  15137. filterFn = function (node) {
  15138. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  15139. },
  15140. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  15141. frag = me.document.createDocumentFragment();
  15142. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  15143. //range.shrinkBoundary();//.adjustmentBoundary();
  15144. range.adjustmentBoundary().shrinkBoundary();
  15145. var bko = range.createBookmark(true),
  15146. start = getLi(me.document.getElementById(bko.start)),
  15147. modifyStart = 0,
  15148. end = getLi(me.document.getElementById(bko.end)),
  15149. modifyEnd = 0,
  15150. startParent, endParent,
  15151. list, tmp;
  15152. if (start || end) {
  15153. start && (startParent = start.parentNode);
  15154. if (!bko.end) {
  15155. end = start;
  15156. }
  15157. end && (endParent = end.parentNode);
  15158. if (startParent === endParent) {
  15159. while (start !== end) {
  15160. tmp = start;
  15161. start = start.nextSibling;
  15162. if (!domUtils.isBlockElm(tmp.firstChild)) {
  15163. var p = me.document.createElement('p');
  15164. while (tmp.firstChild) {
  15165. p.appendChild(tmp.firstChild);
  15166. }
  15167. tmp.appendChild(p);
  15168. }
  15169. frag.appendChild(tmp);
  15170. }
  15171. tmp = me.document.createElement('span');
  15172. startParent.insertBefore(tmp, end);
  15173. if (!domUtils.isBlockElm(end.firstChild)) {
  15174. p = me.document.createElement('p');
  15175. while (end.firstChild) {
  15176. p.appendChild(end.firstChild);
  15177. }
  15178. end.appendChild(p);
  15179. }
  15180. frag.appendChild(end);
  15181. domUtils.breakParent(tmp, startParent);
  15182. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  15183. domUtils.remove(tmp.previousSibling);
  15184. }
  15185. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  15186. domUtils.remove(tmp.nextSibling)
  15187. }
  15188. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  15189. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  15190. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  15191. if (domUtils.isTagNode(ci, 'ol ul')) {
  15192. // 删除时,子列表不处理
  15193. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  15194. // while(li.firstChild){
  15195. // tmpFrag.appendChild(li.firstChild);
  15196. // }
  15197. //
  15198. // });
  15199. tmpFrag.appendChild(ci);
  15200. } else {
  15201. while (ci.firstChild) {
  15202. tmpFrag.appendChild(ci.firstChild);
  15203. domUtils.remove(ci);
  15204. }
  15205. }
  15206. }
  15207. tmp.parentNode.insertBefore(tmpFrag, tmp);
  15208. } else {
  15209. list = me.document.createElement(tag);
  15210. setListStyle(list, style);
  15211. list.appendChild(frag);
  15212. tmp.parentNode.insertBefore(list, tmp);
  15213. }
  15214. domUtils.remove(tmp);
  15215. list && adjustList(list, tag, style);
  15216. range.moveToBookmark(bko).select();
  15217. return;
  15218. }
  15219. //开始
  15220. if (start) {
  15221. while (start) {
  15222. tmp = start.nextSibling;
  15223. if (domUtils.isTagNode(start, 'ol ul')) {
  15224. frag.appendChild(start);
  15225. } else {
  15226. var tmpfrag = me.document.createDocumentFragment(),
  15227. hasBlock = 0;
  15228. while (start.firstChild) {
  15229. if (domUtils.isBlockElm(start.firstChild)) {
  15230. hasBlock = 1;
  15231. }
  15232. tmpfrag.appendChild(start.firstChild);
  15233. }
  15234. if (!hasBlock) {
  15235. var tmpP = me.document.createElement('p');
  15236. tmpP.appendChild(tmpfrag);
  15237. frag.appendChild(tmpP);
  15238. } else {
  15239. frag.appendChild(tmpfrag);
  15240. }
  15241. domUtils.remove(start);
  15242. }
  15243. start = tmp;
  15244. }
  15245. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  15246. if (domUtils.isEmptyNode(startParent)) {
  15247. range.setStartBefore(startParent);
  15248. domUtils.remove(startParent);
  15249. } else {
  15250. range.setStartAfter(startParent);
  15251. }
  15252. modifyStart = 1;
  15253. }
  15254. if (end && domUtils.inDoc(endParent, me.document)) {
  15255. //结束
  15256. start = endParent.firstChild;
  15257. while (start && start !== end) {
  15258. tmp = start.nextSibling;
  15259. if (domUtils.isTagNode(start, 'ol ul')) {
  15260. frag.appendChild(start);
  15261. } else {
  15262. tmpfrag = me.document.createDocumentFragment();
  15263. hasBlock = 0;
  15264. while (start.firstChild) {
  15265. if (domUtils.isBlockElm(start.firstChild)) {
  15266. hasBlock = 1;
  15267. }
  15268. tmpfrag.appendChild(start.firstChild);
  15269. }
  15270. if (!hasBlock) {
  15271. tmpP = me.document.createElement('p');
  15272. tmpP.appendChild(tmpfrag);
  15273. frag.appendChild(tmpP);
  15274. } else {
  15275. frag.appendChild(tmpfrag);
  15276. }
  15277. domUtils.remove(start);
  15278. }
  15279. start = tmp;
  15280. }
  15281. var tmpDiv = domUtils.createElement(me.document, 'div', {
  15282. 'tmpDiv': 1
  15283. });
  15284. domUtils.moveChild(end, tmpDiv);
  15285. frag.appendChild(tmpDiv);
  15286. domUtils.remove(end);
  15287. endParent.parentNode.insertBefore(frag, endParent);
  15288. range.setEndBefore(endParent);
  15289. if (domUtils.isEmptyNode(endParent)) {
  15290. domUtils.remove(endParent);
  15291. }
  15292. modifyEnd = 1;
  15293. }
  15294. }
  15295. if (!modifyStart) {
  15296. range.setStartBefore(me.document.getElementById(bko.start));
  15297. }
  15298. if (bko.end && !modifyEnd) {
  15299. range.setEndAfter(me.document.getElementById(bko.end));
  15300. }
  15301. range.enlarge(true, function (node) {
  15302. return notExchange[node.tagName];
  15303. });
  15304. frag = me.document.createDocumentFragment();
  15305. var bk = range.createBookmark(),
  15306. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  15307. tmpRange = range.cloneRange(),
  15308. tmpNode,
  15309. block = domUtils.isBlockElm;
  15310. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  15311. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  15312. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  15313. while (current.firstChild) {
  15314. frag.appendChild(current.firstChild);
  15315. }
  15316. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  15317. domUtils.remove(current);
  15318. current = tmpNode;
  15319. continue;
  15320. }
  15321. tmpNode = current;
  15322. tmpRange.setStartBefore(current);
  15323. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current))) {
  15324. tmpNode = current;
  15325. current = domUtils.getNextDomNode(current, false, null, function (node) {
  15326. return !notExchange[node.tagName];
  15327. });
  15328. }
  15329. if (current && block(current)) {
  15330. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  15331. if (tmp && domUtils.isBookmarkNode(tmp)) {
  15332. current = domUtils.getNextDomNode(tmp, false, filterFn);
  15333. tmpNode = tmp;
  15334. }
  15335. }
  15336. tmpRange.setEndAfter(tmpNode);
  15337. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  15338. var li = range.document.createElement('li');
  15339. li.appendChild(tmpRange.extractContents());
  15340. if (domUtils.isEmptyNode(li)) {
  15341. var tmpNode = range.document.createElement('p');
  15342. while (li.firstChild) {
  15343. tmpNode.appendChild(li.firstChild)
  15344. }
  15345. li.appendChild(tmpNode);
  15346. }
  15347. frag.appendChild(li);
  15348. } else {
  15349. current = domUtils.getNextDomNode(current, true, filterFn);
  15350. }
  15351. }
  15352. range.moveToBookmark(bk).collapse(true);
  15353. list = me.document.createElement(tag);
  15354. setListStyle(list, style);
  15355. list.appendChild(frag);
  15356. range.insertNode(list);
  15357. //当前list上下看能否合并
  15358. adjustList(list, tag, style);
  15359. //去掉冗余的tmpDiv
  15360. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  15361. if (ci.getAttribute('tmpDiv')) {
  15362. domUtils.remove(ci, true)
  15363. }
  15364. }
  15365. range.moveToBookmark(bko).select();
  15366. },
  15367. queryCommandState: function (command) {
  15368. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  15369. var path = this.selection.getStartElementPath();
  15370. for (var i = 0, ci; ci = path[i++];) {
  15371. if (ci.nodeName == 'TABLE') {
  15372. return 0
  15373. }
  15374. if (tag == ci.nodeName.toLowerCase()) {
  15375. return 1
  15376. }
  15377. ;
  15378. }
  15379. return 0;
  15380. },
  15381. queryCommandValue: function (command) {
  15382. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  15383. var path = this.selection.getStartElementPath(),
  15384. node;
  15385. for (var i = 0, ci; ci = path[i++];) {
  15386. if (ci.nodeName == 'TABLE') {
  15387. node = null;
  15388. break;
  15389. }
  15390. if (tag == ci.nodeName.toLowerCase()) {
  15391. node = ci;
  15392. break;
  15393. }
  15394. ;
  15395. }
  15396. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  15397. }
  15398. };
  15399. };
  15400. // plugins/source.js
  15401. /**
  15402. * 源码编辑插件
  15403. * @file
  15404. * @since 1.2.6.1
  15405. */
  15406. (function () {
  15407. var sourceEditors = {
  15408. textarea: function (editor, holder) {
  15409. var textarea = holder.ownerDocument.createElement('textarea');
  15410. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  15411. // todo: IE下只有onresize属性可用... 很纠结
  15412. if (browser.ie && browser.version < 8) {
  15413. textarea.style.width = holder.offsetWidth + 'px';
  15414. textarea.style.height = holder.offsetHeight + 'px';
  15415. holder.onresize = function () {
  15416. textarea.style.width = holder.offsetWidth + 'px';
  15417. textarea.style.height = holder.offsetHeight + 'px';
  15418. };
  15419. }
  15420. holder.appendChild(textarea);
  15421. return {
  15422. setContent: function (content) {
  15423. textarea.value = content;
  15424. },
  15425. getContent: function () {
  15426. return textarea.value;
  15427. },
  15428. select: function () {
  15429. var range;
  15430. if (browser.ie) {
  15431. range = textarea.createTextRange();
  15432. range.collapse(true);
  15433. range.select();
  15434. } else {
  15435. //todo: chrome下无法设置焦点
  15436. textarea.setSelectionRange(0, 0);
  15437. textarea.focus();
  15438. }
  15439. },
  15440. dispose: function () {
  15441. holder.removeChild(textarea);
  15442. // todo
  15443. holder.onresize = null;
  15444. textarea = null;
  15445. holder = null;
  15446. }
  15447. };
  15448. },
  15449. codemirror: function (editor, holder) {
  15450. var codeEditor = window.CodeMirror(holder, {
  15451. mode: "text/html",
  15452. tabMode: "indent",
  15453. lineNumbers: true,
  15454. lineWrapping: true
  15455. });
  15456. var dom = codeEditor.getWrapperElement();
  15457. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  15458. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  15459. codeEditor.refresh();
  15460. return {
  15461. getCodeMirror: function () {
  15462. return codeEditor;
  15463. },
  15464. setContent: function (content) {
  15465. codeEditor.setValue(content);
  15466. },
  15467. getContent: function () {
  15468. return codeEditor.getValue();
  15469. },
  15470. select: function () {
  15471. codeEditor.focus();
  15472. },
  15473. dispose: function () {
  15474. holder.removeChild(dom);
  15475. dom = null;
  15476. codeEditor = null;
  15477. }
  15478. };
  15479. }
  15480. };
  15481. UE.plugins['source'] = function() {
  15482. var me = this;
  15483. var opt = this.options;
  15484. var sourceMode = false;
  15485. var sourceEditor;
  15486. var orgSetContent;
  15487. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15488. me.setOpt({
  15489. sourceEditorFirst: false
  15490. });
  15491. function createSourceEditor(holder) {
  15492. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15493. }
  15494. var bakCssText;
  15495. //解决在源码模式下getContent不能得到最新的内容问题
  15496. var oldGetContent,
  15497. bakAddress;
  15498. /**
  15499. * 切换源码模式和编辑模式
  15500. * @command source
  15501. * @method execCommand
  15502. * @param { String } cmd 命令字符串
  15503. * @example
  15504. * ```javascript
  15505. * editor.execCommand( 'source');
  15506. * ```
  15507. */
  15508. /**
  15509. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15510. * @command source
  15511. * @method queryCommandState
  15512. * @param { String } cmd 命令字符串
  15513. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15514. * @example
  15515. * ```javascript
  15516. * editor.queryCommandState( 'source' );
  15517. * ```
  15518. */
  15519. me.commands['source'] = {
  15520. execCommand: function () {
  15521. sourceMode = !sourceMode;
  15522. if (sourceMode) {
  15523. bakAddress = me.selection.getRange().createAddress(false, true);
  15524. me.undoManger && me.undoManger.save(true);
  15525. if (browser.gecko) {
  15526. me.body.contentEditable = false;
  15527. }
  15528. bakCssText = me.iframe.style.cssText;
  15529. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15530. me.fireEvent('beforegetcontent');
  15531. var root = UE.htmlparser(me.body.innerHTML);
  15532. me.filterOutputRule(root);
  15533. root.traversal(function (node) {
  15534. if (node.type == 'element') {
  15535. switch (node.tagName) {
  15536. case 'td':
  15537. case 'th':
  15538. case 'caption':
  15539. if (node.children && node.children.length == 1) {
  15540. if (node.firstChild().tagName == 'br') {
  15541. node.removeChild(node.firstChild())
  15542. }
  15543. }
  15544. ;
  15545. break;
  15546. case 'pre':
  15547. node.innerText(node.innerText().replace(/&nbsp;/g, ' '))
  15548. }
  15549. }
  15550. });
  15551. me.fireEvent('aftergetcontent');
  15552. var content = root.toHtml(true);
  15553. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15554. sourceEditor.setContent(content);
  15555. orgSetContent = me.setContent;
  15556. me.setContent = function (html) {
  15557. //这里暂时不触发事件,防止报错
  15558. var root = UE.htmlparser(html);
  15559. me.filterInputRule(root);
  15560. html = root.toHtml();
  15561. sourceEditor.setContent(html);
  15562. };
  15563. setTimeout(function () {
  15564. sourceEditor.select();
  15565. me.addListener('fullscreenchanged', function () {
  15566. try {
  15567. sourceEditor.getCodeMirror().refresh()
  15568. } catch (e) {
  15569. }
  15570. });
  15571. });
  15572. //重置getContent,源码模式下取值也能是最新的数据
  15573. oldGetContent = me.getContent;
  15574. me.getContent = function () {
  15575. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15576. };
  15577. } else {
  15578. me.iframe.style.cssText = bakCssText;
  15579. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15580. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15581. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>', 'g'), function (a, b) {
  15582. if (b && !dtd.$inlineWithA[b.toLowerCase()]) {
  15583. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g, '');
  15584. }
  15585. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g, '')
  15586. });
  15587. me.setContent = orgSetContent;
  15588. me.setContent(cont);
  15589. sourceEditor.dispose();
  15590. sourceEditor = null;
  15591. //还原getContent方法
  15592. me.getContent = oldGetContent;
  15593. var first = me.body.firstChild;
  15594. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15595. if (!first) {
  15596. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15597. first = me.body.firstChild;
  15598. }
  15599. //要在ifm为显示时ff才能取到selection,否则报错
  15600. //这里不能比较位置了
  15601. me.undoManger && me.undoManger.save(true);
  15602. if (browser.gecko) {
  15603. var input = document.createElement('input');
  15604. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15605. document.body.appendChild(input);
  15606. me.body.contentEditable = false;
  15607. setTimeout(function () {
  15608. domUtils.setViewportOffset(input, {left: -32768, top: 0});
  15609. input.focus();
  15610. setTimeout(function () {
  15611. me.body.contentEditable = true;
  15612. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15613. domUtils.remove(input);
  15614. });
  15615. });
  15616. } else {
  15617. //ie下有可能报错,比如在代码顶头的情况
  15618. try {
  15619. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15620. } catch (e) {
  15621. }
  15622. }
  15623. }
  15624. this.fireEvent('sourcemodechanged', sourceMode);
  15625. },
  15626. queryCommandState: function () {
  15627. return sourceMode | 0;
  15628. },
  15629. notNeedUndo: 1
  15630. };
  15631. var oldQueryCommandState = me.queryCommandState;
  15632. me.queryCommandState = function (cmdName) {
  15633. cmdName = cmdName.toLowerCase();
  15634. if (sourceMode) {
  15635. //源码模式下可以开启的命令
  15636. return cmdName in {
  15637. 'source': 1,
  15638. 'fullscreen': 1
  15639. } ? 1 : -1
  15640. }
  15641. return oldQueryCommandState.apply(this, arguments);
  15642. };
  15643. if (opt.sourceEditor == "codemirror") {
  15644. me.addListener("ready", function () {
  15645. utils.loadFile(document, {
  15646. src: opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15647. tag: "script",
  15648. type: "text/javascript",
  15649. defer: "defer"
  15650. }, function () {
  15651. if (opt.sourceEditorFirst) {
  15652. setTimeout(function () {
  15653. me.execCommand("source");
  15654. }, 0);
  15655. }
  15656. });
  15657. utils.loadFile(document, {
  15658. tag: "link",
  15659. rel: "stylesheet",
  15660. type: "text/css",
  15661. href: opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15662. });
  15663. });
  15664. }
  15665. };
  15666. })();
  15667. // plugins/enterkey.js
  15668. ///import core
  15669. ///import plugins/undo.js
  15670. ///commands 设置回车标签p或br
  15671. ///commandsName EnterKey
  15672. ///commandsTitle 设置回车标签p或br
  15673. /**
  15674. * @description 处理回车
  15675. * @author zhanyi
  15676. */
  15677. UE.plugins['enterkey'] = function () {
  15678. var hTag,
  15679. me = this,
  15680. tag = me.options.enterTag;
  15681. me.addListener('keyup', function (type, evt) {
  15682. var keyCode = evt.keyCode || evt.which;
  15683. if (keyCode == 13) {
  15684. var range = me.selection.getRange(),
  15685. start = range.startContainer,
  15686. doSave;
  15687. //修正在h1-h6里边回车后不能嵌套p的问题
  15688. if (!browser.ie) {
  15689. if (/h\d/i.test(hTag)) {
  15690. if (browser.gecko) {
  15691. var h = domUtils.findParentByTagName(start, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'caption', 'table'], true);
  15692. if (!h) {
  15693. me.document.execCommand('formatBlock', false, '<p>');
  15694. doSave = 1;
  15695. }
  15696. } else {
  15697. //chrome remove div
  15698. if (start.nodeType == 1) {
  15699. var tmp = me.document.createTextNode(''), div;
  15700. range.insertNode(tmp);
  15701. div = domUtils.findParentByTagName(tmp, 'div', true);
  15702. if (div) {
  15703. var p = me.document.createElement('p');
  15704. while (div.firstChild) {
  15705. p.appendChild(div.firstChild);
  15706. }
  15707. div.parentNode.insertBefore(p, div);
  15708. domUtils.remove(div);
  15709. range.setStartBefore(tmp).setCursor();
  15710. doSave = 1;
  15711. }
  15712. domUtils.remove(tmp);
  15713. }
  15714. }
  15715. if (me.undoManger && doSave) {
  15716. me.undoManger.save();
  15717. }
  15718. }
  15719. //没有站位符,会出现多行的问题
  15720. browser.opera && range.select();
  15721. } else {
  15722. me.fireEvent('saveScene', true, true)
  15723. }
  15724. }
  15725. });
  15726. me.addListener('keydown', function (type, evt) {
  15727. var keyCode = evt.keyCode || evt.which;
  15728. if (keyCode == 13) {//回车
  15729. if (me.fireEvent('beforeenterkeydown')) {
  15730. domUtils.preventDefault(evt);
  15731. return;
  15732. }
  15733. me.fireEvent('saveScene', true, true);
  15734. hTag = '';
  15735. var range = me.selection.getRange();
  15736. if (!range.collapsed) {
  15737. //跨td不能删
  15738. var start = range.startContainer,
  15739. end = range.endContainer,
  15740. startTd = domUtils.findParentByTagName(start, 'td', true),
  15741. endTd = domUtils.findParentByTagName(end, 'td', true);
  15742. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15743. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  15744. return;
  15745. }
  15746. }
  15747. if (tag == 'p') {
  15748. if (!browser.ie) {
  15749. start = domUtils.findParentByTagName(range.startContainer, ['ol', 'ul', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'caption'], true);
  15750. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15751. //trace:2431
  15752. if (!start && !browser.opera) {
  15753. me.document.execCommand('formatBlock', false, '<p>');
  15754. if (browser.gecko) {
  15755. range = me.selection.getRange();
  15756. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15757. start && domUtils.removeDirtyAttr(start);
  15758. }
  15759. } else {
  15760. hTag = start.tagName;
  15761. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15762. }
  15763. }
  15764. } else {
  15765. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  15766. if (!range.collapsed) {
  15767. range.deleteContents();
  15768. start = range.startContainer;
  15769. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15770. while (start.nodeType == 1) {
  15771. if (dtd.$empty[start.tagName]) {
  15772. range.setStartBefore(start).setCursor();
  15773. if (me.undoManger) {
  15774. me.undoManger.save();
  15775. }
  15776. return false;
  15777. }
  15778. if (!start.firstChild) {
  15779. var br = range.document.createElement('br');
  15780. start.appendChild(br);
  15781. range.setStart(start, 0).setCursor();
  15782. if (me.undoManger) {
  15783. me.undoManger.save();
  15784. }
  15785. return false;
  15786. }
  15787. start = start.firstChild;
  15788. }
  15789. if (start === range.startContainer.childNodes[range.startOffset]) {
  15790. br = range.document.createElement('br');
  15791. range.insertNode(br).setCursor();
  15792. } else {
  15793. range.setStart(start, 0).setCursor();
  15794. }
  15795. } else {
  15796. br = range.document.createElement('br');
  15797. range.insertNode(br).setStartAfter(br).setCursor();
  15798. }
  15799. } else {
  15800. br = range.document.createElement('br');
  15801. range.insertNode(br);
  15802. var parent = br.parentNode;
  15803. if (parent.lastChild === br) {
  15804. br.parentNode.insertBefore(br.cloneNode(true), br);
  15805. range.setStartBefore(br);
  15806. } else {
  15807. range.setStartAfter(br);
  15808. }
  15809. range.setCursor();
  15810. }
  15811. }
  15812. }
  15813. });
  15814. };
  15815. // plugins/keystrokes.js
  15816. /* 处理特殊键的兼容性问题 */
  15817. UE.plugins['keystrokes'] = function () {
  15818. var me = this;
  15819. var collapsed = true;
  15820. me.addListener('keydown', function (type, evt) {
  15821. var keyCode = evt.keyCode || evt.which,
  15822. rng = me.selection.getRange();
  15823. //处理全选的情况
  15824. if (!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <= 90
  15825. || keyCode >= 48 && keyCode <= 57 ||
  15826. keyCode >= 96 && keyCode <= 111 || {
  15827. 13: 1,
  15828. 8: 1,
  15829. 46: 1
  15830. }[keyCode])
  15831. ) {
  15832. var tmpNode = rng.startContainer;
  15833. if (domUtils.isFillChar(tmpNode)) {
  15834. rng.setStartBefore(tmpNode)
  15835. }
  15836. tmpNode = rng.endContainer;
  15837. if (domUtils.isFillChar(tmpNode)) {
  15838. rng.setEndAfter(tmpNode)
  15839. }
  15840. rng.txtToElmBoundary();
  15841. //结束边界可能放到了br的前边,要把br包含进来
  15842. // x[xxx]<br/>
  15843. if (rng.endContainer && rng.endContainer.nodeType == 1) {
  15844. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15845. if (tmpNode && domUtils.isBr(tmpNode)) {
  15846. rng.setEndAfter(tmpNode);
  15847. }
  15848. }
  15849. if (rng.startOffset == 0) {
  15850. tmpNode = rng.startContainer;
  15851. if (domUtils.isBoundaryNode(tmpNode, 'firstChild')) {
  15852. tmpNode = rng.endContainer;
  15853. if (rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode, 'lastChild')) {
  15854. me.fireEvent('saveScene');
  15855. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15856. rng.setStart(me.body.firstChild, 0).setCursor(false, true);
  15857. me._selectionChange();
  15858. return;
  15859. }
  15860. }
  15861. }
  15862. }
  15863. //处理backspace
  15864. if (keyCode == keymap.Backspace) {
  15865. rng = me.selection.getRange();
  15866. collapsed = rng.collapsed;
  15867. if (me.fireEvent('delkeydown', evt)) {
  15868. return;
  15869. }
  15870. var start, end;
  15871. //避免按两次删除才能生效的问题
  15872. if (rng.collapsed && rng.inFillChar()) {
  15873. start = rng.startContainer;
  15874. if (domUtils.isFillChar(start)) {
  15875. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15876. domUtils.remove(start)
  15877. } else {
  15878. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar), '');
  15879. rng.startOffset--;
  15880. rng.collapse(true).select(true)
  15881. }
  15882. }
  15883. //解决选中control元素不能删除的问题
  15884. if (start = rng.getClosedNode()) {
  15885. me.fireEvent('saveScene');
  15886. rng.setStartBefore(start);
  15887. domUtils.remove(start);
  15888. rng.setCursor();
  15889. me.fireEvent('saveScene');
  15890. domUtils.preventDefault(evt);
  15891. return;
  15892. }
  15893. //阻止在table上的删除
  15894. if (!browser.ie) {
  15895. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15896. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15897. if (start && !end || !start && end || start !== end) {
  15898. evt.preventDefault();
  15899. return;
  15900. }
  15901. }
  15902. }
  15903. //处理tab键的逻辑
  15904. if (keyCode == keymap.Tab) {
  15905. //不处理以下标签
  15906. var excludeTagNameForTabKey = {
  15907. 'ol': 1,
  15908. 'ul': 1,
  15909. 'table': 1
  15910. };
  15911. //处理组件里的tab按下事件
  15912. if (me.fireEvent('tabkeydown', evt)) {
  15913. domUtils.preventDefault(evt);
  15914. return;
  15915. }
  15916. var range = me.selection.getRange();
  15917. me.fireEvent('saveScene');
  15918. for (var i = 0, txt = '', tabSize = me.options.tabSize || 4, tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15919. txt += tabNode;
  15920. }
  15921. var span = me.document.createElement('span');
  15922. span.innerHTML = txt + domUtils.fillChar;
  15923. if (range.collapsed) {
  15924. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15925. } else {
  15926. var filterFn = function (node) {
  15927. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15928. };
  15929. //普通的情况
  15930. start = domUtils.findParent(range.startContainer, filterFn, true);
  15931. end = domUtils.findParent(range.endContainer, filterFn, true);
  15932. if (start && end && start === end) {
  15933. range.deleteContents();
  15934. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15935. } else {
  15936. var bookmark = range.createBookmark();
  15937. range.enlarge(true);
  15938. var bookmark2 = range.createBookmark(),
  15939. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15940. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15941. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15942. current = domUtils.getNextDomNode(current, false, filterFn);
  15943. }
  15944. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15945. }
  15946. }
  15947. domUtils.preventDefault(evt)
  15948. }
  15949. //trace:1634
  15950. //ff的del键在容器空的时候,也会删除
  15951. if (browser.gecko && keyCode == 46) {
  15952. range = me.selection.getRange();
  15953. if (range.collapsed) {
  15954. start = range.startContainer;
  15955. if (domUtils.isEmptyBlock(start)) {
  15956. var parent = start.parentNode;
  15957. while (domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)) {
  15958. start = parent;
  15959. parent = parent.parentNode;
  15960. }
  15961. if (start === parent.lastChild)
  15962. evt.preventDefault();
  15963. return;
  15964. }
  15965. }
  15966. }
  15967. });
  15968. me.addListener('keyup', function (type, evt) {
  15969. var keyCode = evt.keyCode || evt.which,
  15970. rng, me = this;
  15971. if (keyCode == keymap.Backspace) {
  15972. if (me.fireEvent('delkeyup')) {
  15973. return;
  15974. }
  15975. rng = me.selection.getRange();
  15976. if (rng.collapsed) {
  15977. var tmpNode,
  15978. autoClearTagName = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  15979. if (tmpNode = domUtils.findParentByTagName(rng.startContainer, autoClearTagName, true)) {
  15980. if (domUtils.isEmptyBlock(tmpNode)) {
  15981. var pre = tmpNode.previousSibling;
  15982. if (pre && pre.nodeName != 'TABLE') {
  15983. domUtils.remove(tmpNode);
  15984. rng.setStartAtLast(pre).setCursor(false, true);
  15985. return;
  15986. } else {
  15987. var next = tmpNode.nextSibling;
  15988. if (next && next.nodeName != 'TABLE') {
  15989. domUtils.remove(tmpNode);
  15990. rng.setStartAtFirst(next).setCursor(false, true);
  15991. return;
  15992. }
  15993. }
  15994. }
  15995. }
  15996. //处理当删除到body时,要重新给p标签展位
  15997. if (domUtils.isBody(rng.startContainer)) {
  15998. var tmpNode = domUtils.createElement(me.document, 'p', {
  15999. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  16000. });
  16001. rng.insertNode(tmpNode).setStart(tmpNode, 0).setCursor(false, true);
  16002. }
  16003. }
  16004. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  16005. if (!collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))) {
  16006. if (browser.ie) {
  16007. var span = rng.document.createElement('span');
  16008. rng.insertNode(span).setStartBefore(span).collapse(true);
  16009. rng.select();
  16010. domUtils.remove(span)
  16011. } else {
  16012. rng.select()
  16013. }
  16014. }
  16015. }
  16016. })
  16017. };
  16018. // plugins/fiximgclick.js
  16019. ///import core
  16020. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  16021. ///commandsName FixImgClick
  16022. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  16023. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  16024. UE.plugins['fiximgclick'] = (function() {
  16025. var elementUpdated = false;
  16026. function Scale() {
  16027. this.editor = null;
  16028. this.resizer = null;
  16029. this.cover = null;
  16030. this.doc = document;
  16031. this.prePos = { x: 0, y: 0 };
  16032. this.startPos = { x: 0, y: 0 };
  16033. }
  16034. (function () {
  16035. var rect = [
  16036. //[left, top, width, height]
  16037. [0, 0, -1, -1],
  16038. [0, 0, 0, -1],
  16039. [0, 0, 1, -1],
  16040. [0, 0, -1, 0],
  16041. [0, 0, 1, 0],
  16042. [0, 0, -1, 1],
  16043. [0, 0, 0, 1],
  16044. [0, 0, 1, 1]
  16045. ];
  16046. Scale.prototype = {
  16047. init: function(editor) {
  16048. var me = this;
  16049. me.editor = editor;
  16050. me.startPos = this.prePos = { x: 0, y: 0 };
  16051. me.dragId = -1;
  16052. var hands = [],
  16053. cover = me.cover = document.createElement('div'),
  16054. resizer = me.resizer = document.createElement('div');
  16055. cover.id = me.editor.ui.id + '_imagescale_cover';
  16056. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  16057. domUtils.on(cover, 'mousedown click', function() {
  16058. me.hide();
  16059. });
  16060. for (i = 0; i < 8; i++) {
  16061. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  16062. }
  16063. resizer.id = me.editor.ui.id + '_imagescale';
  16064. resizer.className = 'edui-editor-imagescale';
  16065. resizer.innerHTML = hands.join('');
  16066. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  16067. me.editor.ui.getDom().appendChild(cover);
  16068. me.editor.ui.getDom().appendChild(resizer);
  16069. me.initStyle();
  16070. me.initEvents();
  16071. },
  16072. initStyle: function() {
  16073. 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;}' +
  16074. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  16075. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  16076. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  16077. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  16078. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  16079. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  16080. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  16081. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  16082. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  16083. },
  16084. initEvents: function() {
  16085. var me = this;
  16086. me.startPos.x = me.startPos.y = 0;
  16087. me.isDraging = false;
  16088. },
  16089. _eventHandler: function (e) {
  16090. var me = this;
  16091. switch (e.type) {
  16092. case 'mousedown':
  16093. var hand = e.target || e.srcElement, hand;
  16094. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  16095. me.dragId = hand.className.slice(-1);
  16096. me.startPos.x = me.prePos.x = e.clientX;
  16097. me.startPos.y = me.prePos.y = e.clientY;
  16098. domUtils.on(me.doc, 'mousemove', me.proxy(me._eventHandler, me));
  16099. }
  16100. break;
  16101. case 'mousemove':
  16102. if (me.dragId != -1) {
  16103. me.updateContainerStyle(me.dragId, {
  16104. x: e.clientX - me.prePos.x,
  16105. y: e.clientY - me.prePos.y
  16106. });
  16107. me.prePos.x = e.clientX;
  16108. me.prePos.y = e.clientY;
  16109. elementUpdated = true;
  16110. me.updateTargetElement();
  16111. }
  16112. break;
  16113. case 'mouseup':
  16114. if (me.dragId != -1) {
  16115. me.updateContainerStyle(me.dragId, {
  16116. x: e.clientX - me.prePos.x,
  16117. y: e.clientY - me.prePos.y
  16118. });
  16119. me.updateTargetElement();
  16120. if (me.target.parentNode) me.attachTo(me.target);
  16121. me.dragId = -1;
  16122. }
  16123. domUtils.un(me.doc, 'mousemove', me.proxy(me._eventHandler, me));
  16124. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  16125. if (elementUpdated) {
  16126. elementUpdated = false;
  16127. me.editor.fireEvent('contentchange');
  16128. }
  16129. break;
  16130. default:
  16131. break;
  16132. }
  16133. },
  16134. updateTargetElement: function () {
  16135. var me = this;
  16136. domUtils.setStyles(me.target, {
  16137. 'width': me.resizer.style.width,
  16138. 'height': me.resizer.style.height
  16139. });
  16140. me.target.width = parseInt(me.resizer.style.width);
  16141. me.target.height = parseInt(me.resizer.style.height);
  16142. me.attachTo(me.target);
  16143. },
  16144. updateContainerStyle: function (dir, offset) {
  16145. var me = this,
  16146. dom = me.resizer, tmp;
  16147. if (rect[dir][0] != 0) {
  16148. tmp = parseInt(dom.style.left) + offset.x;
  16149. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  16150. }
  16151. if (rect[dir][1] != 0) {
  16152. tmp = parseInt(dom.style.top) + offset.y;
  16153. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  16154. }
  16155. if (rect[dir][2] != 0) {
  16156. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  16157. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  16158. }
  16159. if (rect[dir][3] != 0) {
  16160. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  16161. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  16162. }
  16163. },
  16164. _validScaledProp: function(prop, value) {
  16165. var ele = this.resizer,
  16166. wrap = document;
  16167. value = isNaN(value) ? 0 : value;
  16168. switch (prop) {
  16169. case 'left':
  16170. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  16171. case 'top':
  16172. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  16173. case 'width':
  16174. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  16175. case 'height':
  16176. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  16177. }
  16178. },
  16179. hideCover: function() {
  16180. this.cover.style.display = 'none';
  16181. },
  16182. showCover: function() {
  16183. var me = this,
  16184. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  16185. iframePos = domUtils.getXY(me.editor.iframe);
  16186. domUtils.setStyles(me.cover, {
  16187. 'width': me.editor.iframe.offsetWidth + 'px',
  16188. 'height': me.editor.iframe.offsetHeight + 'px',
  16189. 'top': iframePos.y - editorPos.y + 'px',
  16190. 'left': iframePos.x - editorPos.x + 'px',
  16191. 'position': 'absolute',
  16192. 'display': ''
  16193. })
  16194. },
  16195. show: function (targetObj) {
  16196. var me = this;
  16197. me.resizer.style.display = 'block';
  16198. if (targetObj) me.attachTo(targetObj);
  16199. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  16200. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  16201. me.showCover();
  16202. me.editor.fireEvent('afterscaleshow', me);
  16203. me.editor.fireEvent('saveScene');
  16204. },
  16205. hide: function() {
  16206. var me = this;
  16207. me.hideCover();
  16208. me.resizer.style.display = 'none';
  16209. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  16210. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  16211. me.editor.fireEvent('afterscalehide', me);
  16212. },
  16213. proxy: function(fn, context) {
  16214. return function(e) {
  16215. return fn.apply(context || this, arguments);
  16216. };
  16217. },
  16218. attachTo: function(targetObj) {
  16219. var me = this,
  16220. target = me.target = targetObj,
  16221. resizer = this.resizer,
  16222. imgPos = domUtils.getXY(target),
  16223. iframePos = domUtils.getXY(me.editor.iframe),
  16224. editorPos = domUtils.getXY(resizer.parentNode);
  16225. domUtils.setStyles(resizer, {
  16226. 'width': target.width + 'px',
  16227. 'height': target.height + 'px',
  16228. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  16229. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  16230. });
  16231. }
  16232. }
  16233. })();
  16234. return function() {
  16235. var me = this,
  16236. imageScale;
  16237. me.setOpt('imageScaleEnabled', true);
  16238. if (!browser.ie && me.options.imageScaleEnabled) {
  16239. me.addListener('click', function(type, e) {
  16240. var range = me.selection.getRange(),
  16241. img = range.getClosedNode();
  16242. if (img && img.tagName == 'IMG' && me.body.contentEditable != "false") {
  16243. if (img.className.indexOf("edui-faked-music") != -1 ||
  16244. img.getAttribute("anchorname") ||
  16245. domUtils.hasClass(img, 'loadingclass') ||
  16246. domUtils.hasClass(img, 'loaderrorclass')) {
  16247. return
  16248. }
  16249. if (!imageScale) {
  16250. imageScale = new Scale();
  16251. imageScale.init(me);
  16252. me.ui.getDom().appendChild(imageScale.resizer);
  16253. var _keyDownHandler = function(e) {
  16254. imageScale.hide();
  16255. if (imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  16256. }, _mouseDownHandler = function(e) {
  16257. var ele = e.target || e.srcElement;
  16258. if (ele && (ele.className === undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  16259. _keyDownHandler(e);
  16260. }
  16261. }, timer;
  16262. me.addListener('afterscaleshow', function(e) {
  16263. me.addListener('beforekeydown', _keyDownHandler);
  16264. me.addListener('beforemousedown', _mouseDownHandler);
  16265. domUtils.on(document, 'keydown', _keyDownHandler);
  16266. domUtils.on(document, 'mousedown', _mouseDownHandler);
  16267. me.selection.getNative().removeAllRanges();
  16268. });
  16269. me.addListener('afterscalehide', function(e) {
  16270. me.removeListener('beforekeydown', _keyDownHandler);
  16271. me.removeListener('beforemousedown', _mouseDownHandler);
  16272. domUtils.un(document, 'keydown', _keyDownHandler);
  16273. domUtils.un(document, 'mousedown', _mouseDownHandler);
  16274. var target = imageScale.target;
  16275. if (target.parentNode) {
  16276. me.selection.getRange().selectNode(target).select();
  16277. }
  16278. });
  16279. //TODO 有iframe的情况,mousedown不能往下传。。
  16280. domUtils.on(imageScale.resizer, 'mousedown', function(e) {
  16281. me.selection.getNative().removeAllRanges();
  16282. var ele = e.target || e.srcElement;
  16283. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  16284. timer = setTimeout(function() {
  16285. imageScale.hide();
  16286. if (imageScale.target) me.selection.getRange().selectNode(ele).select();
  16287. }, 200);
  16288. }
  16289. });
  16290. domUtils.on(imageScale.resizer, 'mouseup', function(e) {
  16291. var ele = e.target || e.srcElement;
  16292. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  16293. clearTimeout(timer);
  16294. }
  16295. });
  16296. }
  16297. imageScale.show(img);
  16298. } else {
  16299. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  16300. }
  16301. });
  16302. }
  16303. if (browser.webkit) {
  16304. me.addListener('click', function (type, e) {
  16305. if (e.target.tagName == 'IMG' && me.body.contentEditable != "false") {
  16306. var range = new dom.Range(me.document);
  16307. range.selectNode(e.target).select();
  16308. }
  16309. });
  16310. }
  16311. }
  16312. })();
  16313. // plugins/autolink.js
  16314. ///import core
  16315. ///commands 为非ie浏览器自动添加a标签
  16316. ///commandsName AutoLink
  16317. ///commandsTitle 自动增加链接
  16318. /**
  16319. * @description 为非ie浏览器自动添加a标签
  16320. * @author zhanyi
  16321. */
  16322. UE.plugin.register('autolink', function() {
  16323. var cont = 0;
  16324. return !browser.ie ? {
  16325. bindEvents: {
  16326. 'reset': function() {
  16327. cont = 0;
  16328. },
  16329. 'keydown': function(type, evt) {
  16330. var me = this;
  16331. var keyCode = evt.keyCode || evt.which;
  16332. if (keyCode == 32 || keyCode == 13) {
  16333. var sel = me.selection.getNative(),
  16334. range = sel.getRangeAt(0).cloneRange(),
  16335. offset,
  16336. charCode;
  16337. var start = range.startContainer;
  16338. while (start.nodeType == 1 && range.startOffset > 0) {
  16339. start = range.startContainer.childNodes[range.startOffset - 1];
  16340. if (!start) {
  16341. break;
  16342. }
  16343. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  16344. range.collapse(true);
  16345. start = range.startContainer;
  16346. }
  16347. do {
  16348. if (range.startOffset == 0) {
  16349. start = range.startContainer.previousSibling;
  16350. while (start && start.nodeType == 1) {
  16351. start = start.lastChild;
  16352. }
  16353. if (!start || domUtils.isFillChar(start)) {
  16354. break;
  16355. }
  16356. offset = start.nodeValue.length;
  16357. } else {
  16358. start = range.startContainer;
  16359. offset = range.startOffset;
  16360. }
  16361. range.setStart(start, offset - 1);
  16362. charCode = range.toString().charCodeAt(0);
  16363. } while (charCode != 160 && charCode != 32);
  16364. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  16365. while (range.toString().length) {
  16366. if (/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())) {
  16367. break;
  16368. }
  16369. try {
  16370. range.setStart(range.startContainer, range.startOffset + 1);
  16371. } catch (e) {
  16372. //trace:2121
  16373. var start = range.startContainer;
  16374. while (!(next = start.nextSibling)) {
  16375. if (domUtils.isBody(start)) {
  16376. return;
  16377. }
  16378. start = start.parentNode;
  16379. }
  16380. range.setStart(next, 0);
  16381. }
  16382. }
  16383. //range的开始边界已经在a标签里的不再处理
  16384. if (domUtils.findParentByTagName(range.startContainer, 'a', true)) {
  16385. return;
  16386. }
  16387. var a = me.document.createElement('a'), text = me.document.createTextNode(' '), href;
  16388. me.undoManger && me.undoManger.save();
  16389. a.appendChild(range.extractContents());
  16390. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g, '');
  16391. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar, 'g'), '');
  16392. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://" + href;
  16393. a.setAttribute('_src', utils.html(href));
  16394. a.href = utils.html(href);
  16395. range.insertNode(a);
  16396. a.parentNode.insertBefore(text, a.nextSibling);
  16397. range.setStart(text, 0);
  16398. range.collapse(true);
  16399. sel.removeAllRanges();
  16400. sel.addRange(range);
  16401. me.undoManger && me.undoManger.save();
  16402. }
  16403. }
  16404. }
  16405. }
  16406. } : {}
  16407. }, function () {
  16408. var keyCodes = {
  16409. 37: 1, 38: 1, 39: 1, 40: 1,
  16410. 13: 1, 32: 1
  16411. };
  16412. function checkIsCludeLink(node) {
  16413. if (node.nodeType == 3) {
  16414. return null
  16415. }
  16416. if (node.nodeName == 'A') {
  16417. return node;
  16418. }
  16419. var lastChild = node.lastChild;
  16420. while (lastChild) {
  16421. if (lastChild.nodeName == 'A') {
  16422. return lastChild;
  16423. }
  16424. if (lastChild.nodeType == 3) {
  16425. if (domUtils.isWhitespace(lastChild)) {
  16426. lastChild = lastChild.previousSibling;
  16427. continue;
  16428. }
  16429. return null
  16430. }
  16431. lastChild = lastChild.lastChild;
  16432. }
  16433. }
  16434. browser.ie && this.addListener('keyup', function(cmd, evt) {
  16435. var me = this, keyCode = evt.keyCode;
  16436. if (keyCodes[keyCode]) {
  16437. var rng = me.selection.getRange();
  16438. var start = rng.startContainer;
  16439. if (keyCode == 13) {
  16440. while (start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)) {
  16441. start = start.parentNode;
  16442. }
  16443. if (start && !domUtils.isBody(start) && start.nodeName == 'P') {
  16444. var pre = start.previousSibling;
  16445. if (pre && pre.nodeType == 1) {
  16446. var pre = checkIsCludeLink(pre);
  16447. if (pre && !pre.getAttribute('_href')) {
  16448. domUtils.remove(pre, true);
  16449. }
  16450. }
  16451. }
  16452. } else if (keyCode == 32) {
  16453. if (start.nodeType == 3 && /^\s$/.test(start.nodeValue)) {
  16454. start = start.previousSibling;
  16455. if (start && start.nodeName == 'A' && !start.getAttribute('_href')) {
  16456. domUtils.remove(start, true);
  16457. }
  16458. }
  16459. } else {
  16460. start = domUtils.findParentByTagName(start, 'a', true);
  16461. if (start && !start.getAttribute('_href')) {
  16462. var bk = rng.createBookmark();
  16463. domUtils.remove(start, true);
  16464. rng.moveToBookmark(bk).select(true)
  16465. }
  16466. }
  16467. }
  16468. });
  16469. }
  16470. );
  16471. // plugins/autoheight.js
  16472. ///import core
  16473. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  16474. ///commandsName AutoHeight,autoHeightEnabled
  16475. ///commandsTitle 自动增高
  16476. /**
  16477. * @description 自动伸展
  16478. * @author zhanyi
  16479. */
  16480. UE.plugins['autoheight'] = function() {
  16481. var me = this;
  16482. //提供开关,就算加载也可以关闭
  16483. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16484. if (!me.autoHeightEnabled) {
  16485. return;
  16486. }
  16487. var bakOverflow,
  16488. lastHeight = 0,
  16489. options = me.options,
  16490. currentHeight,
  16491. timer;
  16492. function adjustHeight() {
  16493. var me = this;
  16494. clearTimeout(timer);
  16495. if (isFullscreen) return;
  16496. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16497. timer = setTimeout(function() {
  16498. var node = me.body.lastChild;
  16499. while (node && node.nodeType != 1) {
  16500. node = node.previousSibling;
  16501. }
  16502. if (node && node.nodeType == 1) {
  16503. node.style.clear = 'both';
  16504. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25, Math.max(options.minFrameHeight, options.initialFrameHeight));
  16505. if (currentHeight != lastHeight) {
  16506. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16507. me.iframe.parentNode.style.height = currentHeight + 'px';
  16508. }
  16509. me.body.style.height = currentHeight + 'px';
  16510. lastHeight = currentHeight;
  16511. }
  16512. domUtils.removeStyle(node, 'clear');
  16513. }
  16514. }, 50)
  16515. }
  16516. }
  16517. var isFullscreen;
  16518. me.addListener('fullscreenchanged', function (cmd, f) {
  16519. isFullscreen = f
  16520. });
  16521. me.addListener('destroy', function () {
  16522. me.removeListener('contentchange afterinserthtml keyup mouseup', adjustHeight)
  16523. });
  16524. me.enableAutoHeight = function () {
  16525. var me = this;
  16526. if (!me.autoHeightEnabled) {
  16527. return;
  16528. }
  16529. var doc = me.document;
  16530. me.autoHeightEnabled = true;
  16531. bakOverflow = doc.body.style.overflowY;
  16532. doc.body.style.overflowY = 'hidden';
  16533. me.addListener('contentchange afterinserthtml keyup mouseup', adjustHeight);
  16534. //ff不给事件算得不对
  16535. setTimeout(function() {
  16536. adjustHeight.call(me);
  16537. }, browser.gecko ? 100 : 0);
  16538. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16539. };
  16540. me.disableAutoHeight = function() {
  16541. me.body.style.overflowY = bakOverflow || '';
  16542. me.removeListener('contentchange', adjustHeight);
  16543. me.removeListener('keyup', adjustHeight);
  16544. me.removeListener('mouseup', adjustHeight);
  16545. me.autoHeightEnabled = false;
  16546. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16547. };
  16548. me.on('setHeight', function () {
  16549. me.disableAutoHeight()
  16550. });
  16551. me.addListener('ready', function () {
  16552. me.enableAutoHeight();
  16553. //trace:1764
  16554. var timer;
  16555. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16556. clearTimeout(timer);
  16557. timer = setTimeout(function () {
  16558. //trace:3681
  16559. adjustHeight.call(me);
  16560. }, 100);
  16561. });
  16562. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16563. var lastScrollY;
  16564. window.onscroll = function () {
  16565. if (lastScrollY === null) {
  16566. lastScrollY = this.scrollY
  16567. } else if (this.scrollY == 0 && lastScrollY != 0) {
  16568. me.window.scrollTo(0, 0);
  16569. lastScrollY = null;
  16570. }
  16571. }
  16572. });
  16573. };
  16574. // plugins/autofloat.js
  16575. ///import core
  16576. ///commands 悬浮工具栏
  16577. ///commandsName AutoFloat,autoFloatEnabled
  16578. ///commandsTitle 悬浮工具栏
  16579. /**
  16580. * modified by chengchao01
  16581. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16582. */
  16583. UE.plugins['autofloat'] = function () {
  16584. var me = this,
  16585. lang = me.getLang();
  16586. me.setOpt({
  16587. topOffset: 0
  16588. });
  16589. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16590. topOffset = me.options.topOffset;
  16591. //如果不固定toolbar的位置,则直接退出
  16592. if (!optsAutoFloatEnabled) {
  16593. return;
  16594. }
  16595. var uiUtils = UE.ui.uiUtils,
  16596. LteIE6 = browser.ie && browser.version <= 6,
  16597. quirks = browser.quirks;
  16598. function checkHasUI() {
  16599. if (!UE.ui) {
  16600. alert(lang.autofloatMsg);
  16601. return 0;
  16602. }
  16603. return 1;
  16604. }
  16605. function fixIE6FixedPos() {
  16606. var docStyle = document.body.style;
  16607. docStyle.backgroundImage = 'url("about:blank")';
  16608. docStyle.backgroundAttachment = 'fixed';
  16609. }
  16610. var bakCssText,
  16611. placeHolder = document.createElement('div'),
  16612. toolbarBox, orgTop,
  16613. getPosition,
  16614. flag = true; //ie7模式下需要偏移
  16615. function setFloating() {
  16616. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16617. origalFloat = domUtils.getComputedStyle(toolbarBox, 'position'),
  16618. origalLeft = domUtils.getComputedStyle(toolbarBox, 'left');
  16619. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16620. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16621. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16622. if (LteIE6 || (quirks && browser.ie)) {
  16623. if (toolbarBox.style.position != 'absolute') {
  16624. toolbarBox.style.position = 'absolute';
  16625. }
  16626. toolbarBox.style.top = (document.body.scrollTop || document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16627. } else {
  16628. if (browser.ie7Compat && flag) {
  16629. flag = false;
  16630. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left + 2 + 'px';
  16631. }
  16632. if (toolbarBox.style.position != 'fixed') {
  16633. toolbarBox.style.position = 'fixed';
  16634. toolbarBox.style.top = topOffset + "px";
  16635. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16636. }
  16637. }
  16638. }
  16639. function unsetFloating() {
  16640. flag = true;
  16641. if (placeHolder.parentNode) {
  16642. placeHolder.parentNode.removeChild(placeHolder);
  16643. }
  16644. toolbarBox.style.cssText = bakCssText;
  16645. }
  16646. function updateFloating() {
  16647. var rect3 = getPosition(me.container);
  16648. var offset = me.options.toolbarTopOffset || 0;
  16649. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16650. setFloating();
  16651. } else {
  16652. unsetFloating();
  16653. }
  16654. }
  16655. var defer_updateFloating = utils.defer(function() {
  16656. updateFloating();
  16657. }, browser.ie ? 200 : 100, true);
  16658. me.addListener('destroy', function() {
  16659. domUtils.un(window, ['scroll', 'resize'], updateFloating);
  16660. me.removeListener('keydown', defer_updateFloating);
  16661. });
  16662. me.addListener('ready', function() {
  16663. if (checkHasUI(me)) {
  16664. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16665. if (!me.ui) {
  16666. return;
  16667. }
  16668. getPosition = uiUtils.getClientRect;
  16669. toolbarBox = me.ui.getDom('toolbarbox');
  16670. orgTop = getPosition(toolbarBox).top;
  16671. bakCssText = toolbarBox.style.cssText;
  16672. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16673. if (LteIE6) {
  16674. fixIE6FixedPos();
  16675. }
  16676. domUtils.on(window, ['scroll', 'resize'], updateFloating);
  16677. me.addListener('keydown', defer_updateFloating);
  16678. me.addListener('beforefullscreenchange', function (t, enabled) {
  16679. if (enabled) {
  16680. unsetFloating();
  16681. }
  16682. });
  16683. me.addListener('fullscreenchanged', function (t, enabled) {
  16684. if (!enabled) {
  16685. updateFloating();
  16686. }
  16687. });
  16688. me.addListener('sourcemodechanged', function (t, enabled) {
  16689. setTimeout(function () {
  16690. updateFloating();
  16691. }, 0);
  16692. });
  16693. me.addListener("clearDoc", function () {
  16694. setTimeout(function () {
  16695. updateFloating();
  16696. }, 0);
  16697. })
  16698. }
  16699. });
  16700. };
  16701. // plugins/video.js
  16702. /**
  16703. * video插件, 为UEditor提供视频插入支持
  16704. * @file
  16705. * @since 1.2.6.1
  16706. */
  16707. UE.plugins['video'] = function() {
  16708. var me = this;
  16709. /**
  16710. * 创建插入视频字符窜
  16711. * @param url 视频地址
  16712. * @param width 视频宽度
  16713. * @param height 视频高度
  16714. * @param align 视频对齐
  16715. * @param toEmbed 是否以flash代替显示
  16716. * @param addParagraph 是否需要添加P 标签
  16717. */
  16718. function creatInsertStr(url, width, height, id, align, classname, type) {
  16719. url = utils.unhtmlForUrl(url);
  16720. align = utils.unhtml(align);
  16721. classname = utils.unhtml(classname).trim();
  16722. width = parseInt(width, 10) || 0;
  16723. height = parseInt(height, 10) || 0;
  16724. var str;
  16725. switch (type) {
  16726. case 'image':
  16727. str = '<img ' + (id ? 'id="' + id + '"' : '') + ' width="' + width + '" height="' + height + '" _url="' + url + '" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16728. ' 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 + ';' : '') + '" />';
  16729. break;
  16730. case 'embed':
  16731. str = '<embed src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"' : '') +
  16732. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16733. break;
  16734. case 'video':
  16735. var ext = url.substr(url.lastIndexOf('.') + 1);
  16736. if (ext == 'ogv') ext = 'ogg';
  16737. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"' : '') +
  16738. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16739. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16740. break;
  16741. }
  16742. return str;
  16743. }
  16744. function switchImgAndVideo(root, img2video) {
  16745. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'), function (node) {
  16746. var className = node.getAttr('class');
  16747. if (className && className.indexOf('edui-faked-video') != -1) {
  16748. var html = creatInsertStr(img2video ? node.getAttr('_url') : node.getAttr('src'), node.getAttr('width'), node.getAttr('height'), null, node.getStyle('float') || '', className, img2video ? 'embed' : 'image');
  16749. node.parentNode.replaceChild(UE.uNode.createElement(html), node);
  16750. }
  16751. if (className && className.indexOf('edui-upload-video') != -1) {
  16752. var html = creatInsertStr(img2video ? node.getAttr('_url') : node.getAttr('src'), node.getAttr('width'), node.getAttr('height'), null, node.getStyle('float') || '', className, img2video ? 'video' : 'image');
  16753. node.parentNode.replaceChild(UE.uNode.createElement(html), node);
  16754. }
  16755. })
  16756. }
  16757. me.addOutputRule(function (root) {
  16758. switchImgAndVideo(root, true)
  16759. });
  16760. me.addInputRule(function (root) {
  16761. switchImgAndVideo(root)
  16762. });
  16763. /**
  16764. * 插入视频
  16765. * @command insertvideo
  16766. * @method execCommand
  16767. * @param { String } cmd 命令字符串
  16768. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16769. * @example
  16770. * ```javascript
  16771. *
  16772. * var videoAttr = {
  16773. * //视频地址
  16774. * url: 'http://www.youku.com/xxx',
  16775. * //视频宽高值, 单位px
  16776. * width: 200,
  16777. * height: 100
  16778. * };
  16779. *
  16780. * //editor 是编辑器实例
  16781. * //向编辑器插入单个视频
  16782. * editor.execCommand( 'insertvideo', videoAttr );
  16783. * ```
  16784. */
  16785. /**
  16786. * 插入视频
  16787. * @command insertvideo
  16788. * @method execCommand
  16789. * @param { String } cmd 命令字符串
  16790. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16791. * @example
  16792. * ```javascript
  16793. *
  16794. * var videoAttr1 = {
  16795. * //视频地址
  16796. * url: 'http://www.youku.com/xxx',
  16797. * //视频宽高值, 单位px
  16798. * width: 200,
  16799. * height: 100
  16800. * },
  16801. * videoAttr2 = {
  16802. * //视频地址
  16803. * url: 'http://www.youku.com/xxx',
  16804. * //视频宽高值, 单位px
  16805. * width: 200,
  16806. * height: 100
  16807. * }
  16808. *
  16809. * //editor 是编辑器实例
  16810. * //该方法将会向编辑器内插入两个视频
  16811. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16812. * ```
  16813. */
  16814. /**
  16815. * 查询当前光标所在处是否是一个视频
  16816. * @command insertvideo
  16817. * @method queryCommandState
  16818. * @param { String } cmd 需要查询的命令字符串
  16819. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16820. * @example
  16821. * ```javascript
  16822. *
  16823. * //editor 是编辑器实例
  16824. * editor.queryCommandState( 'insertvideo' );
  16825. * ```
  16826. */
  16827. me.commands['insertvideo'] = {
  16828. execCommand: function(cmd, videoObjs, type) {
  16829. videoObjs = utils.isArray(videoObjs) ? videoObjs : [videoObjs];
  16830. var html = [], id = 'tmpVedio', cl;
  16831. for (var i = 0, vi, len = videoObjs.length; i < len; i++) {
  16832. vi = videoObjs[i];
  16833. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin' : 'edui-faked');
  16834. html.push(creatInsertStr(vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'embed'));
  16835. }
  16836. me.execCommand('inserthtml', html.join(''), true);
  16837. var rng = this.selection.getRange();
  16838. // for(var i= 0,len=videoObjs.length;i<len;i++){
  16839. // var img = this.document.getElementById('tmpVedio'+i);
  16840. // domUtils.removeAttributes(img,'id');
  16841. // rng.selectNode(img).select();
  16842. // me.execCommand('imagefloat',videoObjs[i].align)
  16843. // }
  16844. },
  16845. queryCommandState: function() {
  16846. var img = me.selection.getRange().getClosedNode(),
  16847. flag = img && (img.className == 'edui-faked-video' || img.className.indexOf('edui-upload-video') != -1);
  16848. return flag ? 1 : 0;
  16849. },
  16850. };
  16851. };
  16852. // plugins/table.core.js
  16853. /**
  16854. * Created with JetBrains WebStorm.
  16855. * User: taoqili
  16856. * Date: 13-1-18
  16857. * Time: 上午11:09
  16858. * To change this template use File | Settings | File Templates.
  16859. */
  16860. /**
  16861. * UE表格操作类
  16862. * @param table
  16863. * @constructor
  16864. */
  16865. (function() {
  16866. var UETable = UE.UETable = function(table) {
  16867. this.table = table;
  16868. this.indexTable = [];
  16869. this.selectedTds = [];
  16870. this.cellsRange = {};
  16871. this.update(table);
  16872. };
  16873. //===以下为静态工具方法===
  16874. UETable.removeSelectedClass = function (cells) {
  16875. utils.each(cells, function (cell) {
  16876. domUtils.removeClasses(cell, "selectTdClass");
  16877. })
  16878. };
  16879. UETable.addSelectedClass = function (cells) {
  16880. utils.each(cells, function (cell) {
  16881. domUtils.addClass(cell, "selectTdClass");
  16882. })
  16883. };
  16884. UETable.isEmptyBlock = function (node) {
  16885. var reg = new RegExp(domUtils.fillChar, 'g');
  16886. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16887. return 0;
  16888. }
  16889. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16890. if (node.getElementsByTagName(i).length) {
  16891. return 0;
  16892. }
  16893. }
  16894. return 1;
  16895. };
  16896. UETable.getWidth = function (cell) {
  16897. if (!cell) return 0;
  16898. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16899. };
  16900. /**
  16901. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16902. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16903. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16904. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16905. */
  16906. UETable.getTableCellAlignState = function(cells) {
  16907. !utils.isArray(cells) && (cells = [cells]);
  16908. var result = {},
  16909. status = ['align', 'valign'],
  16910. tempStatus = null,
  16911. isSame = true;//状态是否相同
  16912. utils.each(cells, function(cellNode) {
  16913. utils.each(status, function(currentState) {
  16914. tempStatus = cellNode.getAttribute(currentState);
  16915. if (!result[currentState] && tempStatus) {
  16916. result[currentState] = tempStatus;
  16917. } else if (!result[currentState] || (tempStatus !== result[currentState])) {
  16918. isSame = false;
  16919. return false;
  16920. }
  16921. });
  16922. return isSame;
  16923. });
  16924. return isSame ? result : null;
  16925. };
  16926. /**
  16927. * 根据当前选区获取相关的table信息
  16928. * @return {Object}
  16929. */
  16930. UETable.getTableItemsByRange = function(editor) {
  16931. var start = editor.selection.getStart();
  16932. //ff下会选中bookmark
  16933. if (start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16934. start = start.nextSibling;
  16935. }
  16936. //在table或者td边缘有可能存在选中tr的情况
  16937. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16938. tr = cell && cell.parentNode,
  16939. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16940. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16941. return {
  16942. cell: cell,
  16943. tr: tr,
  16944. table: table,
  16945. caption: caption
  16946. }
  16947. };
  16948. UETable.getUETableBySelected = function (editor) {
  16949. var table = UETable.getTableItemsByRange(editor).table;
  16950. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16951. return table.ueTable;
  16952. }
  16953. return null;
  16954. };
  16955. UETable.getDefaultValue = function (editor, table) {
  16956. var borderMap = {
  16957. thin: '0px',
  16958. medium: '1px',
  16959. thick: '2px'
  16960. },
  16961. tableBorder, tdPadding, tdBorder, tmpValue;
  16962. if (!table) {
  16963. table = editor.document.createElement('table');
  16964. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16965. editor.body.appendChild(table);
  16966. var td = table.getElementsByTagName('td')[0];
  16967. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16968. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16969. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16970. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16971. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16972. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16973. domUtils.remove(table);
  16974. return {
  16975. tableBorder: tableBorder,
  16976. tdPadding: tdPadding,
  16977. tdBorder: tdBorder
  16978. };
  16979. } else {
  16980. td = table.getElementsByTagName('td')[0];
  16981. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16982. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16983. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16984. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16985. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16986. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16987. return {
  16988. tableBorder: tableBorder,
  16989. tdPadding: tdPadding,
  16990. tdBorder: tdBorder
  16991. };
  16992. }
  16993. };
  16994. /**
  16995. * 根据当前点击的td或者table获取索引对象
  16996. * @param tdOrTable
  16997. */
  16998. UETable.getUETable = function (tdOrTable) {
  16999. var tag = tdOrTable.tagName.toLowerCase();
  17000. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  17001. if (!tdOrTable.ueTable) {
  17002. tdOrTable.ueTable = new UETable(tdOrTable);
  17003. }
  17004. return tdOrTable.ueTable;
  17005. };
  17006. UETable.cloneCell = function (cell, ignoreMerge, keepPro) {
  17007. if (!cell || utils.isString(cell)) {
  17008. return this.table.ownerDocument.createElement(cell || 'td');
  17009. }
  17010. var flag = domUtils.hasClass(cell, "selectTdClass");
  17011. flag && domUtils.removeClasses(cell, "selectTdClass");
  17012. var tmpCell = cell.cloneNode(true);
  17013. if (ignoreMerge) {
  17014. tmpCell.rowSpan = tmpCell.colSpan = 1;
  17015. }
  17016. //去掉宽高
  17017. !keepPro && domUtils.removeAttributes(tmpCell, 'width height');
  17018. !keepPro && domUtils.removeAttributes(tmpCell, 'style');
  17019. tmpCell.style.borderLeftStyle = "";
  17020. tmpCell.style.borderTopStyle = "";
  17021. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  17022. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  17023. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  17024. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  17025. flag && domUtils.addClass(cell, "selectTdClass");
  17026. return tmpCell;
  17027. }
  17028. UETable.prototype = {
  17029. getMaxRows: function () {
  17030. /**
  17031. * 0428
  17032. * fix:处理异常
  17033. */
  17034. if (!this.table.rows || this.table.rows.length <= 0) return maxLen;
  17035. var rows = this.table.rows, maxLen = 1;
  17036. for (var i = 0, row; row = rows[i]; i++) {
  17037. var currentMax = 1;
  17038. for (var j = 0, cj; cj = row.cells[j++];) {
  17039. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  17040. }
  17041. maxLen = Math.max(currentMax + i, maxLen);
  17042. }
  17043. return maxLen;
  17044. },
  17045. /**
  17046. * 获取当前表格的最大列数
  17047. */
  17048. getMaxCols: function () {
  17049. var rows = this.table.rows, maxLen = 0, cellRows = {};
  17050. /**
  17051. * 0428
  17052. * 处理异常情况
  17053. */
  17054. if (!rows) {
  17055. return
  17056. }
  17057. /******************* */
  17058. for (var i = 0, row; row = rows[i]; i++) {
  17059. var cellsNum = 0;
  17060. for (var j = 0, cj; cj = row.cells[j++];) {
  17061. cellsNum += (cj.colSpan || 1);
  17062. if (cj.rowSpan && cj.rowSpan > 1) {
  17063. for (var k = 1; k < cj.rowSpan; k++) {
  17064. if (!cellRows['row_' + (i + k)]) {
  17065. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  17066. } else {
  17067. cellRows['row_' + (i + k)]++
  17068. }
  17069. }
  17070. }
  17071. }
  17072. cellsNum += cellRows['row_' + i] || 0;
  17073. maxLen = Math.max(cellsNum, maxLen);
  17074. }
  17075. return maxLen;
  17076. },
  17077. getCellColIndex: function(cell) {
  17078. },
  17079. /**
  17080. * 获取当前cell旁边的单元格,
  17081. * @param cell
  17082. * @param right
  17083. */
  17084. getHSideCell: function(cell, right) {
  17085. try {
  17086. var cellInfo = this.getCellInfo(cell),
  17087. previewRowIndex, previewColIndex;
  17088. var len = this.selectedTds.length,
  17089. range = this.cellsRange;
  17090. //首行或者首列没有前置单元格
  17091. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17092. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  17093. previewColIndex = !right ? (!len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17094. : (!len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  17095. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17096. } catch (e) {
  17097. showError(e);
  17098. }
  17099. },
  17100. getTabNextCell: function(cell, preRowIndex) {
  17101. var cellInfo = this.getCellInfo(cell),
  17102. rowIndex = preRowIndex || cellInfo.rowIndex,
  17103. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  17104. nextCell;
  17105. try {
  17106. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  17107. } catch (e) {
  17108. try {
  17109. rowIndex = rowIndex * 1 + 1;
  17110. colIndex = 0;
  17111. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  17112. } catch (e) {
  17113. }
  17114. }
  17115. return nextCell;
  17116. },
  17117. /**
  17118. * 获取视觉上的后置单元格
  17119. * @param cell
  17120. * @param bottom
  17121. */
  17122. getVSideCell: function(cell, bottom, ignoreRange) {
  17123. try {
  17124. var cellInfo = this.getCellInfo(cell),
  17125. nextRowIndex, nextColIndex;
  17126. var len = this.selectedTds.length && !ignoreRange,
  17127. range = this.cellsRange;
  17128. //末行或者末列没有后置单元格
  17129. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  17130. nextRowIndex = !bottom ? (!len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  17131. : (!len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  17132. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  17133. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  17134. } catch (e) {
  17135. showError(e);
  17136. }
  17137. },
  17138. /**
  17139. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  17140. */
  17141. getSameEndPosCells: function (cell, xOrY) {
  17142. try {
  17143. var flag = (xOrY.toLowerCase() === "x"),
  17144. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  17145. rows = this.table.rows,
  17146. cells = null, returns = [];
  17147. for (var i = 0; i < this.rowsNum; i++) {
  17148. cells = rows[i].cells;
  17149. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  17150. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  17151. //对应行的td已经被上面行rowSpan了
  17152. if (tmpEnd > end && flag) break;
  17153. if (cell == tmpCell || end == tmpEnd) {
  17154. //只获取单一的单元格
  17155. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  17156. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  17157. returns.push(tmpCell);
  17158. }
  17159. if (flag) break;
  17160. }
  17161. }
  17162. }
  17163. return returns;
  17164. } catch (e) {
  17165. showError(e);
  17166. }
  17167. },
  17168. setCellContent: function (cell, content) {
  17169. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  17170. },
  17171. cloneCell: UETable.cloneCell,
  17172. /**
  17173. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  17174. */
  17175. getSameStartPosXCells: function (cell) {
  17176. try {
  17177. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  17178. rows = this.table.rows, cells, returns = [];
  17179. for (var i = 0; i < this.rowsNum; i++) {
  17180. cells = rows[i].cells;
  17181. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  17182. var tmpStart = domUtils.getXY(tmpCell).x;
  17183. if (tmpStart > start) break;
  17184. if (tmpStart == start && tmpCell.colSpan == 1) {
  17185. returns.push(tmpCell);
  17186. break;
  17187. }
  17188. }
  17189. }
  17190. return returns;
  17191. } catch (e) {
  17192. showError(e);
  17193. }
  17194. },
  17195. /**
  17196. * 更新table对应的索引表
  17197. */
  17198. update: function (table) {
  17199. this.table = table || this.table;
  17200. this.selectedTds = [];
  17201. this.cellsRange = {};
  17202. this.indexTable = [];
  17203. if (!this.table.rows) return;
  17204. var rows = this.table.rows,
  17205. rowsNum = this.getMaxRows(),
  17206. dNum = rowsNum - rows.length,
  17207. colsNum = this.getMaxCols();
  17208. while (dNum--) {
  17209. this.table.insertRow(rows.length);
  17210. }
  17211. this.rowsNum = rowsNum;
  17212. this.colsNum = colsNum;
  17213. for (var i = 0, len = rows.length; i < len; i++) {
  17214. this.indexTable[i] = new Array(colsNum);
  17215. }
  17216. //填充索引表
  17217. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  17218. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  17219. //修正整行被rowSpan时导致的行数计算错误
  17220. if (cell.rowSpan > rowsNum) {
  17221. cell.rowSpan = rowsNum;
  17222. }
  17223. var colIndex = cellIndex,
  17224. rowSpan = cell.rowSpan || 1,
  17225. colSpan = cell.colSpan || 1;
  17226. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  17227. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  17228. for (var j = 0; j < rowSpan; j++) {
  17229. for (var k = 0; k < colSpan; k++) {
  17230. this.indexTable[rowIndex + j][colIndex + k] = {
  17231. rowIndex: rowIndex,
  17232. cellIndex: cellIndex,
  17233. colIndex: colIndex,
  17234. rowSpan: rowSpan,
  17235. colSpan: colSpan
  17236. }
  17237. }
  17238. }
  17239. }
  17240. }
  17241. //修复残缺td
  17242. for (j = 0; j < rowsNum; j++) {
  17243. for (k = 0; k < colsNum; k++) {
  17244. if (this.indexTable[j][k] === undefined) {
  17245. row = rows[j];
  17246. cell = row.cells[row.cells.length - 1];
  17247. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  17248. this.setCellContent(cell);
  17249. if (cell.colSpan !== 1) cell.colSpan = 1;
  17250. if (cell.rowSpan !== 1) cell.rowSpan = 1;
  17251. row.appendChild(cell);
  17252. this.indexTable[j][k] = {
  17253. rowIndex: j,
  17254. cellIndex: cell.cellIndex,
  17255. colIndex: k,
  17256. rowSpan: 1,
  17257. colSpan: 1
  17258. }
  17259. }
  17260. }
  17261. }
  17262. //当框选后删除行或者列后撤销,需要重建选区。
  17263. var tds = domUtils.getElementsByTagName(this.table, "td"),
  17264. selectTds = [];
  17265. utils.each(tds, function (td) {
  17266. if (domUtils.hasClass(td, "selectTdClass")) {
  17267. selectTds.push(td);
  17268. }
  17269. });
  17270. if (selectTds.length) {
  17271. var start = selectTds[0],
  17272. end = selectTds[selectTds.length - 1],
  17273. startInfo = this.getCellInfo(start),
  17274. endInfo = this.getCellInfo(end);
  17275. this.selectedTds = selectTds;
  17276. this.cellsRange = {
  17277. beginRowIndex: startInfo.rowIndex,
  17278. beginColIndex: startInfo.colIndex,
  17279. endRowIndex: endInfo.rowIndex + endInfo.rowSpan - 1,
  17280. endColIndex: endInfo.colIndex + endInfo.colSpan - 1
  17281. };
  17282. }
  17283. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  17284. if (!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  17285. domUtils.addClass(this.table.rows[0], "firstRow");
  17286. for (var i = 1; i < this.table.rows.length; i++) {
  17287. domUtils.removeClasses(this.table.rows[i], "firstRow");
  17288. }
  17289. }
  17290. },
  17291. /**
  17292. * 获取单元格的索引信息
  17293. */
  17294. getCellInfo: function (cell) {
  17295. if (!cell) return;
  17296. var cellIndex = cell.cellIndex,
  17297. rowIndex = cell.parentNode.rowIndex,
  17298. rowInfo = this.indexTable[rowIndex],
  17299. numCols = this.colsNum;
  17300. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  17301. var cellInfo = rowInfo[colIndex];
  17302. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  17303. return cellInfo;
  17304. }
  17305. }
  17306. },
  17307. /**
  17308. * 根据行列号获取单元格
  17309. */
  17310. getCell: function (rowIndex, cellIndex) {
  17311. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  17312. },
  17313. /**
  17314. * 删除单元格
  17315. */
  17316. deleteCell: function (cell, rowIndex) {
  17317. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  17318. var row = this.table.rows[rowIndex];
  17319. row.deleteCell(cell.cellIndex);
  17320. },
  17321. /**
  17322. * 根据始末两个单元格获取被框选的所有单元格范围
  17323. */
  17324. getCellsRange: function (cellA, cellB) {
  17325. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  17326. var tmpBeginRowIndex = beginRowIndex,
  17327. tmpBeginColIndex = beginColIndex,
  17328. tmpEndRowIndex = endRowIndex,
  17329. tmpEndColIndex = endColIndex,
  17330. cellInfo, colIndex, rowIndex;
  17331. // 通过indexTable检查是否存在超出TableRange上边界的情况
  17332. if (beginRowIndex > 0) {
  17333. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  17334. cellInfo = me.indexTable[beginRowIndex][colIndex];
  17335. rowIndex = cellInfo.rowIndex;
  17336. if (rowIndex < beginRowIndex) {
  17337. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  17338. }
  17339. }
  17340. }
  17341. // 通过indexTable检查是否存在超出TableRange右边界的情况
  17342. if (endColIndex < me.colsNum) {
  17343. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  17344. cellInfo = me.indexTable[rowIndex][endColIndex];
  17345. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  17346. if (colIndex > endColIndex) {
  17347. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  17348. }
  17349. }
  17350. }
  17351. // 检查是否有超出TableRange下边界的情况
  17352. if (endRowIndex < me.rowsNum) {
  17353. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  17354. cellInfo = me.indexTable[endRowIndex][colIndex];
  17355. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  17356. if (rowIndex > endRowIndex) {
  17357. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  17358. }
  17359. }
  17360. }
  17361. // 检查是否有超出TableRange左边界的情况
  17362. if (beginColIndex > 0) {
  17363. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  17364. cellInfo = me.indexTable[rowIndex][beginColIndex];
  17365. colIndex = cellInfo.colIndex;
  17366. if (colIndex < beginColIndex) {
  17367. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  17368. }
  17369. }
  17370. }
  17371. //递归调用直至所有完成所有框选单元格的扩展
  17372. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  17373. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  17374. } else {
  17375. // 不需要扩展TableRange的情况
  17376. return {
  17377. beginRowIndex: beginRowIndex,
  17378. beginColIndex: beginColIndex,
  17379. endRowIndex: endRowIndex,
  17380. endColIndex: endColIndex
  17381. };
  17382. }
  17383. }
  17384. try {
  17385. var me = this,
  17386. cellAInfo = me.getCellInfo(cellA);
  17387. if (cellA === cellB) {
  17388. return {
  17389. beginRowIndex: cellAInfo.rowIndex,
  17390. beginColIndex: cellAInfo.colIndex,
  17391. endRowIndex: cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  17392. endColIndex: cellAInfo.colIndex + cellAInfo.colSpan - 1
  17393. };
  17394. }
  17395. var cellBInfo = me.getCellInfo(cellB);
  17396. // 计算TableRange的四个边
  17397. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  17398. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  17399. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  17400. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  17401. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  17402. } catch (e) {
  17403. //throw e;
  17404. }
  17405. },
  17406. /**
  17407. * 依据cellsRange获取对应的单元格集合
  17408. */
  17409. getCells: function (range) {
  17410. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  17411. this.clearSelected();
  17412. var beginRowIndex = range.beginRowIndex,
  17413. beginColIndex = range.beginColIndex,
  17414. endRowIndex = range.endRowIndex,
  17415. endColIndex = range.endColIndex,
  17416. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  17417. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  17418. for (var j = beginColIndex; j <= endColIndex; j++) {
  17419. cellInfo = this.indexTable[i][j];
  17420. rowIndex = cellInfo.rowIndex;
  17421. colIndex = cellInfo.colIndex;
  17422. // 如果Cells里已经包含了此Cell则跳过
  17423. var key = rowIndex + '|' + colIndex;
  17424. if (tdHash[key]) continue;
  17425. tdHash[key] = 1;
  17426. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  17427. return null;
  17428. }
  17429. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  17430. }
  17431. }
  17432. return returnTds;
  17433. },
  17434. /**
  17435. * 清理已经选中的单元格
  17436. */
  17437. clearSelected: function () {
  17438. UETable.removeSelectedClass(this.selectedTds);
  17439. this.selectedTds = [];
  17440. this.cellsRange = {};
  17441. },
  17442. /**
  17443. * 根据range设置已经选中的单元格
  17444. */
  17445. setSelected: function (range) {
  17446. var cells = this.getCells(range);
  17447. UETable.addSelectedClass(cells);
  17448. this.selectedTds = cells;
  17449. this.cellsRange = range;
  17450. },
  17451. isFullRow: function () {
  17452. var range = this.cellsRange;
  17453. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  17454. },
  17455. isFullCol: function () {
  17456. var range = this.cellsRange,
  17457. table = this.table,
  17458. ths = table.getElementsByTagName("th"),
  17459. rows = range.endRowIndex - range.beginRowIndex + 1;
  17460. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  17461. },
  17462. /**
  17463. * 获取视觉上的前置单元格,默认是左边,top传入时
  17464. * @param cell
  17465. * @param top
  17466. */
  17467. getNextCell: function(cell, bottom, ignoreRange) {
  17468. try {
  17469. var cellInfo = this.getCellInfo(cell),
  17470. nextRowIndex, nextColIndex;
  17471. var len = this.selectedTds.length && !ignoreRange,
  17472. range = this.cellsRange;
  17473. //末行或者末列没有后置单元格
  17474. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  17475. nextRowIndex = !bottom ? (!len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  17476. : (!len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  17477. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  17478. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  17479. } catch (e) {
  17480. showError(e);
  17481. }
  17482. },
  17483. getPreviewCell: function(cell, top) {
  17484. try {
  17485. var cellInfo = this.getCellInfo(cell),
  17486. previewRowIndex, previewColIndex;
  17487. var len = this.selectedTds.length,
  17488. range = this.cellsRange;
  17489. //首行或者首列没有前置单元格
  17490. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17491. previewRowIndex = !top ? (!len ? cellInfo.rowIndex : range.beginRowIndex)
  17492. : (!len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17493. previewColIndex = !top ? (!len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17494. : (!len ? cellInfo.colIndex : range.endColIndex + 1);
  17495. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17496. } catch (e) {
  17497. showError(e);
  17498. }
  17499. },
  17500. /**
  17501. * 移动单元格中的内容
  17502. */
  17503. moveContent: function (cellTo, cellFrom) {
  17504. if (UETable.isEmptyBlock(cellFrom)) return;
  17505. if (UETable.isEmptyBlock(cellTo)) {
  17506. cellTo.innerHTML = cellFrom.innerHTML;
  17507. return;
  17508. }
  17509. var child = cellTo.lastChild;
  17510. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17511. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17512. }
  17513. while (child = cellFrom.firstChild) {
  17514. cellTo.appendChild(child);
  17515. }
  17516. },
  17517. /**
  17518. * 向右合并单元格
  17519. */
  17520. mergeRight: function (cell) {
  17521. var cellInfo = this.getCellInfo(cell),
  17522. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17523. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17524. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17525. //合并
  17526. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17527. //被合并的单元格不应存在宽度属性
  17528. cell.removeAttribute("width");
  17529. //移动内容
  17530. this.moveContent(cell, rightCell);
  17531. //删掉被合并的Cell
  17532. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17533. this.update();
  17534. },
  17535. /**
  17536. * 向下合并单元格
  17537. */
  17538. mergeDown: function (cell) {
  17539. var cellInfo = this.getCellInfo(cell),
  17540. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17541. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17542. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17543. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17544. cell.removeAttribute("height");
  17545. this.moveContent(cell, downCell);
  17546. this.deleteCell(downCell, downCellInfo.rowIndex);
  17547. this.update();
  17548. },
  17549. /**
  17550. * 合并整个range中的内容
  17551. */
  17552. mergeRange: function () {
  17553. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17554. var range = this.cellsRange,
  17555. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17556. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17557. var index = this.indexTable,
  17558. info = this.getCellInfo(leftTopCell);
  17559. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17560. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17561. }
  17562. // 删除剩余的Cells
  17563. var cells = this.getCells(range);
  17564. for (var i = 0, ci; ci = cells[i++];) {
  17565. if (ci !== leftTopCell) {
  17566. this.moveContent(leftTopCell, ci);
  17567. this.deleteCell(ci);
  17568. }
  17569. }
  17570. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17571. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17572. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17573. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17574. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17575. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17576. leftTopCell.colSpan = 1;
  17577. }
  17578. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17579. var rowIndex = leftTopCell.parentNode.rowIndex;
  17580. //解决IE下的表格操作问题
  17581. if (this.table.deleteRow) {
  17582. for (var i = rowIndex + 1, curIndex = rowIndex + 1, len = leftTopCell.rowSpan; i < len; i++) {
  17583. this.table.deleteRow(curIndex);
  17584. }
  17585. } else {
  17586. for (var i = 0, len = leftTopCell.rowSpan - 1; i < len; i++) {
  17587. var row = this.table.rows[rowIndex + 1];
  17588. row.parentNode.removeChild(row);
  17589. }
  17590. }
  17591. leftTopCell.rowSpan = 1;
  17592. }
  17593. this.update();
  17594. },
  17595. /**
  17596. * 插入一行单元格
  17597. */
  17598. insertRow: function(rowIndex, sourceCell) {
  17599. var numCols = this.colsNum,
  17600. table = this.table,
  17601. row = table.insertRow(rowIndex), cell,
  17602. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17603. function replaceTdToTh(colIndex, cell, tableRow) {
  17604. if (colIndex == 0) {
  17605. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17606. th = tr.cells[colIndex];
  17607. if (th.tagName == 'TH') {
  17608. th = cell.ownerDocument.createElement("th");
  17609. th.appendChild(cell.firstChild);
  17610. tableRow.insertBefore(th, cell);
  17611. domUtils.remove(cell)
  17612. }
  17613. } else {
  17614. if (cell.tagName == 'TH') {
  17615. var td = cell.ownerDocument.createElement("td");
  17616. td.appendChild(cell.firstChild);
  17617. tableRow.insertBefore(td, cell);
  17618. domUtils.remove(cell)
  17619. }
  17620. }
  17621. }
  17622. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17623. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17624. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17625. cell = this.cloneCell(sourceCell, true);
  17626. this.setCellContent(cell);
  17627. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17628. row.appendChild(cell);
  17629. if (!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17630. }
  17631. } else {
  17632. var infoRow = this.indexTable[rowIndex],
  17633. cellIndex = 0;
  17634. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17635. var cellInfo = infoRow[colIndex];
  17636. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17637. if (cellInfo.rowIndex < rowIndex) {
  17638. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17639. cell.rowSpan = cellInfo.rowSpan + 1;
  17640. } else {
  17641. cell = this.cloneCell(sourceCell, true);
  17642. this.setCellContent(cell);
  17643. row.appendChild(cell);
  17644. }
  17645. if (!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17646. }
  17647. }
  17648. //框选时插入不触发contentchange,需要手动更新索引。
  17649. this.update();
  17650. return row;
  17651. },
  17652. /**
  17653. * 删除一行单元格
  17654. * @param rowIndex
  17655. */
  17656. deleteRow: function (rowIndex) {
  17657. var row = this.table.rows[rowIndex],
  17658. infoRow = this.indexTable[rowIndex],
  17659. colsNum = this.colsNum,
  17660. count = 0; //处理计数
  17661. for (var colIndex = 0; colIndex < colsNum;) {
  17662. var cellInfo = infoRow[colIndex],
  17663. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17664. if (cell.rowSpan > 1) {
  17665. if (cellInfo.rowIndex == rowIndex) {
  17666. var clone = cell.cloneNode(true);
  17667. clone.rowSpan = cell.rowSpan - 1;
  17668. clone.innerHTML = "";
  17669. cell.rowSpan = 1;
  17670. var nextRowIndex = rowIndex + 1,
  17671. nextRow = this.table.rows[nextRowIndex],
  17672. insertCellIndex,
  17673. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17674. if (preMerged < colIndex) {
  17675. insertCellIndex = colIndex - preMerged - 1;
  17676. //nextRow.insertCell(insertCellIndex);
  17677. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17678. } else {
  17679. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17680. }
  17681. count += 1;
  17682. //cell.parentNode.removeChild(cell);
  17683. }
  17684. }
  17685. colIndex += cell.colSpan || 1;
  17686. }
  17687. var deleteTds = [], cacheMap = {};
  17688. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17689. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17690. tmpCellIndex = infoRow[colIndex].cellIndex,
  17691. key = tmpRowIndex + "_" + tmpCellIndex;
  17692. if (cacheMap[key]) continue;
  17693. cacheMap[key] = 1;
  17694. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17695. deleteTds.push(cell);
  17696. }
  17697. var mergeTds = [];
  17698. utils.each(deleteTds, function (td) {
  17699. if (td.rowSpan == 1) {
  17700. td.parentNode.removeChild(td);
  17701. } else {
  17702. mergeTds.push(td);
  17703. }
  17704. });
  17705. utils.each(mergeTds, function (td) {
  17706. td.rowSpan--;
  17707. });
  17708. row.parentNode.removeChild(row);
  17709. //浏览器方法本身存在bug,采用自定义方法删除
  17710. //this.table.deleteRow(rowIndex);
  17711. this.update();
  17712. },
  17713. insertCol: function (colIndex, sourceCell, defaultValue) {
  17714. var rowsNum = this.rowsNum,
  17715. rowIndex = 0,
  17716. tableRow, cell,
  17717. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17718. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17719. function replaceTdToTh(rowIndex, cell, tableRow) {
  17720. if (rowIndex == 0) {
  17721. var th = cell.nextSibling || cell.previousSibling;
  17722. if (th.tagName == 'TH') {
  17723. th = cell.ownerDocument.createElement("th");
  17724. th.appendChild(cell.firstChild);
  17725. tableRow.insertBefore(th, cell);
  17726. domUtils.remove(cell)
  17727. }
  17728. } else {
  17729. if (cell.tagName == 'TH') {
  17730. var td = cell.ownerDocument.createElement("td");
  17731. td.appendChild(cell.firstChild);
  17732. tableRow.insertBefore(td, cell);
  17733. domUtils.remove(cell)
  17734. }
  17735. }
  17736. }
  17737. var preCell;
  17738. if (colIndex == 0 || colIndex == this.colsNum) {
  17739. for (; rowIndex < rowsNum; rowIndex++) {
  17740. tableRow = this.table.rows[rowIndex];
  17741. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17742. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17743. this.setCellContent(cell);
  17744. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17745. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17746. if (!colIndex) {
  17747. tableRow.insertBefore(cell, tableRow.cells[0]);
  17748. } else {
  17749. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17750. }
  17751. if (!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17752. }
  17753. } else {
  17754. for (; rowIndex < rowsNum; rowIndex++) {
  17755. var cellInfo = this.indexTable[rowIndex][colIndex];
  17756. if (cellInfo.colIndex < colIndex) {
  17757. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17758. cell.colSpan = cellInfo.colSpan + 1;
  17759. } else {
  17760. tableRow = this.table.rows[rowIndex];
  17761. preCell = tableRow.cells[cellInfo.cellIndex];
  17762. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17763. this.setCellContent(cell);
  17764. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17765. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17766. //防止IE下报错
  17767. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17768. }
  17769. if (!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17770. }
  17771. }
  17772. //框选时插入不触发contentchange,需要手动更新索引
  17773. this.update();
  17774. this.updateWidth(backWidth, defaultValue || {tdPadding: 10, tdBorder: 1});
  17775. },
  17776. updateWidth: function (width, defaultValue) {
  17777. var table = this.table,
  17778. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17779. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17780. table.setAttribute("width", tmpWidth);
  17781. return;
  17782. }
  17783. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17784. utils.each(tds, function (td) {
  17785. td.setAttribute("width", width);
  17786. })
  17787. },
  17788. deleteCol: function (colIndex) {
  17789. var indexTable = this.indexTable,
  17790. tableRows = this.table.rows,
  17791. backTableWidth = this.table.getAttribute("width"),
  17792. backTdWidth = 0,
  17793. rowsNum = this.rowsNum,
  17794. cacheMap = {};
  17795. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17796. var infoRow = indexTable[rowIndex],
  17797. cellInfo = infoRow[colIndex],
  17798. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17799. // 跳过已经处理过的Cell
  17800. if (cacheMap[key]) continue;
  17801. cacheMap[key] = 1;
  17802. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17803. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17804. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17805. if (cell.colSpan > 1) {
  17806. cell.colSpan--;
  17807. } else {
  17808. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17809. }
  17810. rowIndex += cellInfo.rowSpan || 1;
  17811. }
  17812. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17813. this.update();
  17814. },
  17815. splitToCells: function (cell) {
  17816. var me = this,
  17817. cells = this.splitToRows(cell);
  17818. utils.each(cells, function (cell) {
  17819. me.splitToCols(cell);
  17820. })
  17821. },
  17822. splitToRows: function (cell) {
  17823. var cellInfo = this.getCellInfo(cell),
  17824. rowIndex = cellInfo.rowIndex,
  17825. colIndex = cellInfo.colIndex,
  17826. results = [];
  17827. // 修改Cell的rowSpan
  17828. cell.rowSpan = 1;
  17829. results.push(cell);
  17830. // 补齐单元格
  17831. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17832. if (i == rowIndex) continue;
  17833. var tableRow = this.table.rows[i],
  17834. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17835. tmpCell.colSpan = cellInfo.colSpan;
  17836. this.setCellContent(tmpCell);
  17837. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17838. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17839. if (cell.style.cssText) {
  17840. tmpCell.style.cssText = cell.style.cssText;
  17841. }
  17842. results.push(tmpCell);
  17843. }
  17844. this.update();
  17845. return results;
  17846. },
  17847. getPreviewMergedCellsNum: function (rowIndex, colIndex) {
  17848. var indexRow = this.indexTable[rowIndex],
  17849. num = 0;
  17850. for (var i = 0; i < colIndex;) {
  17851. var colSpan = indexRow[i].colSpan,
  17852. tmpRowIndex = indexRow[i].rowIndex;
  17853. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17854. i += colSpan;
  17855. }
  17856. return num;
  17857. },
  17858. splitToCols: function (cell) {
  17859. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17860. cellInfo = this.getCellInfo(cell),
  17861. rowIndex = cellInfo.rowIndex,
  17862. colIndex = cellInfo.colIndex,
  17863. results = [];
  17864. // 修改Cell的rowSpan
  17865. cell.colSpan = 1;
  17866. cell.setAttribute("width", backWidth);
  17867. results.push(cell);
  17868. // 补齐单元格
  17869. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17870. if (j == colIndex) continue;
  17871. var tableRow = this.table.rows[rowIndex],
  17872. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17873. tmpCell.rowSpan = cellInfo.rowSpan;
  17874. this.setCellContent(tmpCell);
  17875. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17876. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17877. tmpCell.setAttribute('width', backWidth);
  17878. if (cell.style.cssText) {
  17879. tmpCell.style.cssText = cell.style.cssText;
  17880. }
  17881. //处理th的情况
  17882. if (cell.tagName == 'TH') {
  17883. var th = cell.ownerDocument.createElement('th');
  17884. th.appendChild(tmpCell.firstChild);
  17885. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17886. th.rowSpan = tmpCell.rowSpan;
  17887. tableRow.insertBefore(th, tmpCell);
  17888. domUtils.remove(tmpCell);
  17889. }
  17890. results.push(tmpCell);
  17891. }
  17892. this.update();
  17893. return results;
  17894. },
  17895. isLastCell: function (cell, rowsNum, colsNum) {
  17896. rowsNum = rowsNum || this.rowsNum;
  17897. colsNum = colsNum || this.colsNum;
  17898. var cellInfo = this.getCellInfo(cell);
  17899. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17900. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17901. },
  17902. getLastCell: function (cells) {
  17903. cells = cells || this.table.getElementsByTagName("td");
  17904. var firstInfo = this.getCellInfo(cells[0]);
  17905. var me = this, last = cells[0],
  17906. tr = last.parentNode,
  17907. cellsNum = 0, cols = 0, rows;
  17908. utils.each(cells, function (cell) {
  17909. if (cell.parentNode == tr) cols += cell.colSpan || 1;
  17910. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17911. });
  17912. rows = cellsNum / cols;
  17913. utils.each(cells, function (cell) {
  17914. if (me.isLastCell(cell, rows, cols)) {
  17915. last = cell;
  17916. return false;
  17917. }
  17918. });
  17919. return last;
  17920. },
  17921. selectRow: function (rowIndex) {
  17922. var indexRow = this.indexTable[rowIndex],
  17923. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17924. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17925. range = this.getCellsRange(start, end);
  17926. this.setSelected(range);
  17927. },
  17928. selectTable: function () {
  17929. var tds = this.table.getElementsByTagName("td"),
  17930. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17931. this.setSelected(range);
  17932. },
  17933. setBackground: function (cells, value) {
  17934. if (typeof value === "string") {
  17935. utils.each(cells, function (cell) {
  17936. cell.style.backgroundColor = value;
  17937. })
  17938. } else if (typeof value === "object") {
  17939. value = utils.extend({
  17940. repeat: true,
  17941. colorList: ["#ddd", "#fff"]
  17942. }, value);
  17943. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17944. count = 0,
  17945. colors = value.colorList,
  17946. getColor = function (list, index, repeat) {
  17947. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17948. };
  17949. for (var i = 0, cell; cell = cells[i++];) {
  17950. var cellInfo = this.getCellInfo(cell);
  17951. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17952. }
  17953. }
  17954. },
  17955. removeBackground: function (cells) {
  17956. utils.each(cells, function (cell) {
  17957. cell.style.backgroundColor = "";
  17958. })
  17959. }
  17960. };
  17961. function showError(e) {
  17962. }
  17963. })();
  17964. // plugins/table.cmds.js
  17965. /**
  17966. * Created with JetBrains PhpStorm.
  17967. * User: taoqili
  17968. * Date: 13-2-20
  17969. * Time: 下午6:25
  17970. * To change this template use File | Settings | File Templates.
  17971. */
  17972. ;
  17973. (function () {
  17974. var UT = UE.UETable,
  17975. getTableItemsByRange = function (editor) {
  17976. return UT.getTableItemsByRange(editor);
  17977. },
  17978. getUETableBySelected = function (editor) {
  17979. return UT.getUETableBySelected(editor)
  17980. },
  17981. getDefaultValue = function (editor, table) {
  17982. return UT.getDefaultValue(editor, table);
  17983. },
  17984. getUETable = function (tdOrTable) {
  17985. return UT.getUETable(tdOrTable);
  17986. };
  17987. UE.commands['inserttable'] = {
  17988. queryCommandState: function () {
  17989. return getTableItemsByRange(this).table ? -1 : 0;
  17990. },
  17991. execCommand: function (cmd, opt) {
  17992. function createTable(opt, tdWidth) {
  17993. var html = [],
  17994. rowsNum = opt.numRows,
  17995. colsNum = opt.numCols;
  17996. for (var r = 0; r < rowsNum; r++) {
  17997. html.push('<tr' + (r == 0 ? ' class="firstRow"' : '') + '>');
  17998. for (var c = 0; c < colsNum; c++) {
  17999. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  18000. }
  18001. html.push('</tr>')
  18002. }
  18003. //禁止指定table-width
  18004. return '<table><tbody>' + html.join('') + '</tbody></table>'
  18005. }
  18006. if (!opt) {
  18007. opt = utils.extend({}, {
  18008. numCols: this.options.defaultCols,
  18009. numRows: this.options.defaultRows,
  18010. tdvalign: this.options.tdvalign
  18011. })
  18012. }
  18013. var me = this;
  18014. var range = this.selection.getRange(),
  18015. start = range.startContainer,
  18016. firstParentBlock = domUtils.findParent(start, function (node) {
  18017. return domUtils.isBlockElm(node);
  18018. }, true) || me.body;
  18019. var defaultValue = getDefaultValue(me),
  18020. tableWidth = firstParentBlock.offsetWidth,
  18021. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  18022. //todo其他属性
  18023. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  18024. me.execCommand("inserthtml", createTable(opt, tdWidth));
  18025. }
  18026. };
  18027. UE.commands['insertparagraphbeforetable'] = {
  18028. queryCommandState: function () {
  18029. return getTableItemsByRange(this).cell ? 0 : -1;
  18030. },
  18031. execCommand: function () {
  18032. var table = getTableItemsByRange(this).table;
  18033. if (table) {
  18034. var p = this.document.createElement("p");
  18035. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  18036. table.parentNode.insertBefore(p, table);
  18037. this.selection.getRange().setStart(p, 0).setCursor();
  18038. }
  18039. }
  18040. };
  18041. UE.commands['deletetable'] = {
  18042. queryCommandState: function () {
  18043. var rng = this.selection.getRange();
  18044. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  18045. },
  18046. execCommand: function (cmd, table) {
  18047. var rng = this.selection.getRange();
  18048. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  18049. if (table) {
  18050. var next = table.nextSibling;
  18051. if (!next) {
  18052. next = domUtils.createElement(this.document, 'p', {
  18053. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  18054. });
  18055. table.parentNode.insertBefore(next, table);
  18056. }
  18057. domUtils.remove(table);
  18058. rng = this.selection.getRange();
  18059. if (next.nodeType == 3) {
  18060. rng.setStartBefore(next)
  18061. } else {
  18062. rng.setStart(next, 0)
  18063. }
  18064. rng.setCursor(false, true)
  18065. this.fireEvent("tablehasdeleted")
  18066. }
  18067. }
  18068. };
  18069. UE.commands['cellalign'] = {
  18070. queryCommandState: function () {
  18071. return getSelectedArr(this).length ? 0 : -1
  18072. },
  18073. execCommand: function (cmd, align) {
  18074. var selectedTds = getSelectedArr(this);
  18075. if (selectedTds.length) {
  18076. for (var i = 0, ci; ci = selectedTds[i++];) {
  18077. ci.setAttribute('align', align);
  18078. }
  18079. }
  18080. }
  18081. };
  18082. UE.commands['cellvalign'] = {
  18083. queryCommandState: function () {
  18084. return getSelectedArr(this).length ? 0 : -1;
  18085. },
  18086. execCommand: function (cmd, valign) {
  18087. var selectedTds = getSelectedArr(this);
  18088. if (selectedTds.length) {
  18089. for (var i = 0, ci; ci = selectedTds[i++];) {
  18090. ci.setAttribute('vAlign', valign);
  18091. }
  18092. }
  18093. }
  18094. };
  18095. UE.commands['insertcaption'] = {
  18096. queryCommandState: function () {
  18097. var table = getTableItemsByRange(this).table;
  18098. if (table) {
  18099. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  18100. }
  18101. return -1;
  18102. },
  18103. execCommand: function () {
  18104. var table = getTableItemsByRange(this).table;
  18105. if (table) {
  18106. var caption = this.document.createElement('caption');
  18107. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  18108. table.insertBefore(caption, table.firstChild);
  18109. var range = this.selection.getRange();
  18110. range.setStart(caption, 0).setCursor();
  18111. }
  18112. }
  18113. };
  18114. UE.commands['deletecaption'] = {
  18115. queryCommandState: function () {
  18116. var rng = this.selection.getRange(),
  18117. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18118. if (table) {
  18119. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  18120. }
  18121. return -1;
  18122. },
  18123. execCommand: function () {
  18124. var rng = this.selection.getRange(),
  18125. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18126. if (table) {
  18127. domUtils.remove(table.getElementsByTagName('caption')[0]);
  18128. var range = this.selection.getRange();
  18129. range.setStart(table.rows[0].cells[0], 0).setCursor();
  18130. }
  18131. }
  18132. };
  18133. UE.commands['inserttitle'] = {
  18134. queryCommandState: function () {
  18135. var table = getTableItemsByRange(this).table;
  18136. if (table) {
  18137. var firstRow = table.rows[0];
  18138. return firstRow.cells[firstRow.cells.length - 1].tagName.toLowerCase() != 'th' ? 0 : -1
  18139. }
  18140. return -1;
  18141. },
  18142. execCommand: function () {
  18143. var table = getTableItemsByRange(this).table;
  18144. if (table) {
  18145. getUETable(table).insertRow(0, 'th');
  18146. }
  18147. var th = table.getElementsByTagName('th')[0];
  18148. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  18149. }
  18150. };
  18151. UE.commands['deletetitle'] = {
  18152. queryCommandState: function () {
  18153. var table = getTableItemsByRange(this).table;
  18154. if (table) {
  18155. var firstRow = table.rows[0];
  18156. return firstRow.cells[firstRow.cells.length - 1].tagName.toLowerCase() == 'th' ? 0 : -1
  18157. }
  18158. return -1;
  18159. },
  18160. execCommand: function () {
  18161. var table = getTableItemsByRange(this).table;
  18162. if (table) {
  18163. domUtils.remove(table.rows[0])
  18164. }
  18165. var td = table.getElementsByTagName('td')[0];
  18166. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  18167. }
  18168. };
  18169. UE.commands['inserttitlecol'] = {
  18170. queryCommandState: function () {
  18171. var table = getTableItemsByRange(this).table;
  18172. if (table) {
  18173. var lastRow = table.rows[table.rows.length - 1];
  18174. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  18175. }
  18176. return -1;
  18177. },
  18178. execCommand: function (cmd) {
  18179. var table = getTableItemsByRange(this).table;
  18180. if (table) {
  18181. getUETable(table).insertCol(0, 'th');
  18182. }
  18183. resetTdWidth(table, this);
  18184. var th = table.getElementsByTagName('th')[0];
  18185. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  18186. }
  18187. };
  18188. UE.commands['deletetitlecol'] = {
  18189. queryCommandState: function () {
  18190. var table = getTableItemsByRange(this).table;
  18191. if (table) {
  18192. var lastRow = table.rows[table.rows.length - 1];
  18193. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  18194. }
  18195. return -1;
  18196. },
  18197. execCommand: function () {
  18198. var table = getTableItemsByRange(this).table;
  18199. if (table) {
  18200. for (var i = 0; i < table.rows.length; i++) {
  18201. domUtils.remove(table.rows[i].children[0])
  18202. }
  18203. }
  18204. resetTdWidth(table, this);
  18205. var td = table.getElementsByTagName('td')[0];
  18206. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  18207. }
  18208. };
  18209. UE.commands["mergeright"] = {
  18210. queryCommandState: function (cmd) {
  18211. var tableItems = getTableItemsByRange(this),
  18212. table = tableItems.table,
  18213. cell = tableItems.cell;
  18214. if (!table || !cell) return -1;
  18215. var ut = getUETable(table);
  18216. if (ut.selectedTds.length) return -1;
  18217. var cellInfo = ut.getCellInfo(cell),
  18218. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  18219. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  18220. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  18221. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  18222. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  18223. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  18224. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  18225. },
  18226. execCommand: function (cmd) {
  18227. var rng = this.selection.getRange(),
  18228. bk = rng.createBookmark(true);
  18229. var cell = getTableItemsByRange(this).cell,
  18230. ut = getUETable(cell);
  18231. ut.mergeRight(cell);
  18232. rng.moveToBookmark(bk).select();
  18233. }
  18234. };
  18235. UE.commands["mergedown"] = {
  18236. queryCommandState: function (cmd) {
  18237. var tableItems = getTableItemsByRange(this),
  18238. table = tableItems.table,
  18239. cell = tableItems.cell;
  18240. if (!table || !cell) return -1;
  18241. var ut = getUETable(table);
  18242. if (ut.selectedTds.length) return -1;
  18243. var cellInfo = ut.getCellInfo(cell),
  18244. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  18245. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  18246. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  18247. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  18248. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  18249. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  18250. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  18251. },
  18252. execCommand: function () {
  18253. var rng = this.selection.getRange(),
  18254. bk = rng.createBookmark(true);
  18255. var cell = getTableItemsByRange(this).cell,
  18256. ut = getUETable(cell);
  18257. ut.mergeDown(cell);
  18258. rng.moveToBookmark(bk).select();
  18259. }
  18260. };
  18261. UE.commands["mergecells"] = {
  18262. queryCommandState: function () {
  18263. return getUETableBySelected(this) ? 0 : -1;
  18264. },
  18265. execCommand: function () {
  18266. var ut = getUETableBySelected(this);
  18267. if (ut && ut.selectedTds.length) {
  18268. var cell = ut.selectedTds[0];
  18269. ut.mergeRange();
  18270. var rng = this.selection.getRange();
  18271. if (domUtils.isEmptyBlock(cell)) {
  18272. rng.setStart(cell, 0).collapse(true)
  18273. } else {
  18274. rng.selectNodeContents(cell)
  18275. }
  18276. rng.select();
  18277. }
  18278. }
  18279. };
  18280. UE.commands["insertrow"] = {
  18281. queryCommandState: function () {
  18282. var tableItems = getTableItemsByRange(this),
  18283. cell = tableItems.cell;
  18284. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  18285. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  18286. },
  18287. execCommand: function () {
  18288. var rng = this.selection.getRange(),
  18289. bk = rng.createBookmark(true);
  18290. var tableItems = getTableItemsByRange(this),
  18291. cell = tableItems.cell,
  18292. table = tableItems.table,
  18293. ut = getUETable(table),
  18294. cellInfo = ut.getCellInfo(cell);
  18295. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  18296. if (!ut.selectedTds.length) {
  18297. ut.insertRow(cellInfo.rowIndex, cell);
  18298. } else {
  18299. var range = ut.cellsRange;
  18300. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  18301. ut.insertRow(range.beginRowIndex, cell);
  18302. }
  18303. }
  18304. rng.moveToBookmark(bk).select();
  18305. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  18306. }
  18307. };
  18308. //后插入行
  18309. UE.commands["insertrownext"] = {
  18310. queryCommandState: function () {
  18311. var tableItems = getTableItemsByRange(this),
  18312. cell = tableItems.cell;
  18313. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  18314. },
  18315. execCommand: function () {
  18316. var rng = this.selection.getRange(),
  18317. bk = rng.createBookmark(true);
  18318. var tableItems = getTableItemsByRange(this),
  18319. cell = tableItems.cell,
  18320. table = tableItems.table,
  18321. ut = getUETable(table),
  18322. cellInfo = ut.getCellInfo(cell);
  18323. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  18324. if (!ut.selectedTds.length) {
  18325. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  18326. } else {
  18327. var range = ut.cellsRange;
  18328. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  18329. ut.insertRow(range.endRowIndex + 1, cell);
  18330. }
  18331. }
  18332. rng.moveToBookmark(bk).select();
  18333. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  18334. }
  18335. };
  18336. UE.commands["deleterow"] = {
  18337. queryCommandState: function () {
  18338. var tableItems = getTableItemsByRange(this);
  18339. return tableItems.cell ? 0 : -1;
  18340. },
  18341. execCommand: function () {
  18342. var cell = getTableItemsByRange(this).cell,
  18343. ut = getUETable(cell),
  18344. cellsRange = ut.cellsRange,
  18345. cellInfo = ut.getCellInfo(cell),
  18346. preCell = ut.getVSideCell(cell),
  18347. nextCell = ut.getVSideCell(cell, true),
  18348. rng = this.selection.getRange();
  18349. if (utils.isEmptyObject(cellsRange)) {
  18350. ut.deleteRow(cellInfo.rowIndex);
  18351. } else {
  18352. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  18353. ut.deleteRow(cellsRange.beginRowIndex);
  18354. }
  18355. }
  18356. var table = ut.table;
  18357. if (!table.getElementsByTagName('td').length) {
  18358. var nextSibling = table.nextSibling;
  18359. domUtils.remove(table);
  18360. if (nextSibling) {
  18361. rng.setStart(nextSibling, 0).setCursor(false, true);
  18362. }
  18363. } else {
  18364. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  18365. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  18366. } else {
  18367. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  18368. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  18369. }
  18370. }
  18371. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  18372. }
  18373. };
  18374. UE.commands["insertcol"] = {
  18375. queryCommandState: function (cmd) {
  18376. var tableItems = getTableItemsByRange(this),
  18377. cell = tableItems.cell;
  18378. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  18379. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  18380. },
  18381. execCommand: function (cmd) {
  18382. var rng = this.selection.getRange(),
  18383. bk = rng.createBookmark(true);
  18384. if (this.queryCommandState(cmd) == -1) return;
  18385. var cell = getTableItemsByRange(this).cell,
  18386. ut = getUETable(cell),
  18387. cellInfo = ut.getCellInfo(cell);
  18388. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  18389. if (!ut.selectedTds.length) {
  18390. ut.insertCol(cellInfo.colIndex, cell);
  18391. } else {
  18392. var range = ut.cellsRange;
  18393. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  18394. ut.insertCol(range.beginColIndex, cell);
  18395. }
  18396. }
  18397. rng.moveToBookmark(bk).select(true);
  18398. }
  18399. };
  18400. UE.commands["insertcolnext"] = {
  18401. queryCommandState: function () {
  18402. var tableItems = getTableItemsByRange(this),
  18403. cell = tableItems.cell;
  18404. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  18405. },
  18406. execCommand: function () {
  18407. var rng = this.selection.getRange(),
  18408. bk = rng.createBookmark(true);
  18409. var cell = getTableItemsByRange(this).cell,
  18410. ut = getUETable(cell),
  18411. cellInfo = ut.getCellInfo(cell);
  18412. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  18413. if (!ut.selectedTds.length) {
  18414. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  18415. } else {
  18416. var range = ut.cellsRange;
  18417. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  18418. ut.insertCol(range.endColIndex + 1, cell);
  18419. }
  18420. }
  18421. rng.moveToBookmark(bk).select();
  18422. }
  18423. };
  18424. UE.commands["deletecol"] = {
  18425. queryCommandState: function () {
  18426. var tableItems = getTableItemsByRange(this);
  18427. return tableItems.cell ? 0 : -1;
  18428. },
  18429. execCommand: function () {
  18430. var cell = getTableItemsByRange(this).cell,
  18431. ut = getUETable(cell),
  18432. range = ut.cellsRange,
  18433. cellInfo = ut.getCellInfo(cell),
  18434. preCell = ut.getHSideCell(cell),
  18435. nextCell = ut.getHSideCell(cell, true);
  18436. if (utils.isEmptyObject(range)) {
  18437. ut.deleteCol(cellInfo.colIndex);
  18438. } else {
  18439. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  18440. ut.deleteCol(range.beginColIndex);
  18441. }
  18442. }
  18443. var table = ut.table,
  18444. rng = this.selection.getRange();
  18445. if (!table.getElementsByTagName('td').length) {
  18446. var nextSibling = table.nextSibling;
  18447. domUtils.remove(table);
  18448. if (nextSibling) {
  18449. rng.setStart(nextSibling, 0).setCursor(false, true);
  18450. }
  18451. } else {
  18452. if (domUtils.inDoc(cell, this.document)) {
  18453. rng.setStart(cell, 0).setCursor(false, true);
  18454. } else {
  18455. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  18456. rng.selectNodeContents(nextCell).setCursor(false, true);
  18457. } else {
  18458. if (preCell && domUtils.inDoc(preCell, this.document)) {
  18459. rng.selectNodeContents(preCell).setCursor(true, true);
  18460. }
  18461. }
  18462. }
  18463. }
  18464. }
  18465. };
  18466. UE.commands["splittocells"] = {
  18467. queryCommandState: function () {
  18468. var tableItems = getTableItemsByRange(this),
  18469. cell = tableItems.cell;
  18470. if (!cell) return -1;
  18471. var ut = getUETable(tableItems.table);
  18472. if (ut.selectedTds.length > 0) return -1;
  18473. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  18474. },
  18475. execCommand: function () {
  18476. var rng = this.selection.getRange(),
  18477. bk = rng.createBookmark(true);
  18478. var cell = getTableItemsByRange(this).cell,
  18479. ut = getUETable(cell);
  18480. ut.splitToCells(cell);
  18481. rng.moveToBookmark(bk).select();
  18482. }
  18483. };
  18484. UE.commands["splittorows"] = {
  18485. queryCommandState: function () {
  18486. var tableItems = getTableItemsByRange(this),
  18487. cell = tableItems.cell;
  18488. if (!cell) return -1;
  18489. var ut = getUETable(tableItems.table);
  18490. if (ut.selectedTds.length > 0) return -1;
  18491. return cell && cell.rowSpan > 1 ? 0 : -1;
  18492. },
  18493. execCommand: function () {
  18494. var rng = this.selection.getRange(),
  18495. bk = rng.createBookmark(true);
  18496. var cell = getTableItemsByRange(this).cell,
  18497. ut = getUETable(cell);
  18498. ut.splitToRows(cell);
  18499. rng.moveToBookmark(bk).select();
  18500. }
  18501. };
  18502. UE.commands["splittocols"] = {
  18503. queryCommandState: function () {
  18504. var tableItems = getTableItemsByRange(this),
  18505. cell = tableItems.cell;
  18506. if (!cell) return -1;
  18507. var ut = getUETable(tableItems.table);
  18508. if (ut.selectedTds.length > 0) return -1;
  18509. return cell && cell.colSpan > 1 ? 0 : -1;
  18510. },
  18511. execCommand: function () {
  18512. var rng = this.selection.getRange(),
  18513. bk = rng.createBookmark(true);
  18514. var cell = getTableItemsByRange(this).cell,
  18515. ut = getUETable(cell);
  18516. ut.splitToCols(cell);
  18517. rng.moveToBookmark(bk).select();
  18518. }
  18519. };
  18520. UE.commands["adaptbytext"] =
  18521. UE.commands["adaptbywindow"] = {
  18522. queryCommandState: function () {
  18523. return getTableItemsByRange(this).table ? 0 : -1
  18524. },
  18525. execCommand: function (cmd) {
  18526. var tableItems = getTableItemsByRange(this),
  18527. table = tableItems.table;
  18528. if (table) {
  18529. if (cmd == 'adaptbywindow') {
  18530. resetTdWidth(table, this);
  18531. } else {
  18532. var cells = domUtils.getElementsByTagName(table, "td th");
  18533. utils.each(cells, function (cell) {
  18534. cell.removeAttribute("width");
  18535. });
  18536. table.removeAttribute("width");
  18537. }
  18538. }
  18539. }
  18540. };
  18541. //平均分配各列
  18542. UE.commands['averagedistributecol'] = {
  18543. queryCommandState: function() {
  18544. var ut = getUETableBySelected(this);
  18545. if (!ut) return -1;
  18546. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18547. },
  18548. execCommand: function(cmd) {
  18549. var me = this,
  18550. ut = getUETableBySelected(me);
  18551. function getAverageWidth() {
  18552. var tb = ut.table,
  18553. averageWidth, sumWidth = 0, colsNum = 0,
  18554. tbAttr = getDefaultValue(me, tb);
  18555. if (ut.isFullRow()) {
  18556. sumWidth = tb.offsetWidth;
  18557. colsNum = ut.colsNum;
  18558. } else {
  18559. var begin = ut.cellsRange.beginColIndex,
  18560. end = ut.cellsRange.endColIndex,
  18561. node;
  18562. for (var i = begin; i <= end;) {
  18563. node = ut.selectedTds[i];
  18564. sumWidth += node.offsetWidth;
  18565. i += node.colSpan;
  18566. colsNum += 1;
  18567. }
  18568. }
  18569. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18570. return averageWidth;
  18571. }
  18572. function setAverageWidth(averageWidth) {
  18573. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18574. node.setAttribute("width", "");
  18575. });
  18576. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18577. utils.each(cells, function (node) {
  18578. if (node.colSpan == 1) {
  18579. node.setAttribute("width", averageWidth);
  18580. }
  18581. });
  18582. }
  18583. if (ut && ut.selectedTds.length) {
  18584. setAverageWidth(getAverageWidth());
  18585. }
  18586. }
  18587. };
  18588. //平均分配各行
  18589. UE.commands['averagedistributerow'] = {
  18590. queryCommandState: function () {
  18591. var ut = getUETableBySelected(this);
  18592. if (!ut) return -1;
  18593. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18594. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18595. },
  18596. execCommand: function (cmd) {
  18597. var me = this,
  18598. ut = getUETableBySelected(me);
  18599. function getAverageHeight() {
  18600. var averageHeight, rowNum, sumHeight = 0,
  18601. tb = ut.table,
  18602. tbAttr = getDefaultValue(me, tb),
  18603. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18604. if (ut.isFullCol()) {
  18605. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18606. thArr = domUtils.getElementsByTagName(tb, "th"),
  18607. captionHeight, thHeight;
  18608. if (captionArr.length > 0) {
  18609. captionHeight = captionArr[0].offsetHeight;
  18610. }
  18611. if (thArr.length > 0) {
  18612. thHeight = thArr[0].offsetHeight;
  18613. }
  18614. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18615. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18616. } else {
  18617. var begin = ut.cellsRange.beginRowIndex,
  18618. end = ut.cellsRange.endRowIndex,
  18619. count = 0,
  18620. trs = domUtils.getElementsByTagName(tb, "tr");
  18621. for (var i = begin; i <= end; i++) {
  18622. sumHeight += trs[i].offsetHeight;
  18623. count += 1;
  18624. }
  18625. rowNum = count;
  18626. }
  18627. //ie8下是混杂模式
  18628. if (browser.ie && browser.version < 9) {
  18629. averageHeight = Math.ceil(sumHeight / rowNum);
  18630. } else {
  18631. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18632. }
  18633. return averageHeight;
  18634. }
  18635. function setAverageHeight(averageHeight) {
  18636. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18637. utils.each(cells, function (node) {
  18638. if (node.rowSpan == 1) {
  18639. node.setAttribute("height", averageHeight);
  18640. }
  18641. });
  18642. }
  18643. if (ut && ut.selectedTds.length) {
  18644. setAverageHeight(getAverageHeight());
  18645. }
  18646. }
  18647. };
  18648. //单元格对齐方式
  18649. UE.commands['cellalignment'] = {
  18650. queryCommandState: function () {
  18651. return getTableItemsByRange(this).table ? 0 : -1
  18652. },
  18653. execCommand: function (cmd, data) {
  18654. var me = this,
  18655. ut = getUETableBySelected(me);
  18656. if (!ut) {
  18657. var start = me.selection.getStart(),
  18658. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18659. if (!/caption/ig.test(cell.tagName)) {
  18660. domUtils.setAttributes(cell, data);
  18661. } else {
  18662. cell.style.textAlign = data.align;
  18663. cell.style.verticalAlign = data.vAlign;
  18664. }
  18665. me.selection.getRange().setCursor(true);
  18666. } else {
  18667. utils.each(ut.selectedTds, function (cell) {
  18668. domUtils.setAttributes(cell, data);
  18669. });
  18670. }
  18671. },
  18672. /**
  18673. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18674. * @see UE.UETable.getTableCellAlignState
  18675. */
  18676. queryCommandValue: function (cmd) {
  18677. var activeMenuCell = getTableItemsByRange(this).cell;
  18678. if (!activeMenuCell) {
  18679. activeMenuCell = getSelectedArr(this)[0];
  18680. }
  18681. if (!activeMenuCell) {
  18682. return null;
  18683. } else {
  18684. //获取同时选中的其他单元格
  18685. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18686. !cells.length && (cells = activeMenuCell);
  18687. return UE.UETable.getTableCellAlignState(cells);
  18688. }
  18689. }
  18690. };
  18691. //表格对齐方式
  18692. UE.commands['tablealignment'] = {
  18693. queryCommandState: function () {
  18694. if (browser.ie && browser.version < 8) {
  18695. return -1;
  18696. }
  18697. return getTableItemsByRange(this).table ? 0 : -1
  18698. },
  18699. execCommand: function (cmd, value) {
  18700. var me = this,
  18701. start = me.selection.getStart(),
  18702. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18703. if (table) {
  18704. table.setAttribute("align", value);
  18705. }
  18706. }
  18707. };
  18708. //表格属性
  18709. UE.commands['edittable'] = {
  18710. queryCommandState: function () {
  18711. return getTableItemsByRange(this).table ? 0 : -1
  18712. },
  18713. execCommand: function (cmd, color) {
  18714. var rng = this.selection.getRange(),
  18715. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18716. if (table) {
  18717. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18718. domUtils.getElementsByTagName(table, "th"),
  18719. domUtils.getElementsByTagName(table, "caption")
  18720. );
  18721. utils.each(arr, function (node) {
  18722. node.style.borderColor = color;
  18723. });
  18724. }
  18725. }
  18726. };
  18727. //单元格属性
  18728. UE.commands['edittd'] = {
  18729. queryCommandState: function () {
  18730. return getTableItemsByRange(this).table ? 0 : -1
  18731. },
  18732. execCommand: function (cmd, bkColor) {
  18733. var me = this,
  18734. ut = getUETableBySelected(me);
  18735. if (!ut) {
  18736. var start = me.selection.getStart(),
  18737. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18738. if (cell) {
  18739. cell.style.backgroundColor = bkColor;
  18740. }
  18741. } else {
  18742. utils.each(ut.selectedTds, function (cell) {
  18743. cell.style.backgroundColor = bkColor;
  18744. });
  18745. }
  18746. }
  18747. };
  18748. UE.commands["settablebackground"] = {
  18749. queryCommandState: function () {
  18750. return getSelectedArr(this).length > 1 ? 0 : -1;
  18751. },
  18752. execCommand: function (cmd, value) {
  18753. var cells, ut;
  18754. cells = getSelectedArr(this);
  18755. ut = getUETable(cells[0]);
  18756. ut.setBackground(cells, value);
  18757. }
  18758. };
  18759. UE.commands["cleartablebackground"] = {
  18760. queryCommandState: function () {
  18761. var cells = getSelectedArr(this);
  18762. if (!cells.length) return -1;
  18763. for (var i = 0, cell; cell = cells[i++];) {
  18764. if (cell.style.backgroundColor !== "") return 0;
  18765. }
  18766. return -1;
  18767. },
  18768. execCommand: function () {
  18769. var cells = getSelectedArr(this),
  18770. ut = getUETable(cells[0]);
  18771. ut.removeBackground(cells);
  18772. }
  18773. };
  18774. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18775. queryCommandState: function (cmd) {
  18776. var table = getTableItemsByRange(this).table;
  18777. if (!table) return -1;
  18778. var interlaced = table.getAttribute("interlaced");
  18779. if (cmd == "interlacetable") {
  18780. //TODO 待定
  18781. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18782. return (interlaced === "enabled") ? -1 : 0;
  18783. } else {
  18784. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18785. }
  18786. },
  18787. execCommand: function (cmd, classList) {
  18788. var table = getTableItemsByRange(this).table;
  18789. if (cmd == "interlacetable") {
  18790. table.setAttribute("interlaced", "enabled");
  18791. this.fireEvent("interlacetable", table, classList);
  18792. } else {
  18793. table.setAttribute("interlaced", "disabled");
  18794. this.fireEvent("uninterlacetable", table);
  18795. }
  18796. }
  18797. };
  18798. UE.commands["setbordervisible"] = {
  18799. queryCommandState: function (cmd) {
  18800. var table = getTableItemsByRange(this).table;
  18801. if (!table) return -1;
  18802. return 0;
  18803. },
  18804. execCommand: function () {
  18805. var table = getTableItemsByRange(this).table;
  18806. utils.each(domUtils.getElementsByTagName(table, 'td'), function (td) {
  18807. td.style.borderWidth = '1px';
  18808. td.style.borderStyle = 'solid';
  18809. })
  18810. }
  18811. };
  18812. function resetTdWidth(table, editor) {
  18813. var tds = domUtils.getElementsByTagName(table, 'td th');
  18814. utils.each(tds, function (td) {
  18815. td.removeAttribute("width");
  18816. });
  18817. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18818. var tdsWidths = [];
  18819. setTimeout(function () {
  18820. utils.each(tds, function (td) {
  18821. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18822. })
  18823. utils.each(tds, function (td, i) {
  18824. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18825. })
  18826. }, 0);
  18827. }
  18828. function getTableWidth(editor, needIEHack, defaultValue) {
  18829. var body = editor.body;
  18830. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18831. }
  18832. function getSelectedArr(editor) {
  18833. var cell = getTableItemsByRange(editor).cell;
  18834. if (cell) {
  18835. var ut = getUETable(cell);
  18836. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18837. } else {
  18838. return [];
  18839. }
  18840. }
  18841. })();
  18842. // plugins/table.action.js
  18843. /**
  18844. * Created with JetBrains PhpStorm.
  18845. * User: taoqili
  18846. * Date: 12-10-12
  18847. * Time: 上午10:05
  18848. * To change this template use File | Settings | File Templates.
  18849. */
  18850. UE.plugins['table'] = function() {
  18851. var me = this,
  18852. tabTimer = null,
  18853. //拖动计时器
  18854. tableDragTimer = null,
  18855. //双击计时器
  18856. tableResizeTimer = null,
  18857. //单元格最小宽度
  18858. cellMinWidth = 5,
  18859. isInResizeBuffer = false,
  18860. //单元格边框大小
  18861. cellBorderWidth = 5,
  18862. //鼠标偏移距离
  18863. offsetOfTableCell = 10,
  18864. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18865. singleClickState = 0,
  18866. userActionStatus = null,
  18867. //双击允许的时间范围
  18868. dblclickTime = 360,
  18869. UT = UE.UETable,
  18870. getUETable = function(tdOrTable) {
  18871. return UT.getUETable(tdOrTable);
  18872. },
  18873. getUETableBySelected = function(editor) {
  18874. return UT.getUETableBySelected(editor);
  18875. },
  18876. getDefaultValue = function(editor, table) {
  18877. return UT.getDefaultValue(editor, table);
  18878. },
  18879. removeSelectedClass = function(cells) {
  18880. return UT.removeSelectedClass(cells);
  18881. };
  18882. function showError(e) {
  18883. // throw e;
  18884. }
  18885. me.ready(function () {
  18886. var me = this;
  18887. var orgGetText = me.selection.getText;
  18888. me.selection.getText = function () {
  18889. var table = getUETableBySelected(me);
  18890. if (table) {
  18891. var str = '';
  18892. utils.each(table.selectedTds, function (td) {
  18893. str += td[browser.ie ? 'innerText' : 'textContent'];
  18894. })
  18895. return str;
  18896. } else {
  18897. return orgGetText.call(me.selection)
  18898. }
  18899. }
  18900. })
  18901. //处理拖动及框选相关方法
  18902. var startTd = null, //鼠标按下时的锚点td
  18903. currentTd = null, //当前鼠标经过时的td
  18904. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18905. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18906. dragButton = null,
  18907. dragOver = false,
  18908. dragLine = null, //模拟的拖动线
  18909. dragTd = null; //发生拖动的目标td
  18910. /*
  18911. *0428
  18912. *add:添加拖拽线延时器
  18913. * **********************/
  18914. var dragLineShowTimer;
  18915. var dragLineHideTimer;
  18916. /********************* */
  18917. var mousedown = false,
  18918. //todo 判断混乱模式
  18919. needIEHack = true;
  18920. me.setOpt({
  18921. 'maxColNum': 20,
  18922. 'maxRowNum': 100,
  18923. 'defaultCols': 5,
  18924. 'defaultRows': 5,
  18925. 'tdvalign': 'top',
  18926. 'cursorpath': me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18927. 'tableDragable': false,
  18928. 'classList': ["ue-table-interlace-color-single", "ue-table-interlace-color-double"]
  18929. });
  18930. me.getUETable = getUETable;
  18931. var commands = {
  18932. 'deletetable': 1,
  18933. 'inserttable': 1,
  18934. 'cellvalign': 1,
  18935. 'insertcaption': 1,
  18936. 'deletecaption': 1,
  18937. 'inserttitle': 1,
  18938. 'deletetitle': 1,
  18939. "mergeright": 1,
  18940. "mergedown": 1,
  18941. "mergecells": 1,
  18942. "insertrow": 1,
  18943. "insertrownext": 1,
  18944. "deleterow": 1,
  18945. "insertcol": 1,
  18946. "insertcolnext": 1,
  18947. "deletecol": 1,
  18948. "splittocells": 1,
  18949. "splittorows": 1,
  18950. "splittocols": 1,
  18951. "adaptbytext": 1,
  18952. "adaptbywindow": 1,
  18953. "adaptbycustomer": 1,
  18954. "insertparagraph": 1,
  18955. "insertparagraphbeforetable": 1,
  18956. "averagedistributecol": 1,
  18957. "averagedistributerow": 1
  18958. };
  18959. me.ready(function () {
  18960. utils.cssRule('table',
  18961. //选中的td上的样式
  18962. '.selectTdClass{background-color:#edf5fa !important}' +
  18963. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18964. //插入的表格的默认样式
  18965. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18966. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18967. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18968. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18969. 'table tr.firstRow th{border-top-width:2px;}' +
  18970. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18971. 'td p{margin:0;padding:0;}', me.document);
  18972. var tableCopyList, isFullCol, isFullRow;
  18973. //注册del/backspace事件
  18974. me.addListener('keydown', function(cmd, evt) {
  18975. var me = this;
  18976. var keyCode = evt.keyCode || evt.which;
  18977. if (keyCode == 8) {
  18978. var ut = getUETableBySelected(me);
  18979. if (ut && ut.selectedTds.length) {
  18980. if (ut.isFullCol()) {
  18981. me.execCommand('deletecol')
  18982. } else if (ut.isFullRow()) {
  18983. me.execCommand('deleterow')
  18984. } else {
  18985. me.fireEvent('delcells');
  18986. }
  18987. domUtils.preventDefault(evt);
  18988. }
  18989. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18990. range = me.selection.getRange();
  18991. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18992. me.fireEvent('saveScene');
  18993. var table = caption.parentNode;
  18994. domUtils.remove(caption);
  18995. if (table) {
  18996. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18997. }
  18998. me.fireEvent('saveScene');
  18999. }
  19000. }
  19001. if (keyCode == 46) {
  19002. ut = getUETableBySelected(me);
  19003. if (ut) {
  19004. me.fireEvent('saveScene');
  19005. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  19006. domUtils.fillNode(me.document, ci)
  19007. }
  19008. me.fireEvent('saveScene');
  19009. domUtils.preventDefault(evt);
  19010. }
  19011. }
  19012. if (keyCode == 13) {
  19013. var rng = me.selection.getRange(),
  19014. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  19015. if (caption) {
  19016. var table = domUtils.findParentByTagName(caption, 'table');
  19017. if (!rng.collapsed) {
  19018. rng.deleteContents();
  19019. me.fireEvent('saveScene');
  19020. } else {
  19021. if (caption) {
  19022. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  19023. }
  19024. }
  19025. domUtils.preventDefault(evt);
  19026. return;
  19027. }
  19028. if (rng.collapsed) {
  19029. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  19030. if (table) {
  19031. var cell = table.rows[0].cells[0],
  19032. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  19033. preNode = table.previousSibling;
  19034. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE') && domUtils.isStartInblock(rng)) {
  19035. var first = domUtils.findParent(me.selection.getStart(), function (n) {
  19036. return domUtils.isBlockElm(n)
  19037. }, true);
  19038. if (first && (/t(h|d)/i.test(first.tagName) || first === start.firstChild)) {
  19039. me.execCommand('insertparagraphbeforetable');
  19040. domUtils.preventDefault(evt);
  19041. }
  19042. }
  19043. }
  19044. }
  19045. }
  19046. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  19047. tableCopyList = null;
  19048. var ut = getUETableBySelected(me);
  19049. if (ut) {
  19050. var tds = ut.selectedTds;
  19051. isFullCol = ut.isFullCol();
  19052. isFullRow = ut.isFullRow();
  19053. tableCopyList = [
  19054. [ut.cloneCell(tds[0], null, true)]
  19055. ];
  19056. for (var i = 1, ci; ci = tds[i]; i++) {
  19057. if (ci.parentNode !== tds[i - 1].parentNode) {
  19058. tableCopyList.push([ut.cloneCell(ci, null, true)]);
  19059. } else {
  19060. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci, null, true));
  19061. }
  19062. }
  19063. }
  19064. }
  19065. });
  19066. me.addListener("tablehasdeleted", function () {
  19067. toggleDraggableState(this, false, "", null);
  19068. if (dragButton) domUtils.remove(dragButton);
  19069. });
  19070. me.addListener('beforepaste', function (cmd, html) {
  19071. var me = this;
  19072. var rng = me.selection.getRange();
  19073. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  19074. var div = me.document.createElement("div");
  19075. div.innerHTML = html.html;
  19076. //trace:3729
  19077. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  19078. return;
  19079. }
  19080. var table = getUETableBySelected(me);
  19081. if (tableCopyList) {
  19082. me.fireEvent('saveScene');
  19083. var rng = me.selection.getRange();
  19084. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  19085. if (td) {
  19086. var ut = getUETable(td);
  19087. if (isFullRow) {
  19088. var rowIndex = ut.getCellInfo(td).rowIndex;
  19089. if (td.tagName == 'TH') {
  19090. rowIndex++;
  19091. }
  19092. for (var i = 0, ci; ci = tableCopyList[i++];) {
  19093. var tr = ut.insertRow(rowIndex++, "td");
  19094. for (var j = 0, cj; cj = ci[j]; j++) {
  19095. var cell = tr.cells[j];
  19096. if (!cell) {
  19097. cell = tr.insertCell(j)
  19098. }
  19099. cell.innerHTML = cj.innerHTML;
  19100. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  19101. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  19102. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  19103. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  19104. }
  19105. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  19106. if (!ci[j])
  19107. break;
  19108. cj.innerHTML = ci[j].innerHTML;
  19109. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  19110. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  19111. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  19112. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  19113. }
  19114. }
  19115. } else {
  19116. if (isFullCol) {
  19117. cellInfo = ut.getCellInfo(td);
  19118. var maxColNum = 0;
  19119. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  19120. maxColNum += cj.colSpan || 1;
  19121. }
  19122. me.__hasEnterExecCommand = true;
  19123. for (i = 0; i < maxColNum; i++) {
  19124. me.execCommand('insertcol');
  19125. }
  19126. me.__hasEnterExecCommand = false;
  19127. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  19128. if (td.tagName == 'TH') {
  19129. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  19130. }
  19131. }
  19132. for (var i = 0, ci; ci = tableCopyList[i++];) {
  19133. tmpNode = td;
  19134. for (var j = 0, cj; cj = ci[j++];) {
  19135. if (td) {
  19136. td.innerHTML = cj.innerHTML;
  19137. //todo 定制处理
  19138. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  19139. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  19140. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  19141. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  19142. preNode = td;
  19143. td = td.nextSibling;
  19144. } else {
  19145. var cloneTd = cj.cloneNode(true);
  19146. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  19147. preNode.parentNode.appendChild(cloneTd)
  19148. }
  19149. }
  19150. td = ut.getNextCell(tmpNode, true, true);
  19151. if (!tableCopyList[i])
  19152. break;
  19153. if (!td) {
  19154. var cellInfo = ut.getCellInfo(tmpNode);
  19155. ut.table.insertRow(ut.table.rows.length);
  19156. ut.update();
  19157. td = ut.getVSideCell(tmpNode, true);
  19158. }
  19159. }
  19160. }
  19161. ut.update();
  19162. } else {
  19163. table = me.document.createElement('table');
  19164. for (var i = 0, ci; ci = tableCopyList[i++];) {
  19165. var tr = table.insertRow(table.rows.length);
  19166. for (var j = 0, cj; cj = ci[j++];) {
  19167. cloneTd = UT.cloneCell(cj, null, true);
  19168. domUtils.removeAttributes(cloneTd, ['class']);
  19169. tr.appendChild(cloneTd)
  19170. }
  19171. if (j == 2 && cloneTd.rowSpan > 1) {
  19172. cloneTd.rowSpan = 1;
  19173. }
  19174. }
  19175. var defaultValue = getDefaultValue(me),
  19176. width = me.body.offsetWidth -
  19177. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  19178. me.execCommand('insertHTML', '<table ' +
  19179. (isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  19180. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  19181. }
  19182. me.fireEvent('contentchange');
  19183. me.fireEvent('saveScene');
  19184. html.html = '';
  19185. return true;
  19186. } else {
  19187. var div = me.document.createElement("div"), tables;
  19188. div.innerHTML = html.html;
  19189. tables = div.getElementsByTagName("table");
  19190. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  19191. utils.each(tables, function (t) {
  19192. domUtils.remove(t)
  19193. });
  19194. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  19195. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  19196. }
  19197. } else {
  19198. utils.each(tables, function (table) {
  19199. removeStyleSize(table, true);
  19200. domUtils.removeAttributes(table, ['style', 'border']);
  19201. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  19202. if (isEmptyBlock(td)) {
  19203. domUtils.fillNode(me.document, td);
  19204. }
  19205. removeStyleSize(td, true);
  19206. // domUtils.removeAttributes(td, ['style'])
  19207. });
  19208. });
  19209. }
  19210. html.html = div.innerHTML;
  19211. }
  19212. });
  19213. me.addListener('afterpaste', function () {
  19214. var pasteArguments = arguments
  19215. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  19216. /*
  19217. *0428
  19218. *add:取消粘贴后的表格调整大小,改用百分比调整
  19219. **********************************/
  19220. if (pasteArguments && pasteArguments.length == 2 && pasteArguments[0] == 'afterpaste') {
  19221. var html = pasteArguments[1]
  19222. if (html.isOfficeContent && html.officeHtml) {
  19223. if ($(html.html)[0].textContent == $(table)[0].textContent) {
  19224. var firstCell = $(table).find('tbody tr:eq(0) td:eq(0)');
  19225. if (firstCell && firstCell.length > 0) {
  19226. changeColWidth(firstCell[0], 0)
  19227. }
  19228. }
  19229. }
  19230. }
  19231. return
  19232. /*********************************/
  19233. if (table.offsetWidth > me.body.offsetWidth) {
  19234. var defaultValue = getDefaultValue(me, table);
  19235. 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'
  19236. }
  19237. })
  19238. });
  19239. me.addListener('blur', function () {
  19240. tableCopyList = null;
  19241. });
  19242. var timer;
  19243. me.addListener('keydown', function () {
  19244. clearTimeout(timer);
  19245. timer = setTimeout(function () {
  19246. var rng = me.selection.getRange(),
  19247. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  19248. if (cell) {
  19249. var table = cell.parentNode.parentNode.parentNode;
  19250. if (table.offsetWidth > table.getAttribute("width")) {
  19251. cell.style.wordBreak = "break-all";
  19252. }
  19253. }
  19254. }, 100);
  19255. });
  19256. me.addListener("selectionchange", function () {
  19257. toggleDraggableState(me, false, "", null);
  19258. });
  19259. //内容变化时触发索引更新
  19260. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  19261. me.addListener("contentchange", function () {
  19262. var me = this;
  19263. //尽可能排除一些不需要更新的状况
  19264. hideDragLine(me);
  19265. if (getUETableBySelected(me)) return;
  19266. var rng = me.selection.getRange();
  19267. var start = rng.startContainer;
  19268. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  19269. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  19270. if (me.fireEvent("excludetable", table) === true) return;
  19271. table.ueTable = new UT(table);
  19272. //trace:3742
  19273. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  19274. //
  19275. // if (domUtils.isEmptyBlock(td) && td !== start) {
  19276. // domUtils.fillNode(me.document, td);
  19277. // if (browser.ie && browser.version == 6) {
  19278. // td.innerHTML = '&nbsp;'
  19279. // }
  19280. // }
  19281. // });
  19282. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  19283. // if (domUtils.isEmptyBlock(th) && th !== start) {
  19284. // domUtils.fillNode(me.document, th);
  19285. // if (browser.ie && browser.version == 6) {
  19286. // th.innerHTML = '&nbsp;'
  19287. // }
  19288. // }
  19289. // });
  19290. table.onmouseover = function () {
  19291. me.fireEvent('tablemouseover', table);
  19292. };
  19293. table.onmousemove = function () {
  19294. me.fireEvent('tablemousemove', table);
  19295. me.options.tableDragable && toggleDragButton(true, this, me);
  19296. utils.defer(function () {
  19297. me.fireEvent('contentchange', 50)
  19298. }, true)
  19299. };
  19300. table.onmouseout = function () {
  19301. me.fireEvent('tablemouseout', table);
  19302. clearTimeout(dragLineShowTimer)
  19303. dragLineHideTimer = setTimeout(function () {
  19304. toggleDraggableState(me, false, "", null);
  19305. hideDragLine(me);
  19306. }, 10)
  19307. };
  19308. table.onclick = function (evt) {
  19309. evt = me.window.event || evt;
  19310. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19311. if (!target) return;
  19312. var ut = getUETable(target),
  19313. table = ut.table,
  19314. cellInfo = ut.getCellInfo(target),
  19315. cellsRange,
  19316. rng = me.selection.getRange();
  19317. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  19318. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  19319. // ut.setSelected(cellsRange);
  19320. // return;
  19321. // }
  19322. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  19323. //
  19324. // return;
  19325. // }
  19326. if (inTableSide(table, target, evt, true)) {
  19327. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  19328. if (evt.shiftKey && ut.selectedTds.length) {
  19329. if (ut.selectedTds[0] !== endTdCol) {
  19330. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  19331. ut.setSelected(cellsRange);
  19332. } else {
  19333. rng && rng.selectNodeContents(endTdCol).select();
  19334. }
  19335. } else {
  19336. if (target !== endTdCol) {
  19337. cellsRange = ut.getCellsRange(target, endTdCol);
  19338. ut.setSelected(cellsRange);
  19339. } else {
  19340. rng && rng.selectNodeContents(endTdCol).select();
  19341. }
  19342. }
  19343. return;
  19344. }
  19345. if (inTableSide(table, target, evt)) {
  19346. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  19347. if (evt.shiftKey && ut.selectedTds.length) {
  19348. if (ut.selectedTds[0] !== endTdRow) {
  19349. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  19350. ut.setSelected(cellsRange);
  19351. } else {
  19352. rng && rng.selectNodeContents(endTdRow).select();
  19353. }
  19354. } else {
  19355. if (target !== endTdRow) {
  19356. cellsRange = ut.getCellsRange(target, endTdRow);
  19357. ut.setSelected(cellsRange);
  19358. } else {
  19359. rng && rng.selectNodeContents(endTdRow).select();
  19360. }
  19361. }
  19362. }
  19363. };
  19364. });
  19365. switchBorderColor(me, true);
  19366. });
  19367. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  19368. domUtils.on(me.document, "mouseout", function (evt) {
  19369. var target = evt.target || evt.srcElement;
  19370. if (target.tagName == "TABLE") {
  19371. toggleDraggableState(me, false, "", null);
  19372. }
  19373. /*
  19374. *0428
  19375. *add:添加鼠标从拖拽线离开时,延迟消失拖拽线
  19376. ********************************************/
  19377. else if (target.id == 'ue_tableDragLine') {
  19378. clearTimeout(dragLineShowTimer)
  19379. dragLineHideTimer = setTimeout(function () {
  19380. hideDragLine(editor)
  19381. }, 30)
  19382. }
  19383. /*************************************** */
  19384. });
  19385. /**
  19386. * 表格隔行变色
  19387. */
  19388. me.addListener("interlacetable", function (type, table, classList) {
  19389. if (!table) return;
  19390. var me = this,
  19391. rows = table.rows,
  19392. len = rows.length,
  19393. getClass = function (list, index, repeat) {
  19394. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  19395. };
  19396. for (var i = 0; i < len; i++) {
  19397. rows[i].className = getClass(classList || me.options.classList, i, true);
  19398. }
  19399. });
  19400. me.addListener("uninterlacetable", function (type, table) {
  19401. if (!table) return;
  19402. var me = this,
  19403. rows = table.rows,
  19404. classList = me.options.classList,
  19405. len = rows.length;
  19406. for (var i = 0; i < len; i++) {
  19407. domUtils.removeClasses(rows[i], classList);
  19408. }
  19409. });
  19410. me.addListener("mousedown", mouseDownEvent);
  19411. me.addListener("mouseup", mouseUpEvent);
  19412. //拖动的时候触发mouseup
  19413. domUtils.on(me.body, 'dragstart', function (evt) {
  19414. mouseUpEvent.call(me, 'dragstart', evt);
  19415. });
  19416. me.addOutputRule(function (root) {
  19417. utils.each(root.getNodesByTagName('div'), function (n) {
  19418. if (n.getAttr('id') == 'ue_tableDragLine') {
  19419. n.parentNode.removeChild(n);
  19420. }
  19421. });
  19422. });
  19423. var currentRowIndex = 0;
  19424. me.addListener("mousedown", function () {
  19425. currentRowIndex = 0;
  19426. });
  19427. me.addListener('tabkeydown', function () {
  19428. var range = this.selection.getRange(),
  19429. common = range.getCommonAncestor(true, true),
  19430. table = domUtils.findParentByTagName(common, 'table');
  19431. if (table) {
  19432. if (domUtils.findParentByTagName(common, 'caption', true)) {
  19433. var cell = domUtils.getElementsByTagName(table, 'th td');
  19434. if (cell && cell.length) {
  19435. range.setStart(cell[0], 0).setCursor(false, true)
  19436. }
  19437. } else {
  19438. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  19439. ua = getUETable(cell);
  19440. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  19441. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  19442. if (nextCell) {
  19443. if (isEmptyBlock(nextCell)) {
  19444. range.setStart(nextCell, 0).setCursor(false, true)
  19445. } else {
  19446. range.selectNodeContents(nextCell).select()
  19447. }
  19448. } else {
  19449. me.fireEvent('saveScene');
  19450. me.__hasEnterExecCommand = true;
  19451. this.execCommand('insertrownext');
  19452. me.__hasEnterExecCommand = false;
  19453. range = this.selection.getRange();
  19454. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  19455. me.fireEvent('saveScene');
  19456. }
  19457. }
  19458. return true;
  19459. }
  19460. });
  19461. browser.ie && me.addListener('selectionchange', function () {
  19462. toggleDraggableState(this, false, "", null);
  19463. });
  19464. me.addListener("keydown", function (type, evt) {
  19465. var me = this;
  19466. //处理在表格的最后一个输入tab产生新的表格
  19467. var keyCode = evt.keyCode || evt.which;
  19468. if (keyCode == 8 || keyCode == 46) {
  19469. return;
  19470. }
  19471. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  19472. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  19473. var ut = getUETableBySelected(me);
  19474. if (!ut) return;
  19475. notCtrlKey && ut.clearSelected();
  19476. });
  19477. me.addListener("beforegetcontent", function () {
  19478. switchBorderColor(this, false);
  19479. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  19480. if (domUtils.isEmptyNode(ci)) {
  19481. ci.innerHTML = '&nbsp;'
  19482. }
  19483. });
  19484. });
  19485. me.addListener("aftergetcontent", function () {
  19486. switchBorderColor(this, true);
  19487. });
  19488. me.addListener("getAllHtml", function () {
  19489. removeSelectedClass(me.document.getElementsByTagName("td"));
  19490. });
  19491. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  19492. me.addListener("fullscreenchanged", function (type, fullscreen) {
  19493. if (!fullscreen) {
  19494. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  19495. tables = domUtils.getElementsByTagName(this.body, "table");
  19496. utils.each(tables, function (table) {
  19497. if (table.offsetWidth < me.body.offsetWidth) return false;
  19498. var tds = domUtils.getElementsByTagName(table, "td"),
  19499. backWidths = [];
  19500. utils.each(tds, function (td) {
  19501. backWidths.push(td.offsetWidth);
  19502. });
  19503. for (var i = 0, td; td = tds[i]; i++) {
  19504. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  19505. }
  19506. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  19507. });
  19508. }
  19509. });
  19510. //重写execCommand命令,用于处理框选时的处理
  19511. var oldExecCommand = me.execCommand;
  19512. me.execCommand = function(cmd, datatat) {
  19513. var me = this,
  19514. args = arguments;
  19515. cmd = cmd.toLowerCase();
  19516. var ut = getUETableBySelected(me), tds,
  19517. range = new dom.Range(me.document),
  19518. cmdFun = me.commands[cmd] || UE.commands[cmd],
  19519. result;
  19520. if (!cmdFun) return;
  19521. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  19522. me.__hasEnterExecCommand = true;
  19523. me.fireEvent("beforeexeccommand", cmd);
  19524. tds = ut.selectedTds;
  19525. var lastState = -2, lastValue = -2, value, state;
  19526. for (var i = 0, td; td = tds[i]; i++) {
  19527. if (isEmptyBlock(td)) {
  19528. range.setStart(td, 0).setCursor(false, true)
  19529. } else {
  19530. range.selectNode(td).select(true);
  19531. }
  19532. state = me.queryCommandState(cmd);
  19533. value = me.queryCommandValue(cmd);
  19534. if (state != -1) {
  19535. if (lastState !== state || lastValue !== value) {
  19536. me._ignoreContentChange = true;
  19537. result = oldExecCommand.apply(me, arguments);
  19538. me._ignoreContentChange = false;
  19539. }
  19540. lastState = me.queryCommandState(cmd);
  19541. lastValue = me.queryCommandValue(cmd);
  19542. if (domUtils.isEmptyBlock(td)) {
  19543. domUtils.fillNode(me.document, td)
  19544. }
  19545. }
  19546. }
  19547. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19548. me.fireEvent('contentchange');
  19549. me.fireEvent("afterexeccommand", cmd);
  19550. me.__hasEnterExecCommand = false;
  19551. me._selectionChange();
  19552. } else {
  19553. result = oldExecCommand.apply(me, arguments);
  19554. }
  19555. return result;
  19556. };
  19557. });
  19558. /**
  19559. * 删除obj的宽高style,改成属性宽高
  19560. * @param obj
  19561. * @param replaceToProperty
  19562. */
  19563. function removeStyleSize(obj, replaceToProperty) {
  19564. removeStyle(obj, "width", true);
  19565. removeStyle(obj, "height", true);
  19566. }
  19567. function removeStyle(obj, styleName, replaceToProperty) {
  19568. if (obj.style[styleName]) {
  19569. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19570. obj.style[styleName] = "";
  19571. }
  19572. }
  19573. function getParentTdOrTh(ele) {
  19574. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19575. var td;
  19576. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19577. return null;
  19578. }
  19579. function isEmptyBlock(node) {
  19580. var reg = new RegExp(domUtils.fillChar, 'g');
  19581. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19582. return 0;
  19583. }
  19584. for (var n in dtd.$isNotEmpty) {
  19585. if (node.getElementsByTagName(n).length) {
  19586. return 0;
  19587. }
  19588. }
  19589. return 1;
  19590. }
  19591. function mouseCoords(evt) {
  19592. if (evt.pageX || evt.pageY) {
  19593. return {x: evt.pageX, y: evt.pageY};
  19594. }
  19595. return {
  19596. x: evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19597. y: evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19598. };
  19599. }
  19600. function mouseMoveEvent(evt) {
  19601. if (isEditorDisabled()) {
  19602. return;
  19603. }
  19604. try {
  19605. //普通状态下鼠标移动
  19606. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19607. pos;
  19608. //区分用户的行为是拖动还是双击
  19609. if (isInResizeBuffer) {
  19610. me.body.style.webkitUserSelect = 'none';
  19611. if (Math.abs(userActionStatus.x - evt.clientX) > offsetOfTableCell || Math.abs(userActionStatus.y - evt.clientY) > offsetOfTableCell) {
  19612. clearTableDragTimer();
  19613. isInResizeBuffer = false;
  19614. singleClickState = 0;
  19615. //drag action
  19616. tableBorderDrag(evt);
  19617. }
  19618. }
  19619. //修改单元格大小时的鼠标移动
  19620. if (onDrag && dragTd) {
  19621. singleClickState = 0;
  19622. me.body.style.webkitUserSelect = 'none';
  19623. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19624. pos = mouseCoords(evt);
  19625. toggleDraggableState(me, true, onDrag, pos, target);
  19626. if (onDrag == "h") {
  19627. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19628. } else if (onDrag == "v") {
  19629. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19630. }
  19631. return;
  19632. }
  19633. //当鼠标处于table上时,修改移动过程中的光标状态
  19634. if (target) {
  19635. //针对使用table作为容器的组件不触发拖拽效果
  19636. if (me.fireEvent('excludetable', target) === true)
  19637. return;
  19638. pos = mouseCoords(evt);
  19639. var state = getRelation(target, pos),
  19640. table = domUtils.findParentByTagName(target, "table", true);
  19641. if (inTableSide(table, target, evt, true)) {
  19642. if (me.fireEvent("excludetable", table) === true) return;
  19643. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19644. } else if (inTableSide(table, target, evt)) {
  19645. if (me.fireEvent("excludetable", table) === true) return;
  19646. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19647. } else {
  19648. me.body.style.cursor = "text";
  19649. var curCell = target;
  19650. if (/\d/.test(state)) {
  19651. state = state.replace(/\d/, '');
  19652. target = getUETable(target).getPreviewCell(target, state == "v");
  19653. }
  19654. //位于第一行的顶部或者第一列的左边时不可拖动
  19655. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19656. }
  19657. } else {
  19658. toggleDragButton(false, table, me);
  19659. }
  19660. } catch (e) {
  19661. showError(e);
  19662. }
  19663. }
  19664. var dragButtonTimer;
  19665. function toggleDragButton(show, table, editor) {
  19666. if (!show) {
  19667. if (dragOver) return;
  19668. dragButtonTimer = setTimeout(function() {
  19669. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19670. }, 2000);
  19671. } else {
  19672. createDragButton(table, editor);
  19673. }
  19674. }
  19675. function createDragButton(table, editor) {
  19676. var pos = domUtils.getXY(table),
  19677. doc = table.ownerDocument;
  19678. if (dragButton && dragButton.parentNode) return dragButton;
  19679. dragButton = doc.createElement("div");
  19680. dragButton.contentEditable = false;
  19681. dragButton.innerHTML = "";
  19682. 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;";
  19683. domUtils.unSelectable(dragButton);
  19684. dragButton.onmouseover = function (evt) {
  19685. dragOver = true;
  19686. };
  19687. dragButton.onmouseout = function (evt) {
  19688. dragOver = false;
  19689. };
  19690. domUtils.on(dragButton, 'click', function (type, evt) {
  19691. doClick(evt, this);
  19692. });
  19693. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19694. doDblClick(evt);
  19695. });
  19696. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19697. domUtils.preventDefault(evt);
  19698. });
  19699. var timer;
  19700. function doClick(evt, button) {
  19701. // 部分浏览器下需要清理
  19702. clearTimeout(timer);
  19703. timer = setTimeout(function () {
  19704. editor.fireEvent("tableClicked", table, button);
  19705. }, 300);
  19706. }
  19707. function doDblClick(evt) {
  19708. clearTimeout(timer);
  19709. var ut = getUETable(table),
  19710. start = table.rows[0].cells[0],
  19711. end = ut.getLastCell(),
  19712. range = ut.getCellsRange(start, end);
  19713. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19714. ut.setSelected(range);
  19715. }
  19716. doc.body.appendChild(dragButton);
  19717. }
  19718. // function inPosition(table, pos) {
  19719. // var tablePos = domUtils.getXY(table),
  19720. // width = table.offsetWidth,
  19721. // height = table.offsetHeight;
  19722. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19723. // return "topLeft";
  19724. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19725. // return "bottomRight";
  19726. // }
  19727. // }
  19728. function inTableSide(table, cell, evt, top) {
  19729. var pos = mouseCoords(evt),
  19730. state = getRelation(cell, pos);
  19731. if (top) {
  19732. var caption = table.getElementsByTagName("caption")[0],
  19733. capHeight = caption ? caption.offsetHeight : 0;
  19734. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19735. } else {
  19736. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19737. }
  19738. }
  19739. /**
  19740. * 获取拖动时允许的X轴坐标
  19741. * @param dragTd
  19742. * @param evt
  19743. */
  19744. function getPermissionX(dragTd, evt) {
  19745. var ut = getUETable(dragTd);
  19746. if (ut) {
  19747. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19748. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19749. mouseX = mouseCoords(evt).x,
  19750. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20,
  19751. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19752. left += cellMinWidth;
  19753. right -= cellMinWidth;
  19754. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19755. }
  19756. }
  19757. /**
  19758. * 获取拖动时允许的Y轴坐标
  19759. */
  19760. function getPermissionY(dragTd, evt) {
  19761. try {
  19762. var top = domUtils.getXY(dragTd).y,
  19763. mousePosY = mouseCoords(evt).y;
  19764. return mousePosY < top ? top : mousePosY;
  19765. } catch (e) {
  19766. showError(e);
  19767. }
  19768. }
  19769. /**
  19770. * 移动状态切换
  19771. */
  19772. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19773. try {
  19774. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19775. if (browser.ie) {
  19776. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19777. getDragLine(editor, editor.document);
  19778. showDragLineAt(dir, cell);
  19779. } else {
  19780. hideDragLine(editor)
  19781. }
  19782. }
  19783. onBorder = draggable;
  19784. /*
  19785. *0428
  19786. *add:鼠标移到border时,更加容易看见拖拽的线
  19787. ********************************************/
  19788. // if (onBorder) {
  19789. // getDragLine(editor, editor.document);
  19790. // showDragLineAt(dir, cell);
  19791. // } else {
  19792. // hideDragLine(editor)
  19793. // }
  19794. /**************************************** */
  19795. } catch (e) {
  19796. showError(e);
  19797. }
  19798. }
  19799. /**
  19800. * 获取与UETable相关的resize line
  19801. * @param uetable UETable对象
  19802. */
  19803. function getResizeLineByUETable() {
  19804. var lineId = '_UETableResizeLine',
  19805. line = this.document.getElementById(lineId);
  19806. if (!line) {
  19807. line = this.document.createElement("div");
  19808. line.id = lineId;
  19809. line.contnetEditable = false;
  19810. line.setAttribute("unselectable", "on");
  19811. var styles = {
  19812. width: 2 * cellBorderWidth + 1 + 'px',
  19813. position: 'absolute',
  19814. 'z-index': 100000,
  19815. cursor: 'col-resize',
  19816. background: 'red',
  19817. display: 'none'
  19818. };
  19819. //切换状态
  19820. line.onmouseout = function() {
  19821. this.style.display = 'none';
  19822. };
  19823. utils.extend(line.style, styles);
  19824. this.document.body.appendChild(line);
  19825. }
  19826. return line;
  19827. }
  19828. /**
  19829. * 更新resize-line
  19830. */
  19831. function updateResizeLine(cell, uetable) {
  19832. var line = getResizeLineByUETable.call(this),
  19833. table = uetable.table,
  19834. styles = {
  19835. top: domUtils.getXY(table).y + 'px',
  19836. left: domUtils.getXY(cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19837. display: 'block',
  19838. height: table.offsetHeight + 'px'
  19839. };
  19840. utils.extend(line.style, styles);
  19841. }
  19842. /**
  19843. * 显示resize-line
  19844. */
  19845. function showResizeLine(cell) {
  19846. var uetable = getUETable(cell);
  19847. updateResizeLine.call(this, cell, uetable);
  19848. }
  19849. /**
  19850. * 获取鼠标与当前单元格的相对位置
  19851. * @param ele
  19852. * @param mousePos
  19853. */
  19854. function getRelation(ele, mousePos) {
  19855. var elePos = domUtils.getXY(ele);
  19856. if (!elePos) {
  19857. return '';
  19858. }
  19859. // if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth ) {
  19860. // return "h";
  19861. // }
  19862. // if (mousePos.x - elePos.x < cellBorderWidth ) {
  19863. // return 'h1'
  19864. // }
  19865. // if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19866. // return "v";
  19867. // }
  19868. // if (mousePos.y - elePos.y < cellBorderWidth ) {
  19869. // return 'v1'
  19870. // }
  19871. // return '';
  19872. /*
  19873. *0428
  19874. *modify:加大可拖拽的boder范围
  19875. *************************************/
  19876. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth + 5) {
  19877. return "h";
  19878. }
  19879. if (mousePos.x - elePos.x < cellBorderWidth + 5) {
  19880. return 'h1'
  19881. }
  19882. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth + 5) {
  19883. return "v";
  19884. }
  19885. if (mousePos.y - elePos.y < cellBorderWidth + 5) {
  19886. return 'v1'
  19887. }
  19888. return '';
  19889. /********************************* */
  19890. }
  19891. function mouseDownEvent(type, evt) {
  19892. if (isEditorDisabled()) {
  19893. return;
  19894. }
  19895. userActionStatus = {
  19896. x: evt.clientX,
  19897. y: evt.clientY
  19898. };
  19899. //右键菜单单独处理
  19900. if (evt.button == 2) {
  19901. var ut = getUETableBySelected(me),
  19902. flag = false;
  19903. if (ut) {
  19904. var td = getTargetTd(me, evt);
  19905. utils.each(ut.selectedTds, function (ti) {
  19906. if (ti === td) {
  19907. flag = true;
  19908. }
  19909. });
  19910. if (!flag) {
  19911. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19912. ut.clearSelected()
  19913. } else {
  19914. td = ut.selectedTds[0];
  19915. setTimeout(function () {
  19916. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19917. }, 0);
  19918. }
  19919. }
  19920. } else {
  19921. return tableClickHander(evt);
  19922. }
  19923. }
  19924. //清除表格的计时器
  19925. function clearTableTimer() {
  19926. tabTimer && clearTimeout(tabTimer);
  19927. tabTimer = null;
  19928. }
  19929. //双击收缩
  19930. function tableDbclickHandler(evt) {
  19931. singleClickState = 0;
  19932. evt = evt || me.window.event;
  19933. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19934. if (target) {
  19935. var h;
  19936. if (h = getRelation(target, mouseCoords(evt))) {
  19937. hideDragLine(me);
  19938. if (h == 'h1') {
  19939. h = 'h';
  19940. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19941. me.execCommand('adaptbywindow');
  19942. } else {
  19943. target = getUETable(target).getPreviewCell(target);
  19944. if (target) {
  19945. var rng = me.selection.getRange();
  19946. rng.selectNodeContents(target).setCursor(true, true)
  19947. }
  19948. }
  19949. }
  19950. if (h == 'h') {
  19951. var ut = getUETable(target),
  19952. table = ut.table,
  19953. cells = getCellsByMoveBorder(target, table, true);
  19954. cells = extractArray(cells, 'left');
  19955. ut.width = ut.offsetWidth;
  19956. var oldWidth = [],
  19957. newWidth = [];
  19958. utils.each(cells, function(cell) {
  19959. oldWidth.push(cell.offsetWidth);
  19960. });
  19961. utils.each(cells, function(cell) {
  19962. cell.removeAttribute("width");
  19963. });
  19964. window.setTimeout(function() {
  19965. //是否允许改变
  19966. var changeable = true;
  19967. utils.each(cells, function(cell, index) {
  19968. var width = cell.offsetWidth;
  19969. if (width > oldWidth[index]) {
  19970. changeable = false;
  19971. return false;
  19972. }
  19973. newWidth.push(width);
  19974. });
  19975. var change = changeable ? newWidth : oldWidth;
  19976. utils.each(cells, function(cell, index) {
  19977. cell.width = change[index] - getTabcellSpace();
  19978. });
  19979. }, 0);
  19980. // minWidth -= cellMinWidth;
  19981. //
  19982. // table.removeAttribute("width");
  19983. // utils.each(cells, function (cell) {
  19984. // cell.style.width = "";
  19985. // cell.width -= minWidth;
  19986. // });
  19987. }
  19988. }
  19989. }
  19990. }
  19991. function tableClickHander(evt) {
  19992. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19993. //trace:3113
  19994. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19995. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19996. t.ueTable = null;
  19997. });
  19998. startTd = getTargetTd(me, evt);
  19999. if (!startTd) return;
  20000. var table = domUtils.findParentByTagName(startTd, "table", true);
  20001. ut = getUETable(table);
  20002. ut && ut.clearSelected();
  20003. //判断当前鼠标状态
  20004. if (!onBorder) {
  20005. me.document.body.style.webkitUserSelect = '';
  20006. mousedown = true;
  20007. me.addListener('mouseover', mouseOverEvent);
  20008. } else {
  20009. //边框上的动作处理
  20010. borderActionHandler(evt);
  20011. /*
  20012. *0428
  20013. *add:点击拖拽线时,防止选中单元格
  20014. *********************************/
  20015. return true
  20016. }
  20017. }
  20018. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  20019. function borderActionHandler(evt) {
  20020. if (browser.ie) {
  20021. evt = reconstruct(evt);
  20022. }
  20023. clearTableDragTimer();
  20024. //是否正在等待resize的缓冲中
  20025. isInResizeBuffer = true;
  20026. // tableDragTimer = setTimeout(function(){
  20027. // tableBorderDrag( evt );
  20028. // }, dblclickTime);
  20029. /*
  20030. *0428
  20031. *modify:缩小拖拽线的显示时间间隔
  20032. ********************************************/
  20033. tableDragTimer = setTimeout(function () {
  20034. tableBorderDrag(evt);
  20035. }, 180);
  20036. }
  20037. function extractArray(originArr, key) {
  20038. var result = [],
  20039. tmp = null;
  20040. for (var i = 0, len = originArr.length; i < len; i++) {
  20041. tmp = originArr[i][key];
  20042. if (tmp) {
  20043. result.push(tmp);
  20044. }
  20045. }
  20046. return result;
  20047. }
  20048. function clearTableDragTimer() {
  20049. tableDragTimer && clearTimeout(tableDragTimer);
  20050. tableDragTimer = null;
  20051. }
  20052. function reconstruct(obj) {
  20053. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  20054. newObj = {};
  20055. if (obj) {
  20056. for (var i = 0, key, val; key = attrs[i]; i++) {
  20057. val = obj[key];
  20058. val && (newObj[key] = val);
  20059. }
  20060. }
  20061. return newObj;
  20062. }
  20063. //边框拖动
  20064. function tableBorderDrag(evt) {
  20065. isInResizeBuffer = false;
  20066. startTd = evt.target || evt.srcElement;
  20067. if (!startTd) return;
  20068. var state = getRelation(startTd, mouseCoords(evt));
  20069. if (/\d/.test(state)) {
  20070. state = state.replace(/\d/, '');
  20071. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  20072. }
  20073. hideDragLine(me);
  20074. getDragLine(me, me.document);
  20075. // me.fireEvent('saveScene');
  20076. showDragLineAt(state, startTd);
  20077. mousedown = true;
  20078. //拖动开始
  20079. onDrag = state;
  20080. dragTd = startTd;
  20081. }
  20082. function mouseUpEvent(type, evt) {
  20083. if (isEditorDisabled()) {
  20084. return;
  20085. }
  20086. clearTableDragTimer();
  20087. isInResizeBuffer = false;
  20088. if (onBorder) {
  20089. singleClickState = ++singleClickState % 3;
  20090. userActionStatus = {
  20091. x: evt.clientX,
  20092. y: evt.clientY
  20093. };
  20094. tableResizeTimer = setTimeout(function() {
  20095. singleClickState > 0 && singleClickState--;
  20096. }, dblclickTime);
  20097. if (singleClickState === 2) {
  20098. singleClickState = 0;
  20099. tableDbclickHandler(evt);
  20100. return;
  20101. }
  20102. }
  20103. if (evt.button == 2) return;
  20104. var me = this;
  20105. //清除表格上原生跨选问题
  20106. var range = me.selection.getRange(),
  20107. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  20108. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  20109. if (start || end) {
  20110. if (start === end) {
  20111. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  20112. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  20113. if (start !== end) {
  20114. me.selection.clearRange()
  20115. }
  20116. } else {
  20117. me.selection.clearRange()
  20118. }
  20119. }
  20120. mousedown = false;
  20121. me.document.body.style.webkitUserSelect = '';
  20122. //拖拽状态下的mouseUP
  20123. if (onDrag && dragTd) {
  20124. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  20125. singleClickState = 0;
  20126. dragLine = me.document.getElementById('ue_tableDragLine');
  20127. // trace 3973
  20128. if (dragLine) {
  20129. var dragTdPos = domUtils.getXY(dragTd),
  20130. dragLinePos = domUtils.getXY(dragLine);
  20131. switch (onDrag) {
  20132. case "h":
  20133. // changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  20134. /*
  20135. *0428
  20136. *modify:取实际的偏移量
  20137. **************************************/
  20138. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x - dragTd.clientWidth);
  20139. break;
  20140. case "v":
  20141. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  20142. break;
  20143. default:
  20144. }
  20145. onDrag = "";
  20146. dragTd = null;
  20147. hideDragLine(me);
  20148. me.fireEvent('saveScene');
  20149. return;
  20150. }
  20151. }
  20152. //正常状态下的mouseup
  20153. if (!startTd) {
  20154. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  20155. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  20156. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  20157. if (me.fireEvent("excludetable", target) === true) return;
  20158. range = new dom.Range(me.document);
  20159. range.setStart(target, 0).setCursor(false, true);
  20160. }
  20161. } else {
  20162. var ut = getUETable(startTd),
  20163. cell = ut ? ut.selectedTds[0] : null;
  20164. if (cell) {
  20165. range = new dom.Range(me.document);
  20166. if (domUtils.isEmptyBlock(cell)) {
  20167. range.setStart(cell, 0).setCursor(false, true);
  20168. } else {
  20169. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  20170. }
  20171. } else {
  20172. range = me.selection.getRange().shrinkBoundary();
  20173. if (!range.collapsed) {
  20174. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  20175. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  20176. //在table里边的不能清除
  20177. if (start && !end || !start && end || start && end && start !== end) {
  20178. range.setCursor(false, true);
  20179. }
  20180. }
  20181. }
  20182. startTd = null;
  20183. me.removeListener('mouseover', mouseOverEvent);
  20184. }
  20185. me._selectionChange(250, evt);
  20186. }
  20187. function mouseOverEvent(type, evt) {
  20188. if (isEditorDisabled()) {
  20189. return;
  20190. }
  20191. var me = this,
  20192. tar = evt.target || evt.srcElement;
  20193. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  20194. //需要判断两个TD是否位于同一个表格内
  20195. if (startTd && currentTd &&
  20196. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  20197. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  20198. var ut = getUETable(currentTd);
  20199. if (startTd != currentTd) {
  20200. me.document.body.style.webkitUserSelect = 'none';
  20201. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  20202. var range = ut.getCellsRange(startTd, currentTd);
  20203. ut.setSelected(range);
  20204. } else {
  20205. me.document.body.style.webkitUserSelect = '';
  20206. ut.clearSelected();
  20207. }
  20208. }
  20209. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  20210. }
  20211. function setCellHeight(cell, height, backHeight) {
  20212. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  20213. tmpHeight = backHeight + height;
  20214. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  20215. if (cell.style.height) cell.style.height = "";
  20216. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  20217. }
  20218. function getWidth(cell) {
  20219. if (!cell) return 0;
  20220. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  20221. }
  20222. /***
  20223. * 0428
  20224. * add:表格工具类
  20225. */
  20226. var resizeUtil = {
  20227. getColGroup: function (table) {
  20228. var colGroup = table.getElementsByTagName('colgroup');
  20229. return colGroup && colGroup.length > 0 ? colGroup[0] : null
  20230. },
  20231. getCols: function (table) {
  20232. },
  20233. getTbody: function (table) {
  20234. var tbody = table.getElementsByTagName('tbody');
  20235. return tbody && tbody.length > 0 ? tbody[0] : null
  20236. },
  20237. getTfoot: function (table) {
  20238. var tfooter = table.getElementsByTagName('tfoot');
  20239. return tfooter && tfooter.length > 0 ? tfooter[0] : null
  20240. },
  20241. getTrs: function (table) {
  20242. var tbody = this.getTbody(table);
  20243. if (tbody) {
  20244. var trs = tbody.getElementsByTagName('tr');
  20245. return trs || null;
  20246. }
  20247. return null;
  20248. },
  20249. getTdIndex: function (table, cell, maxColCount) {
  20250. var index = -1;
  20251. if (cell && maxColCount) {
  20252. var position = cell.getBoundingClientRect();
  20253. var trs = $(table).find('tr');
  20254. if (trs && trs.length > 0) {
  20255. var maxColTr;
  20256. for (var i = 0; i < trs.length; i++) {
  20257. var tr = trs.eq(i);
  20258. var colCount = tr.find('th,td').length;
  20259. if (colCount == maxColCount) {
  20260. maxColTr = tr;
  20261. break;
  20262. }
  20263. }
  20264. if (maxColTr) {
  20265. var cols = maxColTr.find('th,td');
  20266. if (cols && cols.length > 0) {
  20267. for (var i = 0; i < cols.length; i++) {
  20268. var col = cols.eq(i)[0];
  20269. var colPosition = col.getBoundingClientRect();
  20270. if (colPosition.right == position.right) {
  20271. index = i;
  20272. break;
  20273. }
  20274. }
  20275. }
  20276. }
  20277. }
  20278. }
  20279. return index;
  20280. },
  20281. getColsWidth: function (table, maxColCount, isFirst) {
  20282. var result = [];
  20283. var trs = this.getTrs(table);
  20284. var maxTr;
  20285. if (trs) {
  20286. for (var i = 0; i < trs.length; i++) {
  20287. var tr = trs[i];
  20288. var tds = tr.children;
  20289. if (tds && tds.length == maxColCount) {
  20290. maxTr = tr;
  20291. break;
  20292. }
  20293. }
  20294. var tds;
  20295. if (maxTr) {
  20296. //没有合并单元格式的
  20297. tds = maxTr.children;
  20298. } else {
  20299. //有合并单元格式的
  20300. //需要构造tfooter
  20301. var tfoot = me.document.createElement('tfoot');
  20302. for (var i = 0; i < maxColCount; i++) {
  20303. var td = me.document.createElement('td');
  20304. tfoot.appendChild(td);
  20305. }
  20306. table.appendChild(tfoot);
  20307. tds = tfoot.children;
  20308. }
  20309. if (tds && tds.length > 0) {
  20310. for (var i = 0; i < maxColCount; i++) {
  20311. var td = tds[i];
  20312. // var q=isFirst?td.getBoundingClientRect().width:td.clientWidth;
  20313. var q = td.getBoundingClientRect();
  20314. result.push(q)
  20315. }
  20316. if (tfoot) {
  20317. tfoot.remove();
  20318. }
  20319. }
  20320. }
  20321. return result;
  20322. }
  20323. };
  20324. function changeColWidth(cell, changeValue) {
  20325. var ut = getUETable(cell);
  20326. if (ut) {
  20327. //根据当前移动的边框获取相关的单元格
  20328. var table = ut.table,
  20329. cells = getCellsByMoveBorder(cell, table);
  20330. var isSuccess = false;
  20331. try {
  20332. if (table && table.nodeName.toLowerCase() != 'table') return;
  20333. changeValue;
  20334. var bodyWidth = me.body.clientWidth;
  20335. var tableWidth = table.clientWidth;
  20336. var tableFinalWidth = (tableWidth + changeValue);
  20337. var tr = cell.parentNode;
  20338. var tdIndex = cell.cellIndex;
  20339. var maxColCount = ut.getMaxCols();
  20340. var colIndex = resizeUtil.getTdIndex(table, cell, maxColCount);
  20341. var colgroup = table.getElementsByTagName('colgroup');
  20342. var tbody = table.getElementsByTagName('tbody');
  20343. var trs = tbody[0].getElementsByTagName('tr');
  20344. //是否需要重建colGroup
  20345. var reBuildColGroup = true;
  20346. if (colgroup && colgroup.length > 0) {
  20347. var cols = colgroup[0].getElementsByTagName('col');
  20348. //不需要重建是否需要重建colGroup
  20349. var tdArray = resizeUtil.getColsWidth(table, maxColCount, true);
  20350. if (cols && cols.length == maxColCount) {
  20351. for (var i = 0; i < cols.length; i++) {
  20352. var col = cols[i];
  20353. if (col) {
  20354. var width, left, right, percent, widthPercent;
  20355. if (col.hasAttribute('data-resize-pixel')) {
  20356. width = col.getAttribute('data-resize-pixel');
  20357. // percent=col.getAttribute('data-resize-percent');
  20358. // left=col.getAttribute('data-offset-left');
  20359. // right=col.getAttribute('data-offset-right');
  20360. if (i == colIndex) {
  20361. var width = parseInt(width) + changeValue;
  20362. var percent = (width / tableWidth * 100);
  20363. var widthPercent = percent.toFixed(4);
  20364. col.style.width = (widthPercent + '%');
  20365. }
  20366. }
  20367. // else{
  20368. // }
  20369. }
  20370. }
  20371. table.style.width = (tableFinalWidth + 'px');
  20372. // table.style.width= (((tableFinalWidth/bodyWidth)*100).toFixed(4) +'%');
  20373. table.style['table-layout'] = 'fixed';
  20374. table.removeAttribute('width');
  20375. // table.setAttribute('width', (tableFinalWidth + 'px'));
  20376. // table.setAttribute('table-layout','fixed');
  20377. for (var i = 0; i < cols.length; i++) {
  20378. var col = cols[i];
  20379. var td = tdArray[i];
  20380. var width = td.width;
  20381. var left = td.left;
  20382. var right = td.right;
  20383. var percent = (width / tableFinalWidth * 100);
  20384. var widthPercent = percent.toFixed(4);
  20385. //调整的是当前列
  20386. if (i == colIndex) {
  20387. width = width + changeValue;
  20388. right = right + changeValue;
  20389. percent = (width / tableFinalWidth * 100);
  20390. widthPercent = percent.toFixed(4);
  20391. }
  20392. col.style.width = (widthPercent + '%');
  20393. col.setAttribute('data-offset-left', left);
  20394. col.setAttribute('data-offset-right', right);
  20395. col.setAttribute('data-resize-pixel', width);
  20396. col.setAttribute('data-resize-percent', percent);
  20397. }
  20398. reBuildColGroup = false;
  20399. }
  20400. } else {
  20401. // colgroup[0].remove()
  20402. reBuildColGroup = true;
  20403. }
  20404. if (reBuildColGroup) {
  20405. //重建colGroup
  20406. var tdArray = resizeUtil.getColsWidth(table, maxColCount, true);
  20407. //重建colGroup
  20408. var newColGroup = me.document.createElement('colgroup');
  20409. for (var i = 0; i < maxColCount; i++) {
  20410. var newCol = me.document.createElement('col');
  20411. var td = tdArray[i];
  20412. var width = td.width;
  20413. var left = td.left;
  20414. var right = td.right;
  20415. if (i == colIndex) {
  20416. width = width + changeValue;
  20417. right = right + changeValue;
  20418. }
  20419. newCol.style.width = (width + 'px');
  20420. newCol.setAttribute('data-offset-left', left);
  20421. newCol.setAttribute('data-offset-right', right);
  20422. newCol.setAttribute('data-resize-pixel', width);
  20423. newColGroup.appendChild(newCol)
  20424. }
  20425. if (tbody && tbody.length > 0) {
  20426. //移除旧的
  20427. if (colgroup && colgroup.length > 0) {
  20428. colgroup[0].remove();
  20429. }
  20430. $('theader th,tbody td', $(table)).css({width: ''}).removeAttr('width');
  20431. //添加新的
  20432. table.insertBefore(newColGroup, tbody[0]);
  20433. }
  20434. tdArray = resizeUtil.getColsWidth(table, maxColCount, true);
  20435. table.style.width = (tableFinalWidth + 'px');
  20436. // table.style.width= (((tableFinalWidth/bodyWidth)*100).toFixed(4) +'%');
  20437. table.style['table-layout'] = 'fixed';
  20438. table.removeAttribute('width');
  20439. // table.setAttribute('width', (tableFinalWidth + 'px'));
  20440. // table.setAttribute('table-layout','fixed');
  20441. // var bodyWidth=me.body.clientWidth;
  20442. // table.style.width = ((tableFinalWidth/bodyWidth * 100).toFixed(4)+ '%');
  20443. // table.setAttribute('table-layout','fixed');
  20444. //转换为百分比
  20445. var newCols = newColGroup.children;
  20446. for (var i = 0; i < newCols.length; i++) {
  20447. var newCol = newCols[i];
  20448. var td = tdArray[i];
  20449. var width = td.width;
  20450. var left = td.left;
  20451. var right = td.right;
  20452. var percent = (width / tableFinalWidth * 100);
  20453. var widthPercent = percent.toFixed(4);
  20454. newCol.style.width = (widthPercent + '%');
  20455. newCol.setAttribute('data-offset-left', left);
  20456. newCol.setAttribute('data-offset-right', right);
  20457. newCol.setAttribute('data-resize-pixel', width);
  20458. newCol.setAttribute('data-resize-percent', percent);
  20459. }
  20460. }
  20461. isSuccess = true;
  20462. } catch (ex) {
  20463. throw ex;
  20464. } finally {
  20465. //成功后返回,否则执行原来的逻辑
  20466. if (isSuccess) return;
  20467. }
  20468. /**********************************************/
  20469. //根据当前移动的边框获取相关的单元格
  20470. var table = ut.table,
  20471. cells = getCellsByMoveBorder(cell, table);
  20472. table.style.width = "";
  20473. table.removeAttribute("width");
  20474. //修正改变量
  20475. // changeValue = correctChangeValue(changeValue, cell, cells);
  20476. /**
  20477. *0428
  20478. *modify:只调整当前单元格,不影响其他单元格
  20479. **********************************************/
  20480. // changeValue -= getTabcellSpace();
  20481. changeValue
  20482. var colgroup = table.getElementsByTagName('colgroup');
  20483. if (colgroup && colgroup.length > 0) {
  20484. colgroup[0].remove()
  20485. } else {
  20486. }
  20487. var tbClientWidth = table.clientWidth;
  20488. table.style.width = tbClientWidth + changeValue;
  20489. table.setAttribute('width', ((tbClientWidth + changeValue) + 'px'));
  20490. var cellClientWidth = cell.clientWidth;
  20491. cell.style.width = (cellClientWidth + changeValue) + 'px';
  20492. cell.setAttribute('width', ((cellClientWidth + changeValue) + 'px'));
  20493. return
  20494. /**********************************************/
  20495. if (cell.nextSibling) {
  20496. var i = 0;
  20497. utils.each(cells, function (cellGroup) {
  20498. cellGroup.left.width = (+cellGroup.left.width) + changeValue;
  20499. cellGroup.right && (cellGroup.right.width = (+cellGroup.right.width) - changeValue);
  20500. });
  20501. } else {
  20502. utils.each(cells, function (cellGroup) {
  20503. cellGroup.left.width -= -changeValue;
  20504. });
  20505. }
  20506. }
  20507. var ut = getUETable(cell);
  20508. if (ut) {
  20509. //根据当前移动的边框获取相关的单元格
  20510. var table = ut.table,
  20511. cells = getCellsByMoveBorder(cell, table);
  20512. // table.style.width = "";
  20513. // table.removeAttribute("width");
  20514. //修正改变量
  20515. // changeValue = correctChangeValue( changeValue, cell, cells );
  20516. /**
  20517. *0428
  20518. *modify:只调整当前单元格,不影响其他单元格
  20519. **********************************************/
  20520. // changeValue -= getTabcellSpace();
  20521. // var colgroup = table.getElementsByTagName('colgroup');
  20522. // if (colgroup && colgroup.length > 0) {
  20523. // colgroup[0].remove()
  20524. // } else {
  20525. // }
  20526. // var tbClientWidth = table.clientWidth;
  20527. // table.style.width = tbClientWidth + changeValue;
  20528. // table.setAttribute('width', (tbClientWidth + changeValue) + 'px');
  20529. // var cellClientWidth = cell.clientWidth;
  20530. // cell.style.width = (cellClientWidth + changeValue) + 'px';
  20531. // cell.setAttribute('width', (cellClientWidth + changeValue) + 'px');
  20532. // return
  20533. /**********************************************/
  20534. if (cell.nextSibling) {
  20535. var i = 0;
  20536. utils.each(cells, function(cellGroup) {
  20537. cellGroup.left.width = (+cellGroup.left.width) + changeValue;
  20538. cellGroup.right && (cellGroup.right.width = (+cellGroup.right.width) - changeValue);
  20539. });
  20540. } else {
  20541. utils.each(cells, function(cellGroup) {
  20542. cellGroup.left.width -= -changeValue;
  20543. });
  20544. }
  20545. }
  20546. }
  20547. function isEditorDisabled() {
  20548. return me.body.contentEditable === "false";
  20549. }
  20550. function changeRowHeight(td, changeValue) {
  20551. if (Math.abs(changeValue) < 10) return;
  20552. var ut = getUETable(td);
  20553. if (ut) {
  20554. var cells = ut.getSameEndPosCells(td, "y"),
  20555. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  20556. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  20557. for (var i = 0, cell; cell = cells[i++];) {
  20558. setCellHeight(cell, changeValue, backHeight);
  20559. }
  20560. }
  20561. }
  20562. /**
  20563. * 获取调整单元格大小的相关单元格
  20564. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  20565. */
  20566. function getCellsByMoveBorder(cell, table, isContainMergeCell) {
  20567. if (!table) {
  20568. table = domUtils.findParentByTagName(cell, 'table');
  20569. }
  20570. if (!table) {
  20571. return null;
  20572. }
  20573. //获取到该单元格所在行的序列号
  20574. var index = domUtils.getNodeIndex(cell),
  20575. temp = cell,
  20576. rows = table.rows,
  20577. colIndex = 0;
  20578. while (temp) {
  20579. //获取到当前单元格在未发生单元格合并时的序列
  20580. if (temp.nodeType === 1) {
  20581. colIndex += (temp.colSpan || 1);
  20582. }
  20583. temp = temp.previousSibling;
  20584. }
  20585. temp = null;
  20586. //记录想关的单元格
  20587. var borderCells = [];
  20588. utils.each(rows, function(tabRow) {
  20589. var cells = tabRow.cells,
  20590. currIndex = 0;
  20591. utils.each(cells, function(tabCell) {
  20592. currIndex += (tabCell.colSpan || 1);
  20593. if (currIndex === colIndex) {
  20594. borderCells.push({
  20595. left: tabCell,
  20596. right: tabCell.nextSibling || null
  20597. });
  20598. return false;
  20599. } else if (currIndex > colIndex) {
  20600. if (isContainMergeCell) {
  20601. borderCells.push({
  20602. left: tabCell
  20603. });
  20604. }
  20605. return false;
  20606. }
  20607. });
  20608. });
  20609. return borderCells;
  20610. }
  20611. /**
  20612. * 通过给定的单元格集合获取最小的单元格width
  20613. */
  20614. function getMinWidthByTableCells(cells) {
  20615. var minWidth = Number.MAX_VALUE;
  20616. for (var i = 0, curCell; curCell = cells[i]; i++) {
  20617. minWidth = Math.min(minWidth, curCell.width || getTableCellWidth(curCell));
  20618. }
  20619. return minWidth;
  20620. }
  20621. function correctChangeValue(changeValue, relatedCell, cells) {
  20622. //为单元格的paading预留空间
  20623. changeValue -= getTabcellSpace();
  20624. if (changeValue < 0) {
  20625. return 0;
  20626. }
  20627. changeValue -= getTableCellWidth(relatedCell);
  20628. //确定方向
  20629. var direction = changeValue < 0 ? 'left' : 'right';
  20630. changeValue = Math.abs(changeValue);
  20631. //只关心非最后一个单元格就可以
  20632. utils.each(cells, function(cellGroup) {
  20633. var curCell = cellGroup[direction];
  20634. //为单元格保留最小空间
  20635. if (curCell) {
  20636. changeValue = Math.min(changeValue, getTableCellWidth(curCell) - cellMinWidth);
  20637. }
  20638. });
  20639. //修正越界
  20640. changeValue = changeValue < 0 ? 0 : changeValue;
  20641. return direction === 'left' ? -changeValue : changeValue;
  20642. }
  20643. function getTableCellWidth(cell) {
  20644. var width = 0,
  20645. //偏移纠正量
  20646. offset = 0,
  20647. width = cell.offsetWidth - getTabcellSpace();
  20648. //最后一个节点纠正一下
  20649. if (!cell.nextSibling) {
  20650. width -= getTableCellOffset(cell);
  20651. }
  20652. width = width < 0 ? 0 : width;
  20653. try {
  20654. cell.width = width;
  20655. } catch (e) {
  20656. }
  20657. return width;
  20658. }
  20659. /**
  20660. * 获取单元格所在表格的最末单元格的偏移量
  20661. */
  20662. function getTableCellOffset(cell) {
  20663. tab = domUtils.findParentByTagName(cell, "table", false);
  20664. if (tab.offsetVal === undefined) {
  20665. var prev = cell.previousSibling;
  20666. if (prev) {
  20667. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  20668. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  20669. } else {
  20670. tab.offsetVal = 0;
  20671. }
  20672. }
  20673. return tab.offsetVal;
  20674. }
  20675. function getTabcellSpace() {
  20676. if (UT.tabcellSpace === undefined) {
  20677. var cell = null,
  20678. tab = me.document.createElement("table"),
  20679. tbody = me.document.createElement("tbody"),
  20680. trow = me.document.createElement("tr"),
  20681. tabcell = me.document.createElement("td"),
  20682. mirror = null;
  20683. tabcell.style.cssText = 'border: 0;';
  20684. tabcell.width = 1;
  20685. trow.appendChild(tabcell);
  20686. trow.appendChild(mirror = tabcell.cloneNode(false));
  20687. tbody.appendChild(trow);
  20688. tab.appendChild(tbody);
  20689. tab.style.cssText = "visibility: hidden;";
  20690. me.body.appendChild(tab);
  20691. UT.paddingSpace = tabcell.offsetWidth - 1;
  20692. var tmpTabWidth = tab.offsetWidth;
  20693. tabcell.style.cssText = '';
  20694. mirror.style.cssText = '';
  20695. UT.borderWidth = (tab.offsetWidth - tmpTabWidth) / 3;
  20696. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  20697. me.body.removeChild(tab);
  20698. }
  20699. getTabcellSpace = function() {
  20700. return UT.tabcellSpace;
  20701. };
  20702. return UT.tabcellSpace;
  20703. }
  20704. function getDragLine(editor, doc) {
  20705. if (mousedown) return;
  20706. if (editor.document.getElementById('ue_tableDragLine')) {
  20707. return;
  20708. }
  20709. dragLine = editor.document.createElement("div");
  20710. domUtils.setAttributes(dragLine, {
  20711. id: "ue_tableDragLine",
  20712. unselectable: 'on',
  20713. contenteditable: false,
  20714. 'onresizestart': 'return false',
  20715. 'ondragstart': 'return false',
  20716. 'onselectstart': 'return false',
  20717. style: "background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  20718. });
  20719. /*
  20720. *0428
  20721. *add:清除dragLine上的鼠标事件对自身的影响
  20722. * ****************************************/
  20723. dragLine.addEventListener('mouseenter', function () {
  20724. clearTimeout(dragLineHideTimer)
  20725. })
  20726. dragLine.addEventListener('mouseout', function () {
  20727. clearTimeout(dragLineHideTimer)
  20728. dragLineHideTimer = setTimeout(function () {
  20729. hideDragLine(editor);
  20730. }, 60)
  20731. })
  20732. dragLine.addEventListener('mousedown', function (e) {
  20733. // e.stopPropagation()
  20734. // e.preventDefault()
  20735. })
  20736. /************************************** */
  20737. editor.body.appendChild(dragLine);
  20738. }
  20739. function hideDragLine(editor) {
  20740. if (mousedown) return;
  20741. var line;
  20742. if (!editor.document) return
  20743. while (line = editor.document.getElementById('ue_tableDragLine')) {
  20744. domUtils.remove(line);
  20745. /*
  20746. *0428
  20747. *add:拖拽线消失时,去掉拖动的手势
  20748. *********************************/
  20749. editor.body.style.cursor = "text";
  20750. }
  20751. }
  20752. /**
  20753. * 依据state(v|h)在cell位置显示横线
  20754. * @param state
  20755. * @param cell
  20756. */
  20757. function showDragLineAt(state, cell) {
  20758. if (!cell) return;
  20759. var table = domUtils.findParentByTagName(cell, "table"),
  20760. caption = table.getElementsByTagName('caption'),
  20761. width = table.offsetWidth,
  20762. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  20763. tablePos = domUtils.getXY(table),
  20764. cellPos = domUtils.getXY(cell), css;
  20765. switch (state) {
  20766. case "h":
  20767. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  20768. // dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  20769. /*
  20770. *0428
  20771. *modify:添加禁止拖拽线的行为
  20772. ***************/
  20773. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:2px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30); pointer-events: none;';
  20774. break;
  20775. case "v":
  20776. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight);
  20777. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  20778. // dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:3px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20);';
  20779. /*
  20780. *0428
  20781. *modify:添加禁止拖拽线的行为
  20782. ***************/
  20783. dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:2px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20);pointer-events:none;';
  20784. break;
  20785. default:
  20786. }
  20787. }
  20788. /**
  20789. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  20790. * @param editor
  20791. * @param flag
  20792. */
  20793. function switchBorderColor(editor, flag) {
  20794. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  20795. for (var i = 0, node; node = tableArr[i++];) {
  20796. var td = domUtils.getElementsByTagName(node, "td");
  20797. if (td[0]) {
  20798. if (flag) {
  20799. color = (td[0].style.borderColor).replace(/\s/g, "");
  20800. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  20801. domUtils.addClass(node, "noBorderTable")
  20802. } else {
  20803. domUtils.removeClasses(node, "noBorderTable")
  20804. }
  20805. }
  20806. }
  20807. }
  20808. function getTableWidth(editor, needIEHack, defaultValue) {
  20809. var body = editor.body;
  20810. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  20811. }
  20812. /**
  20813. * 获取当前拖动的单元格
  20814. */
  20815. function getTargetTd(editor, evt) {
  20816. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  20817. dir = null;
  20818. if (!target) {
  20819. return null;
  20820. }
  20821. dir = getRelation(target, mouseCoords(evt));
  20822. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  20823. if (!target) {
  20824. return null;
  20825. }
  20826. if (dir === 'h1' && target.previousSibling) {
  20827. var position = domUtils.getXY(target),
  20828. cellWidth = target.offsetWidth;
  20829. if (Math.abs(position.x + cellWidth - evt.clientX) > cellWidth / 3) {
  20830. target = target.previousSibling;
  20831. }
  20832. } else if (dir === 'v1' && target.parentNode.previousSibling) {
  20833. var position = domUtils.getXY(target),
  20834. cellHeight = target.offsetHeight;
  20835. if (Math.abs(position.y + cellHeight - evt.clientY) > cellHeight / 3) {
  20836. target = target.parentNode.previousSibling.firstChild;
  20837. }
  20838. }
  20839. //排除了非td内部以及用于代码高亮部分的td
  20840. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  20841. }
  20842. };
  20843. // plugins/table.sort.js
  20844. /**
  20845. * Created with JetBrains PhpStorm.
  20846. * User: Jinqn
  20847. * Date: 13-10-12
  20848. * Time: 上午10:20
  20849. * To change this template use File | Settings | File Templates.
  20850. */
  20851. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  20852. var table = this.table,
  20853. rows = table.rows,
  20854. trArray = [],
  20855. flag = rows[0].cells[0].tagName === "TH",
  20856. lastRowIndex = 0;
  20857. if (this.selectedTds.length) {
  20858. var range = this.cellsRange,
  20859. len = range.endRowIndex + 1;
  20860. for (var i = range.beginRowIndex; i < len; i++) {
  20861. trArray[i] = rows[i];
  20862. }
  20863. trArray.splice(0, range.beginRowIndex);
  20864. lastRowIndex = (range.endRowIndex + 1) === this.rowsNum ? 0 : range.endRowIndex + 1;
  20865. } else {
  20866. for (var i = 0, len = rows.length; i < len; i++) {
  20867. trArray[i] = rows[i];
  20868. }
  20869. }
  20870. var Fn = {
  20871. 'reversecurrent': function (td1, td2) {
  20872. return 1;
  20873. },
  20874. 'orderbyasc': function (td1, td2) {
  20875. var value1 = td1.innerText || td1.textContent,
  20876. value2 = td2.innerText || td2.textContent;
  20877. return value1.localeCompare(value2);
  20878. },
  20879. 'reversebyasc': function (td1, td2) {
  20880. var value1 = td1.innerHTML,
  20881. value2 = td2.innerHTML;
  20882. return value2.localeCompare(value1);
  20883. },
  20884. 'orderbynum': function (td1, td2) {
  20885. var value1 = td1[browser.ie ? 'innerText' : 'textContent'].match(/\d+/),
  20886. value2 = td2[browser.ie ? 'innerText' : 'textContent'].match(/\d+/);
  20887. if (value1) value1 = +value1[0];
  20888. if (value2) value2 = +value2[0];
  20889. return (value1 || 0) - (value2 || 0);
  20890. },
  20891. 'reversebynum': function (td1, td2) {
  20892. var value1 = td1[browser.ie ? 'innerText' : 'textContent'].match(/\d+/),
  20893. value2 = td2[browser.ie ? 'innerText' : 'textContent'].match(/\d+/);
  20894. if (value1) value1 = +value1[0];
  20895. if (value2) value2 = +value2[0];
  20896. return (value2 || 0) - (value1 || 0);
  20897. }
  20898. };
  20899. //对表格设置排序的标记data-sort-type
  20900. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn : '');
  20901. //th不参与排序
  20902. flag && trArray.splice(0, 1);
  20903. trArray = utils.sort(trArray, function (tr1, tr2) {
  20904. var result;
  20905. if (compareFn && typeof compareFn === "function") {
  20906. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20907. } else if (compareFn && typeof compareFn === "number") {
  20908. result = 1;
  20909. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  20910. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20911. } else {
  20912. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20913. }
  20914. return result;
  20915. });
  20916. var fragment = table.ownerDocument.createDocumentFragment();
  20917. for (var j = 0, len = trArray.length; j < len; j++) {
  20918. fragment.appendChild(trArray[j]);
  20919. }
  20920. var tbody = table.getElementsByTagName("tbody")[0];
  20921. if (!lastRowIndex) {
  20922. tbody.appendChild(fragment);
  20923. } else {
  20924. tbody.insertBefore(fragment, rows[lastRowIndex - range.endRowIndex + range.beginRowIndex - 1])
  20925. }
  20926. };
  20927. UE.plugins['tablesort'] = function() {
  20928. var me = this,
  20929. UT = UE.UETable,
  20930. getUETable = function(tdOrTable) {
  20931. return UT.getUETable(tdOrTable);
  20932. },
  20933. getTableItemsByRange = function(editor) {
  20934. return UT.getTableItemsByRange(editor);
  20935. };
  20936. me.ready(function() {
  20937. //添加表格可排序的样式
  20938. utils.cssRule('tablesort',
  20939. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20940. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20941. me.document);
  20942. //做单元格合并操作时,清除可排序标识
  20943. me.addListener("afterexeccommand", function (type, cmd) {
  20944. if (cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20945. this.execCommand('disablesort');
  20946. }
  20947. });
  20948. });
  20949. //表格排序
  20950. UE.commands['sorttable'] = {
  20951. queryCommandState: function () {
  20952. var me = this,
  20953. tableItems = getTableItemsByRange(me);
  20954. if (!tableItems.cell) return -1;
  20955. var table = tableItems.table,
  20956. cells = table.getElementsByTagName("td");
  20957. for (var i = 0, cell; cell = cells[i++];) {
  20958. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20959. }
  20960. return 0;
  20961. },
  20962. execCommand: function (cmd, fn) {
  20963. var me = this,
  20964. range = me.selection.getRange(),
  20965. bk = range.createBookmark(true),
  20966. tableItems = getTableItemsByRange(me),
  20967. cell = tableItems.cell,
  20968. ut = getUETable(tableItems.table),
  20969. cellInfo = ut.getCellInfo(cell);
  20970. ut.sortTable(cellInfo.cellIndex, fn);
  20971. range.moveToBookmark(bk);
  20972. try {
  20973. range.select();
  20974. } catch (e) {
  20975. }
  20976. }
  20977. };
  20978. //设置表格可排序,清除表格可排序
  20979. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20980. queryCommandState: function (cmd) {
  20981. var table = getTableItemsByRange(this).table;
  20982. if (table && cmd == 'enablesort') {
  20983. var cells = domUtils.getElementsByTagName(table, 'th td');
  20984. for (var i = 0; i < cells.length; i++) {
  20985. if (cells[i].getAttribute('colspan') > 1 || cells[i].getAttribute('rowspan') > 1) return -1;
  20986. }
  20987. }
  20988. return !table ? -1 : cmd == 'enablesort' ^ table.getAttribute('data-sort') != 'sortEnabled' ? -1 : 0;
  20989. },
  20990. execCommand: function (cmd) {
  20991. var table = getTableItemsByRange(this).table;
  20992. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20993. cmd == "enablesort" ? domUtils.addClass(table, "sortEnabled") : domUtils.removeClasses(table, "sortEnabled");
  20994. }
  20995. };
  20996. };
  20997. // plugins/contextmenu.js
  20998. ///import core
  20999. ///commands 右键菜单
  21000. ///commandsName ContextMenu
  21001. ///commandsTitle 右键菜单
  21002. /**
  21003. * 右键菜单
  21004. * @function
  21005. * @name baidu.editor.plugins.contextmenu
  21006. * @author zhanyi
  21007. */
  21008. UE.plugins['contextmenu'] = function () {
  21009. var me = this;
  21010. me.setOpt('enableContextMenu', true);
  21011. if (me.getOpt('enableContextMenu') === false) {
  21012. return;
  21013. }
  21014. var lang = me.getLang("contextMenu"),
  21015. menu,
  21016. items = me.options.contextMenu || [
  21017. {label: lang['selectall'], cmdName: 'selectall'},
  21018. {
  21019. label: lang.cleardoc,
  21020. cmdName: 'cleardoc',
  21021. exec: function () {
  21022. if (confirm(lang.confirmclear)) {
  21023. this.execCommand('cleardoc');
  21024. }
  21025. }
  21026. },
  21027. '-',
  21028. {
  21029. label: lang.unlink,
  21030. cmdName: 'unlink'
  21031. },
  21032. '-',
  21033. {
  21034. group: lang.paragraph,
  21035. icon: 'justifyjustify',
  21036. subMenu: [
  21037. {
  21038. label: lang.justifyleft,
  21039. cmdName: 'justify',
  21040. value: 'left'
  21041. },
  21042. {
  21043. label: lang.justifyright,
  21044. cmdName: 'justify',
  21045. value: 'right'
  21046. },
  21047. {
  21048. label: lang.justifycenter,
  21049. cmdName: 'justify',
  21050. value: 'center'
  21051. },
  21052. {
  21053. label: lang.justifyjustify,
  21054. cmdName: 'justify',
  21055. value: 'justify'
  21056. }
  21057. ]
  21058. },
  21059. '-',
  21060. {
  21061. group: lang.table,
  21062. icon: 'table',
  21063. subMenu: [
  21064. {
  21065. label: lang.inserttable,
  21066. cmdName: 'inserttable'
  21067. },
  21068. {
  21069. label: lang.deletetable,
  21070. cmdName: 'deletetable'
  21071. },
  21072. '-',
  21073. {
  21074. label: lang.deleterow,
  21075. cmdName: 'deleterow'
  21076. },
  21077. {
  21078. label: lang.deletecol,
  21079. cmdName: 'deletecol'
  21080. },
  21081. {
  21082. label: lang.insertcol,
  21083. cmdName: 'insertcol'
  21084. },
  21085. {
  21086. label: lang.insertcolnext,
  21087. cmdName: 'insertcolnext'
  21088. },
  21089. {
  21090. label: lang.insertrow,
  21091. cmdName: 'insertrow'
  21092. },
  21093. {
  21094. label: lang.insertrownext,
  21095. cmdName: 'insertrownext'
  21096. },
  21097. '-',
  21098. {
  21099. label: lang.insertcaption,
  21100. cmdName: 'insertcaption'
  21101. },
  21102. {
  21103. label: lang.deletecaption,
  21104. cmdName: 'deletecaption'
  21105. },
  21106. {
  21107. label: lang.inserttitle,
  21108. cmdName: 'inserttitle'
  21109. },
  21110. {
  21111. label: lang.deletetitle,
  21112. cmdName: 'deletetitle'
  21113. },
  21114. {
  21115. label: lang.inserttitlecol,
  21116. cmdName: 'inserttitlecol'
  21117. },
  21118. {
  21119. label: lang.deletetitlecol,
  21120. cmdName: 'deletetitlecol'
  21121. },
  21122. '-',
  21123. {
  21124. label: lang.mergecells,
  21125. cmdName: 'mergecells'
  21126. },
  21127. {
  21128. label: lang.mergeright,
  21129. cmdName: 'mergeright'
  21130. },
  21131. {
  21132. label: lang.mergedown,
  21133. cmdName: 'mergedown'
  21134. },
  21135. '-',
  21136. {
  21137. label: lang.splittorows,
  21138. cmdName: 'splittorows'
  21139. },
  21140. {
  21141. label: lang.splittocols,
  21142. cmdName: 'splittocols'
  21143. },
  21144. {
  21145. label: lang.splittocells,
  21146. cmdName: 'splittocells'
  21147. },
  21148. '-',
  21149. {
  21150. label: lang.averageDiseRow,
  21151. cmdName: 'averagedistributerow'
  21152. },
  21153. {
  21154. label: lang.averageDisCol,
  21155. cmdName: 'averagedistributecol'
  21156. },
  21157. '-',
  21158. {
  21159. label: lang.edittd,
  21160. cmdName: 'edittd',
  21161. exec: function () {
  21162. if (UE.ui['edittd']) {
  21163. new UE.ui['edittd'](this);
  21164. }
  21165. this.getDialog('edittd').open();
  21166. }
  21167. },
  21168. {
  21169. label: lang.edittable,
  21170. cmdName: 'edittable',
  21171. exec: function () {
  21172. if (UE.ui['edittable']) {
  21173. new UE.ui['edittable'](this);
  21174. }
  21175. this.getDialog('edittable').open();
  21176. }
  21177. },
  21178. {
  21179. label: lang.setbordervisible,
  21180. cmdName: 'setbordervisible'
  21181. }
  21182. ]
  21183. },
  21184. {
  21185. group: lang.tablesort,
  21186. icon: 'tablesort',
  21187. subMenu: [
  21188. {
  21189. label: lang.enablesort,
  21190. cmdName: 'enablesort'
  21191. },
  21192. {
  21193. label: lang.disablesort,
  21194. cmdName: 'disablesort'
  21195. },
  21196. '-',
  21197. {
  21198. label: lang.reversecurrent,
  21199. cmdName: 'sorttable',
  21200. value: 'reversecurrent'
  21201. },
  21202. {
  21203. label: lang.orderbyasc,
  21204. cmdName: 'sorttable',
  21205. value: 'orderbyasc'
  21206. },
  21207. {
  21208. label: lang.reversebyasc,
  21209. cmdName: 'sorttable',
  21210. value: 'reversebyasc'
  21211. },
  21212. {
  21213. label: lang.orderbynum,
  21214. cmdName: 'sorttable',
  21215. value: 'orderbynum'
  21216. },
  21217. {
  21218. label: lang.reversebynum,
  21219. cmdName: 'sorttable',
  21220. value: 'reversebynum'
  21221. }
  21222. ]
  21223. },
  21224. {
  21225. group: lang.borderbk,
  21226. icon: 'borderBack',
  21227. subMenu: [
  21228. {
  21229. label: lang.setcolor,
  21230. cmdName: "interlacetable",
  21231. exec: function () {
  21232. this.execCommand("interlacetable");
  21233. }
  21234. },
  21235. {
  21236. label: lang.unsetcolor,
  21237. cmdName: "uninterlacetable",
  21238. exec: function () {
  21239. this.execCommand("uninterlacetable");
  21240. }
  21241. },
  21242. {
  21243. label: lang.setbackground,
  21244. cmdName: "settablebackground",
  21245. exec: function () {
  21246. this.execCommand("settablebackground", {repeat: true, colorList: ["#bbb", "#ccc"]});
  21247. }
  21248. },
  21249. {
  21250. label: lang.unsetbackground,
  21251. cmdName: "cleartablebackground",
  21252. exec: function () {
  21253. this.execCommand("cleartablebackground");
  21254. }
  21255. },
  21256. {
  21257. label: lang.redandblue,
  21258. cmdName: "settablebackground",
  21259. exec: function () {
  21260. this.execCommand("settablebackground", {repeat: true, colorList: ["red", "blue"]});
  21261. }
  21262. },
  21263. {
  21264. label: lang.threecolorgradient,
  21265. cmdName: "settablebackground",
  21266. exec: function () {
  21267. this.execCommand("settablebackground", {
  21268. repeat: true,
  21269. colorList: ["#aaa", "#bbb", "#ccc"]
  21270. });
  21271. }
  21272. }
  21273. ]
  21274. },
  21275. {
  21276. group: lang.aligntd,
  21277. icon: 'aligntd',
  21278. subMenu: [
  21279. {
  21280. cmdName: 'cellalignment',
  21281. value: {align: 'left', vAlign: 'top'}
  21282. },
  21283. {
  21284. cmdName: 'cellalignment',
  21285. value: {align: 'center', vAlign: 'top'}
  21286. },
  21287. {
  21288. cmdName: 'cellalignment',
  21289. value: {align: 'right', vAlign: 'top'}
  21290. },
  21291. {
  21292. cmdName: 'cellalignment',
  21293. value: {align: 'left', vAlign: 'middle'}
  21294. },
  21295. {
  21296. cmdName: 'cellalignment',
  21297. value: {align: 'center', vAlign: 'middle'}
  21298. },
  21299. {
  21300. cmdName: 'cellalignment',
  21301. value: {align: 'right', vAlign: 'middle'}
  21302. },
  21303. {
  21304. cmdName: 'cellalignment',
  21305. value: {align: 'left', vAlign: 'bottom'}
  21306. },
  21307. {
  21308. cmdName: 'cellalignment',
  21309. value: {align: 'center', vAlign: 'bottom'}
  21310. },
  21311. {
  21312. cmdName: 'cellalignment',
  21313. value: {align: 'right', vAlign: 'bottom'}
  21314. }
  21315. ]
  21316. },
  21317. {
  21318. group: lang.aligntable,
  21319. icon: 'aligntable',
  21320. subMenu: [
  21321. {
  21322. cmdName: 'tablealignment',
  21323. className: 'left',
  21324. label: lang.tableleft,
  21325. value: "left"
  21326. },
  21327. {
  21328. cmdName: 'tablealignment',
  21329. className: 'center',
  21330. label: lang.tablecenter,
  21331. value: "center"
  21332. },
  21333. {
  21334. cmdName: 'tablealignment',
  21335. className: 'right',
  21336. label: lang.tableright,
  21337. value: "right"
  21338. }
  21339. ]
  21340. },
  21341. '-',
  21342. {
  21343. label: lang.insertparagraphbefore,
  21344. cmdName: 'insertparagraph',
  21345. value: true
  21346. },
  21347. {
  21348. label: lang.insertparagraphafter,
  21349. cmdName: 'insertparagraph'
  21350. },
  21351. {
  21352. label: lang['copy'],
  21353. cmdName: 'copy'
  21354. },
  21355. {
  21356. label: lang['paste'],
  21357. cmdName: 'paste'
  21358. }
  21359. ];
  21360. if (!items.length) {
  21361. return;
  21362. }
  21363. var uiUtils = UE.ui.uiUtils;
  21364. me.addListener('contextmenu', function(type, evt) {
  21365. var offset = uiUtils.getViewportOffsetByEvent(evt);
  21366. me.fireEvent('beforeselectionchange');
  21367. if (menu) {
  21368. menu.destroy();
  21369. }
  21370. for (var i = 0, ti, contextItems = []; ti = items[i]; i++) {
  21371. var last;
  21372. (function (item) {
  21373. if (item == '-') {
  21374. if ((last = contextItems[contextItems.length - 1]) && last !== '-') {
  21375. contextItems.push('-');
  21376. }
  21377. } else if (item.hasOwnProperty("group")) {
  21378. for (var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++) {
  21379. (function (subItem) {
  21380. if (subItem == '-') {
  21381. if ((last = subMenu[subMenu.length - 1]) && last !== '-') {
  21382. subMenu.push('-');
  21383. } else {
  21384. subMenu.splice(subMenu.length - 1);
  21385. }
  21386. } else {
  21387. if ((me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  21388. (subItem.query ? subItem.query() : me.queryCommandState(subItem.cmdName)) > -1) {
  21389. subMenu.push({
  21390. 'label': subItem.label || me.getLang("contextMenu." + subItem.cmdName + (subItem.value || '')) || "",
  21391. 'className': 'edui-for-' + subItem.cmdName + (subItem.className ? (' edui-for-' + subItem.cmdName + '-' + subItem.className) : ''),
  21392. onclick: subItem.exec ? function () {
  21393. subItem.exec.call(me);
  21394. } : function () {
  21395. me.execCommand(subItem.cmdName, subItem.value);
  21396. }
  21397. });
  21398. }
  21399. }
  21400. })(cj);
  21401. }
  21402. if (subMenu.length) {
  21403. function getLabel() {
  21404. switch (item.icon) {
  21405. case "table":
  21406. return me.getLang("contextMenu.table");
  21407. case "justifyjustify":
  21408. return me.getLang("contextMenu.paragraph");
  21409. case "aligntd":
  21410. return me.getLang("contextMenu.aligntd");
  21411. case "aligntable":
  21412. return me.getLang("contextMenu.aligntable");
  21413. case "tablesort":
  21414. return lang.tablesort;
  21415. case "borderBack":
  21416. return lang.borderbk;
  21417. default:
  21418. return '';
  21419. }
  21420. }
  21421. contextItems.push({
  21422. //todo 修正成自动获取方式
  21423. 'label': getLabel(),
  21424. className: 'edui-for-' + item.icon,
  21425. 'subMenu': {
  21426. items: subMenu,
  21427. editor: me
  21428. }
  21429. });
  21430. }
  21431. } else {
  21432. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  21433. if ((me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  21434. (item.query ? item.query.call(me) : me.queryCommandState(item.cmdName)) > -1) {
  21435. contextItems.push({
  21436. 'label': item.label || me.getLang("contextMenu." + item.cmdName),
  21437. className: 'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  21438. onclick: item.exec ? function () {
  21439. item.exec.call(me);
  21440. } : function () {
  21441. me.execCommand(item.cmdName, item.value);
  21442. }
  21443. });
  21444. }
  21445. }
  21446. })(ti);
  21447. }
  21448. if (contextItems[contextItems.length - 1] == '-') {
  21449. contextItems.pop();
  21450. }
  21451. menu = new UE.ui.Menu({
  21452. items: contextItems,
  21453. className: "edui-contextmenu",
  21454. editor: me
  21455. });
  21456. menu.render();
  21457. menu.showAt(offset);
  21458. me.fireEvent("aftershowcontextmenu", menu);
  21459. domUtils.preventDefault(evt);
  21460. if (browser.ie) {
  21461. var ieRange;
  21462. try {
  21463. ieRange = me.selection.getNative().createRange();
  21464. } catch (e) {
  21465. return;
  21466. }
  21467. if (ieRange.item) {
  21468. var range = new dom.Range(me.document);
  21469. range.selectNode(ieRange.item(0)).select(true, true);
  21470. }
  21471. }
  21472. });
  21473. // 添加复制的flash按钮
  21474. me.addListener('aftershowcontextmenu', function(type, menu) {
  21475. if (me.zeroclipboard) {
  21476. var items = menu.items;
  21477. for (var key in items) {
  21478. if (items[key].className == 'edui-for-copy') {
  21479. me.zeroclipboard.clip(items[key].getDom());
  21480. }
  21481. }
  21482. }
  21483. });
  21484. };
  21485. // plugins/shortcutmenu.js
  21486. ///import core
  21487. ///commands 弹出菜单
  21488. // commandsName popupmenu
  21489. ///commandsTitle 弹出菜单
  21490. /**
  21491. * 弹出菜单
  21492. * @function
  21493. * @name baidu.editor.plugins.popupmenu
  21494. * @author xuheng
  21495. */
  21496. UE.plugins['shortcutmenu'] = function() {
  21497. var me = this,
  21498. menu,
  21499. items = me.options.shortcutMenu || [];
  21500. if (!items.length) {
  21501. return;
  21502. }
  21503. me.addListener('contextmenu mouseup', function (type, e) {
  21504. var me = this,
  21505. customEvt = {
  21506. type: type,
  21507. target: e.target || e.srcElement,
  21508. screenX: e.screenX,
  21509. screenY: e.screenY,
  21510. clientX: e.clientX,
  21511. clientY: e.clientY
  21512. };
  21513. setTimeout(function () {
  21514. var rng = me.selection.getRange();
  21515. if (rng.collapsed === false || type == "contextmenu") {
  21516. if (!menu) {
  21517. menu = new baidu.editor.ui.ShortCutMenu({
  21518. editor: me,
  21519. items: items,
  21520. theme: me.options.theme,
  21521. className: 'edui-shortcutmenu'
  21522. });
  21523. menu.render();
  21524. me.fireEvent("afterrendershortcutmenu", menu);
  21525. }
  21526. menu.show(customEvt, !!UE.plugins['contextmenu']);
  21527. }
  21528. });
  21529. if (type == 'contextmenu') {
  21530. domUtils.preventDefault(e);
  21531. if (browser.ie9below) {
  21532. var ieRange;
  21533. try {
  21534. ieRange = me.selection.getNative().createRange();
  21535. } catch (e) {
  21536. return;
  21537. }
  21538. if (ieRange.item) {
  21539. var range = new dom.Range(me.document);
  21540. range.selectNode(ieRange.item(0)).select(true, true);
  21541. }
  21542. }
  21543. }
  21544. });
  21545. me.addListener('keydown', function (type) {
  21546. if (type == "keydown") {
  21547. menu && !menu.isHidden && menu.hide();
  21548. }
  21549. });
  21550. };
  21551. // plugins/basestyle.js
  21552. /**
  21553. * B、I、sub、super命令支持
  21554. * @file
  21555. * @since 1.2.6.1
  21556. */
  21557. UE.plugins['basestyle'] = function() {
  21558. /**
  21559. * 字体加粗
  21560. * @command bold
  21561. * @param { String } cmd 命令字符串
  21562. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  21563. * @method execCommand
  21564. * @example
  21565. * ```javascript
  21566. * //editor是编辑器实例
  21567. * //对当前选中的文本内容执行加粗操作
  21568. * //第一次执行, 文本内容加粗
  21569. * editor.execCommand( 'bold' );
  21570. *
  21571. * //第二次执行, 文本内容取消加粗
  21572. * editor.execCommand( 'bold' );
  21573. * ```
  21574. */
  21575. /**
  21576. * 字体倾斜
  21577. * @command italic
  21578. * @method execCommand
  21579. * @param { String } cmd 命令字符串
  21580. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  21581. * @example
  21582. * ```javascript
  21583. * //editor是编辑器实例
  21584. * //对当前选中的文本内容执行斜体操作
  21585. * //第一次操作, 文本内容将变成斜体
  21586. * editor.execCommand( 'italic' );
  21587. *
  21588. * //再次对同一文本内容执行, 则文本内容将恢复正常
  21589. * editor.execCommand( 'italic' );
  21590. * ```
  21591. */
  21592. /**
  21593. * 下标文本,与“superscript”命令互斥
  21594. * @command subscript
  21595. * @method execCommand
  21596. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  21597. * @param { String } cmd 命令字符串
  21598. * @example
  21599. * ```javascript
  21600. * //editor是编辑器实例
  21601. * //对当前选中的文本内容执行下标操作
  21602. * //第一次操作, 文本内容将变成下标文本
  21603. * editor.execCommand( 'subscript' );
  21604. *
  21605. * //再次对同一文本内容执行, 则文本内容将恢复正常
  21606. * editor.execCommand( 'subscript' );
  21607. * ```
  21608. */
  21609. /**
  21610. * 上标文本,与“subscript”命令互斥
  21611. * @command superscript
  21612. * @method execCommand
  21613. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  21614. * @param { String } cmd 命令字符串
  21615. * @example
  21616. * ```javascript
  21617. * //editor是编辑器实例
  21618. * //对当前选中的文本内容执行上标操作
  21619. * //第一次操作, 文本内容将变成上标文本
  21620. * editor.execCommand( 'superscript' );
  21621. *
  21622. * //再次对同一文本内容执行, 则文本内容将恢复正常
  21623. * editor.execCommand( 'superscript' );
  21624. * ```
  21625. */
  21626. var basestyles = {
  21627. 'bold': ['strong', 'b'],
  21628. 'italic': ['em', 'i'],
  21629. 'subscript': ['sub'],
  21630. 'superscript': ['sup']
  21631. },
  21632. getObj = function (editor, tagNames) {
  21633. return domUtils.filterNodeList(editor.selection.getStartElementPath(), tagNames);
  21634. },
  21635. me = this;
  21636. //添加快捷键
  21637. me.addshortcutkey({
  21638. "Bold": "ctrl+66",//^B
  21639. "Italic": "ctrl+73", //^I
  21640. "Underline": "ctrl+85"//^U
  21641. });
  21642. me.addInputRule(function (root) {
  21643. utils.each(root.getNodesByTagName('b i'), function (node) {
  21644. switch (node.tagName) {
  21645. case 'b':
  21646. node.tagName = 'strong';
  21647. break;
  21648. case 'i':
  21649. node.tagName = 'em';
  21650. }
  21651. });
  21652. });
  21653. for (var style in basestyles) {
  21654. (function (cmd, tagNames) {
  21655. me.commands[cmd] = {
  21656. execCommand: function (cmdName) {
  21657. var range = me.selection.getRange(), obj = getObj(this, tagNames);
  21658. if (range.collapsed) {
  21659. if (obj) {
  21660. var tmpText = me.document.createTextNode('');
  21661. range.insertNode(tmpText).removeInlineStyle(tagNames);
  21662. range.setStartBefore(tmpText);
  21663. domUtils.remove(tmpText);
  21664. } else {
  21665. var tmpNode = range.document.createElement(tagNames[0]);
  21666. if (cmdName == 'superscript' || cmdName == 'subscript') {
  21667. tmpText = me.document.createTextNode('');
  21668. range.insertNode(tmpText)
  21669. .removeInlineStyle(['sub', 'sup'])
  21670. .setStartBefore(tmpText)
  21671. .collapse(true);
  21672. }
  21673. range.insertNode(tmpNode).setStart(tmpNode, 0);
  21674. }
  21675. range.collapse(true);
  21676. } else {
  21677. if (cmdName == 'superscript' || cmdName == 'subscript') {
  21678. if (!obj || obj.tagName.toLowerCase() != cmdName) {
  21679. range.removeInlineStyle(['sub', 'sup']);
  21680. }
  21681. }
  21682. obj ? range.removeInlineStyle(tagNames) : range.applyInlineStyle(tagNames[0]);
  21683. }
  21684. range.select();
  21685. },
  21686. queryCommandState: function () {
  21687. return getObj(this, tagNames) ? 1 : 0;
  21688. }
  21689. };
  21690. })(style, basestyles[style]);
  21691. }
  21692. };
  21693. // plugins/elementpath.js
  21694. /**
  21695. * 选取路径命令
  21696. * @file
  21697. */
  21698. UE.plugins['elementpath'] = function () {
  21699. var currentLevel,
  21700. tagNames,
  21701. me = this;
  21702. me.setOpt('elementPathEnabled', true);
  21703. if (!me.options.elementPathEnabled) {
  21704. return;
  21705. }
  21706. me.commands['elementpath'] = {
  21707. execCommand: function (cmdName, level) {
  21708. var start = tagNames[level],
  21709. range = me.selection.getRange();
  21710. currentLevel = level * 1;
  21711. range.selectNode(start).select();
  21712. },
  21713. queryCommandValue: function () {
  21714. //产生一个副本,不能修改原来的startElementPath;
  21715. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  21716. names = [];
  21717. tagNames = parents;
  21718. for (var i = 0, ci; ci = parents[i]; i++) {
  21719. if (ci.nodeType == 3) {
  21720. continue;
  21721. }
  21722. var name = ci.tagName.toLowerCase();
  21723. if (name == 'img' && ci.getAttribute('anchorname')) {
  21724. name = 'anchor';
  21725. }
  21726. names[i] = name;
  21727. if (currentLevel == i) {
  21728. currentLevel = -1;
  21729. break;
  21730. }
  21731. }
  21732. return names;
  21733. }
  21734. };
  21735. };
  21736. // plugins/formatmatch.js
  21737. /**
  21738. * 格式刷,只格式inline的
  21739. * @file
  21740. * @since 1.2.6.1
  21741. */
  21742. /**
  21743. * 格式刷
  21744. * @command formatmatch
  21745. * @method execCommand
  21746. * @remind 该操作不能复制段落格式
  21747. * @param { String } cmd 命令字符串
  21748. * @example
  21749. * ```javascript
  21750. * //editor是编辑器实例
  21751. * //获取格式刷
  21752. * editor.execCommand( 'formatmatch' );
  21753. * ```
  21754. */
  21755. UE.plugins['formatmatch'] = function() {
  21756. var me = this,
  21757. list = [], img,
  21758. flag = 0;
  21759. me.addListener('reset', function() {
  21760. list = [];
  21761. flag = 0;
  21762. });
  21763. function addList(type, evt) {
  21764. if (browser.webkit) {
  21765. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  21766. }
  21767. function addFormat(range) {
  21768. if (text) {
  21769. range.selectNode(text);
  21770. }
  21771. return range.applyInlineStyle(list[list.length - 1].tagName, null, list);
  21772. }
  21773. me.undoManger && me.undoManger.save();
  21774. var range = me.selection.getRange(),
  21775. imgT = target || range.getClosedNode();
  21776. if (img && imgT && imgT.tagName == 'IMG') {
  21777. //trace:964
  21778. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat || 'none') + ';display:' + (img.style.display || 'inline');
  21779. img = null;
  21780. } else {
  21781. if (!img) {
  21782. var collapsed = range.collapsed;
  21783. if (collapsed) {
  21784. var text = me.document.createTextNode('match');
  21785. range.insertNode(text).select();
  21786. }
  21787. me.__hasEnterExecCommand = true;
  21788. //不能把block上的属性干掉
  21789. //trace:1553
  21790. var removeFormatAttributes = me.options.removeFormatAttributes;
  21791. me.options.removeFormatAttributes = '';
  21792. me.execCommand('removeformat');
  21793. me.options.removeFormatAttributes = removeFormatAttributes;
  21794. me.__hasEnterExecCommand = false;
  21795. //trace:969
  21796. range = me.selection.getRange();
  21797. if (list.length) {
  21798. addFormat(range);
  21799. }
  21800. if (text) {
  21801. range.setStartBefore(text).collapse(true);
  21802. }
  21803. range.select();
  21804. text && domUtils.remove(text);
  21805. }
  21806. }
  21807. me.undoManger && me.undoManger.save();
  21808. me.removeListener('mouseup', addList);
  21809. flag = 0;
  21810. }
  21811. me.commands['formatmatch'] = {
  21812. execCommand: function(cmdName) {
  21813. if (flag) {
  21814. flag = 0;
  21815. list = [];
  21816. me.removeListener('mouseup', addList);
  21817. return;
  21818. }
  21819. var range = me.selection.getRange();
  21820. img = range.getClosedNode();
  21821. if (!img || img.tagName != 'IMG') {
  21822. range.collapse(true).shrinkBoundary();
  21823. var start = range.startContainer;
  21824. list = domUtils.findParents(start, true, function(node) {
  21825. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  21826. });
  21827. //a不能加入格式刷, 并且克隆节点
  21828. for (var i = 0, ci; ci = list[i]; i++) {
  21829. if (ci.tagName == 'A') {
  21830. list.splice(i, 1);
  21831. break;
  21832. }
  21833. }
  21834. }
  21835. me.addListener('mouseup', addList);
  21836. flag = 1;
  21837. },
  21838. queryCommandState: function () {
  21839. return flag;
  21840. },
  21841. notNeedUndo: 1
  21842. };
  21843. };
  21844. // plugins/searchreplace.js
  21845. ///import core
  21846. ///commands 查找替换
  21847. ///commandsName SearchReplace
  21848. ///commandsTitle 查询替换
  21849. ///commandsDialog dialogs\searchreplace
  21850. /**
  21851. * @description 查找替换
  21852. * @author zhanyi
  21853. */
  21854. UE.plugin.register('searchreplace', function() {
  21855. var me = this;
  21856. var _blockElm = { 'table': 1, 'tbody': 1, 'tr': 1, 'ol': 1, 'ul': 1 };
  21857. function findTextInString(textContent, opt, currentIndex) {
  21858. var str = opt.searchStr;
  21859. if (opt.dir == -1) {
  21860. textContent = textContent.split('').reverse().join('');
  21861. str = str.split('').reverse().join('');
  21862. currentIndex = textContent.length - currentIndex;
  21863. }
  21864. var reg = new RegExp(str, 'g' + (opt.casesensitive ? '' : 'i')), match;
  21865. while (match = reg.exec(textContent)) {
  21866. if (match.index >= currentIndex) {
  21867. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  21868. }
  21869. }
  21870. return -1
  21871. }
  21872. function findTextBlockElm(node, currentIndex, opt) {
  21873. var textContent, index, methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  21874. if (domUtils.isBody(node)) {
  21875. node = node.firstChild;
  21876. }
  21877. var first = 1;
  21878. while (node) {
  21879. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  21880. index = findTextInString(textContent, opt, currentIndex);
  21881. first = 0;
  21882. if (index != -1) {
  21883. return {
  21884. 'node': node,
  21885. 'index': index
  21886. }
  21887. }
  21888. node = domUtils[methodName](node);
  21889. while (node && _blockElm[node.nodeName.toLowerCase()]) {
  21890. node = domUtils[methodName](node, true);
  21891. }
  21892. if (node) {
  21893. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  21894. }
  21895. }
  21896. }
  21897. function findNTextInBlockElm(node, index, str) {
  21898. var currentIndex = 0,
  21899. currentNode = node.firstChild,
  21900. currentNodeLength = 0,
  21901. result;
  21902. while (currentNode) {
  21903. if (currentNode.nodeType == 3) {
  21904. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/, '').length;
  21905. currentIndex += currentNodeLength;
  21906. if (currentIndex >= index) {
  21907. return {
  21908. 'node': currentNode,
  21909. 'index': currentNodeLength - (currentIndex - index)
  21910. }
  21911. }
  21912. } else if (!dtd.$empty[currentNode.tagName]) {
  21913. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/, '').length
  21914. currentIndex += currentNodeLength;
  21915. if (currentIndex >= index) {
  21916. result = findNTextInBlockElm(currentNode, currentNodeLength - (currentIndex - index), str);
  21917. if (result) {
  21918. return result;
  21919. }
  21920. }
  21921. }
  21922. currentNode = domUtils.getNextDomNode(currentNode);
  21923. }
  21924. }
  21925. function searchReplace(me, opt) {
  21926. var rng = me.selection.getRange(),
  21927. startBlockNode,
  21928. searchStr = opt.searchStr,
  21929. span = me.document.createElement('span');
  21930. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21931. rng.shrinkBoundary(true);
  21932. //判断是不是第一次选中
  21933. if (!rng.collapsed) {
  21934. rng.select();
  21935. var rngText = me.selection.getText();
  21936. if (new RegExp('^' + opt.searchStr + '$', (opt.casesensitive ? '' : 'i')).test(rngText)) {
  21937. if (opt.replaceStr != undefined) {
  21938. replaceText(rng, opt.replaceStr);
  21939. rng.select();
  21940. return true;
  21941. } else {
  21942. rng.collapse(opt.dir == -1)
  21943. }
  21944. }
  21945. }
  21946. rng.insertNode(span);
  21947. rng.enlargeToBlockElm(true);
  21948. startBlockNode = rng.startContainer;
  21949. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21950. rng.setStartBefore(span);
  21951. domUtils.remove(span);
  21952. var result = findTextBlockElm(startBlockNode, currentIndex, opt);
  21953. if (result) {
  21954. var rngStart = findNTextInBlockElm(result.node, result.index, searchStr);
  21955. var rngEnd = findNTextInBlockElm(result.node, result.index + searchStr.length, searchStr);
  21956. rng.setStart(rngStart.node, rngStart.index).setEnd(rngEnd.node, rngEnd.index);
  21957. if (opt.replaceStr !== undefined) {
  21958. replaceText(rng, opt.replaceStr)
  21959. }
  21960. rng.select();
  21961. return true;
  21962. } else {
  21963. rng.setCursor()
  21964. }
  21965. }
  21966. function replaceText(rng, str) {
  21967. str = me.document.createTextNode(str);
  21968. rng.deleteContents().insertNode(str);
  21969. }
  21970. return {
  21971. commands: {
  21972. 'searchreplace': {
  21973. execCommand: function (cmdName, opt) {
  21974. utils.extend(opt, {
  21975. all: false,
  21976. casesensitive: false,
  21977. dir: 1
  21978. }, true);
  21979. var num = 0;
  21980. if (opt.all) {
  21981. var rng = me.selection.getRange(),
  21982. first = me.body.firstChild;
  21983. if (first && first.nodeType == 1) {
  21984. rng.setStart(first, 0);
  21985. rng.shrinkBoundary(true);
  21986. } else if (first.nodeType == 3) {
  21987. rng.setStartBefore(first)
  21988. }
  21989. rng.collapse(true).select(true);
  21990. if (opt.replaceStr !== undefined) {
  21991. me.fireEvent('saveScene');
  21992. }
  21993. while (searchReplace(this, opt)) {
  21994. num++;
  21995. }
  21996. if (num) {
  21997. me.fireEvent('saveScene');
  21998. }
  21999. } else {
  22000. if (opt.replaceStr !== undefined) {
  22001. me.fireEvent('saveScene');
  22002. }
  22003. if (searchReplace(this, opt)) {
  22004. num++
  22005. }
  22006. if (num) {
  22007. me.fireEvent('saveScene');
  22008. }
  22009. }
  22010. return num;
  22011. },
  22012. notNeedUndo: 1
  22013. }
  22014. }
  22015. }
  22016. });
  22017. // plugins/customstyle.js
  22018. /**
  22019. * 自定义样式
  22020. * @file
  22021. * @since 1.2.6.1
  22022. */
  22023. /**
  22024. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  22025. * @command customstyle
  22026. * @method execCommand
  22027. * @param { String } cmd 命令字符串
  22028. * @example
  22029. * ```javascript
  22030. * editor.execCommand( 'customstyle' );
  22031. * ```
  22032. */
  22033. UE.plugins['customstyle'] = function () {
  22034. var me = this;
  22035. me.setOpt({
  22036. 'customstyle': [
  22037. {
  22038. tag: 'h1',
  22039. name: 'tc',
  22040. 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;'
  22041. },
  22042. {
  22043. tag: 'h1',
  22044. name: 'tl',
  22045. 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;'
  22046. },
  22047. {tag: 'span', name: 'im', style: 'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  22048. {
  22049. tag: 'span',
  22050. name: 'hi',
  22051. style: 'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'
  22052. }
  22053. ]
  22054. });
  22055. me.commands['customstyle'] = {
  22056. execCommand: function (cmdName, obj) {
  22057. var me = this,
  22058. tagName = obj.tag,
  22059. node = domUtils.findParent(me.selection.getStart(), function (node) {
  22060. return node.getAttribute('label');
  22061. }, true),
  22062. range, bk, tmpObj = {};
  22063. for (var p in obj) {
  22064. if (obj[p] !== undefined)
  22065. tmpObj[p] = obj[p];
  22066. }
  22067. delete tmpObj.tag;
  22068. if (node && node.getAttribute('label') == obj.label) {
  22069. range = this.selection.getRange();
  22070. bk = range.createBookmark();
  22071. if (range.collapsed) {
  22072. //trace:1732 删掉自定义标签,要有p来回填站位
  22073. if (dtd.$block[node.tagName]) {
  22074. var fillNode = me.document.createElement('p');
  22075. domUtils.moveChild(node, fillNode);
  22076. node.parentNode.insertBefore(fillNode, node);
  22077. domUtils.remove(node);
  22078. } else {
  22079. domUtils.remove(node, true);
  22080. }
  22081. } else {
  22082. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  22083. nodes = domUtils.getElementsByTagName(common, tagName);
  22084. if (new RegExp(tagName, 'i').test(common.tagName)) {
  22085. nodes.push(common);
  22086. }
  22087. for (var i = 0, ni; ni = nodes[i++];) {
  22088. if (ni.getAttribute('label') == obj.label) {
  22089. var ps = domUtils.getPosition(ni, bk.start), pe = domUtils.getPosition(ni, bk.end);
  22090. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  22091. &&
  22092. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  22093. )
  22094. if (dtd.$block[tagName]) {
  22095. var fillNode = me.document.createElement('p');
  22096. domUtils.moveChild(ni, fillNode);
  22097. ni.parentNode.insertBefore(fillNode, ni);
  22098. }
  22099. domUtils.remove(ni, true);
  22100. }
  22101. }
  22102. node = domUtils.findParent(common, function(node) {
  22103. return node.getAttribute('label') == obj.label;
  22104. }, true);
  22105. if (node) {
  22106. domUtils.remove(node, true);
  22107. }
  22108. }
  22109. range.moveToBookmark(bk).select();
  22110. } else {
  22111. if (dtd.$block[tagName]) {
  22112. this.execCommand('paragraph', tagName, tmpObj, 'customstyle');
  22113. range = me.selection.getRange();
  22114. if (!range.collapsed) {
  22115. range.collapse();
  22116. node = domUtils.findParent(me.selection.getStart(), function(node) {
  22117. return node.getAttribute('label') == obj.label;
  22118. }, true);
  22119. var pNode = me.document.createElement('p');
  22120. domUtils.insertAfter(node, pNode);
  22121. domUtils.fillNode(me.document, pNode);
  22122. range.setStart(pNode, 0).setCursor();
  22123. }
  22124. } else {
  22125. range = me.selection.getRange();
  22126. if (range.collapsed) {
  22127. node = me.document.createElement(tagName);
  22128. domUtils.setAttributes(node, tmpObj);
  22129. range.insertNode(node).setStart(node, 0).setCursor();
  22130. return;
  22131. }
  22132. bk = range.createBookmark();
  22133. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  22134. }
  22135. }
  22136. },
  22137. queryCommandValue: function () {
  22138. var parent = domUtils.filterNodeList(
  22139. this.selection.getStartElementPath(),
  22140. function (node) {
  22141. return node.getAttribute('label')
  22142. }
  22143. );
  22144. return parent ? parent.getAttribute('label') : '';
  22145. }
  22146. };
  22147. //当去掉customstyle是,如果是块元素,用p代替
  22148. me.addListener('keyup', function (type, evt) {
  22149. var keyCode = evt.keyCode || evt.which;
  22150. if (keyCode == 32 || keyCode == 13) {
  22151. var range = me.selection.getRange();
  22152. if (range.collapsed) {
  22153. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  22154. return node.getAttribute('label');
  22155. }, true);
  22156. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  22157. var p = me.document.createElement('p');
  22158. domUtils.insertAfter(node, p);
  22159. domUtils.fillNode(me.document, p);
  22160. domUtils.remove(node);
  22161. range.setStart(p, 0).setCursor();
  22162. }
  22163. }
  22164. }
  22165. });
  22166. };
  22167. // plugins/catchremoteimage.js
  22168. ///import core
  22169. ///commands 远程图片抓取
  22170. ///commandsName catchRemoteImage,catchremoteimageenable
  22171. ///commandsTitle 远程图片抓取
  22172. /**
  22173. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  22174. */
  22175. UE.plugins['catchremoteimage'] = function() {
  22176. var me = this,
  22177. ajax = UE.ajax;
  22178. /* 设置默认值 */
  22179. if (me.options.catchRemoteImageEnable === false) return;
  22180. me.setOpt({
  22181. catchRemoteImageEnable: false
  22182. });
  22183. me.addListener("afterpaste", function () {
  22184. me.fireEvent("catchRemoteImage");
  22185. });
  22186. me.addListener("catchRemoteImage", function () {
  22187. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  22188. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  22189. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  22190. catcherFieldName = me.getOpt('catcherFieldName');
  22191. var remoteImages = [],
  22192. imgs = domUtils.getElementsByTagName(me.document, "img"),
  22193. test = function (src, urls) {
  22194. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  22195. return true;
  22196. }
  22197. if (urls) {
  22198. for (var j = 0, url; url = urls[j++];) {
  22199. if (src.indexOf(url) !== -1) {
  22200. return true;
  22201. }
  22202. }
  22203. }
  22204. return false;
  22205. };
  22206. for (var i = 0, ci; ci = imgs[i++];) {
  22207. if (ci.getAttribute("word_img")) {
  22208. continue;
  22209. }
  22210. var src = ci.getAttribute("_src") || ci.src || "";
  22211. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  22212. remoteImages.push(src);
  22213. }
  22214. }
  22215. if (remoteImages.length) {
  22216. catchremoteimage(remoteImages, {
  22217. //成功抓取
  22218. success: function (r) {
  22219. try {
  22220. var info = r.state !== undefined ? r : eval("(" + r.responseText + ")");
  22221. } catch (e) {
  22222. return;
  22223. }
  22224. /* 获取源路径和新路径 */
  22225. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  22226. for (i = 0; ci = imgs[i++];) {
  22227. oldSrc = ci.getAttribute("_src") || ci.src || "";
  22228. for (j = 0; cj = list[j++];) {
  22229. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  22230. newSrc = catcherUrlPrefix + cj.url;
  22231. domUtils.setAttributes(ci, {
  22232. "src": newSrc,
  22233. "_src": newSrc
  22234. });
  22235. break;
  22236. }
  22237. }
  22238. }
  22239. me.fireEvent('catchremotesuccess')
  22240. },
  22241. //回调失败,本次请求超时
  22242. error: function () {
  22243. me.fireEvent("catchremoteerror");
  22244. }
  22245. });
  22246. }
  22247. function catchremoteimage(imgs, callbacks) {
  22248. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  22249. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?' : '&') + params),
  22250. isJsonp = utils.isCrossDomainUrl(url),
  22251. opt = {
  22252. 'method': 'POST',
  22253. 'dataType': isJsonp ? 'jsonp' : '',
  22254. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  22255. 'onsuccess': callbacks["success"],
  22256. 'onerror': callbacks["error"]
  22257. };
  22258. opt[catcherFieldName] = imgs;
  22259. ajax.request(url, opt);
  22260. }
  22261. });
  22262. };
  22263. // plugins/snapscreen.js
  22264. /**
  22265. * 截屏插件,为UEditor提供插入支持
  22266. * @file
  22267. * @since 1.4.2
  22268. */
  22269. UE.plugin.register('snapscreen', function() {
  22270. var me = this;
  22271. var snapplugin;
  22272. function getLocation(url) {
  22273. var search,
  22274. a = document.createElement('a'),
  22275. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22276. a.href = url;
  22277. if (browser.ie) {
  22278. a.href = a.href;
  22279. }
  22280. search = a.search;
  22281. if (params) {
  22282. search = search + (search.indexOf('?') == -1 ? '?' : '&') + params;
  22283. search = search.replace(/[&]+/ig, '&');
  22284. }
  22285. return {
  22286. 'port': a.port,
  22287. 'hostname': a.hostname,
  22288. 'path': a.pathname + search || +a.hash
  22289. }
  22290. }
  22291. return {
  22292. commands: {
  22293. /**
  22294. * 字体背景颜色
  22295. * @command snapscreen
  22296. * @method execCommand
  22297. * @param { String } cmd 命令字符串
  22298. * @example
  22299. * ```javascript
  22300. * editor.execCommand('snapscreen');
  22301. * ```
  22302. */
  22303. 'snapscreen': {
  22304. execCommand: function (cmd) {
  22305. var url, local, res;
  22306. var lang = me.getLang("snapScreen_plugin");
  22307. if (!snapplugin) {
  22308. var container = me.container;
  22309. var doc = me.container.ownerDocument || me.container.document;
  22310. snapplugin = doc.createElement("object");
  22311. try {
  22312. snapplugin.type = "application/x-pluginbaidusnap";
  22313. } catch (e) {
  22314. return;
  22315. }
  22316. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  22317. snapplugin.setAttribute("width", "0");
  22318. snapplugin.setAttribute("height", "0");
  22319. container.appendChild(snapplugin);
  22320. }
  22321. function onSuccess(rs) {
  22322. try {
  22323. rs = eval("(" + rs + ")");
  22324. if (rs.state == 'SUCCESS') {
  22325. var opt = me.options;
  22326. me.execCommand('insertimage', {
  22327. src: opt.snapscreenUrlPrefix + rs.url,
  22328. _src: opt.snapscreenUrlPrefix + rs.url,
  22329. alt: rs.title || '',
  22330. floatStyle: opt.snapscreenImgAlign
  22331. });
  22332. } else {
  22333. alert(rs.state);
  22334. }
  22335. } catch (e) {
  22336. alert(lang.callBackErrorMsg);
  22337. }
  22338. }
  22339. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  22340. local = getLocation(url);
  22341. setTimeout(function() {
  22342. try {
  22343. res = snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  22344. } catch (e) {
  22345. me.ui._dialogs['snapscreenDialog'].open();
  22346. return;
  22347. }
  22348. onSuccess(res);
  22349. }, 50);
  22350. },
  22351. queryCommandState: function () {
  22352. return (navigator.userAgent.indexOf("Windows", 0) != -1) ? 0 : -1;
  22353. }
  22354. }
  22355. }
  22356. }
  22357. });
  22358. // plugins/insertparagraph.js
  22359. /**
  22360. * 插入段落
  22361. * @file
  22362. * @since 1.2.6.1
  22363. */
  22364. /**
  22365. * 插入段落
  22366. * @command insertparagraph
  22367. * @method execCommand
  22368. * @param { String } cmd 命令字符串
  22369. * @example
  22370. * ```javascript
  22371. * //editor是编辑器实例
  22372. * editor.execCommand( 'insertparagraph' );
  22373. * ```
  22374. */
  22375. UE.commands['insertparagraph'] = {
  22376. execCommand: function (cmdName, front) {
  22377. var me = this,
  22378. range = me.selection.getRange(),
  22379. start = range.startContainer, tmpNode;
  22380. while (start) {
  22381. if (domUtils.isBody(start)) {
  22382. break;
  22383. }
  22384. tmpNode = start;
  22385. start = start.parentNode;
  22386. }
  22387. if (tmpNode) {
  22388. var p = me.document.createElement('p');
  22389. if (front) {
  22390. tmpNode.parentNode.insertBefore(p, tmpNode)
  22391. } else {
  22392. tmpNode.parentNode.insertBefore(p, tmpNode.nextSibling)
  22393. }
  22394. domUtils.fillNode(me.document, p);
  22395. range.setStart(p, 0).setCursor(false, true);
  22396. }
  22397. }
  22398. };
  22399. // plugins/webapp.js
  22400. /**
  22401. * 百度应用
  22402. * @file
  22403. * @since 1.2.6.1
  22404. */
  22405. /**
  22406. * 插入百度应用
  22407. * @command webapp
  22408. * @method execCommand
  22409. * @remind 需要百度APPKey
  22410. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  22411. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  22412. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  22413. * @example
  22414. * ```javascript
  22415. * //editor是编辑器实例
  22416. * //在编辑器里插入一个“植物大战僵尸”的APP
  22417. * editor.execCommand( 'webapp' , {
  22418. * title: '植物大战僵尸',
  22419. * width: 560,
  22420. * height: 465,
  22421. * logo: '应用展示的图片',
  22422. * url: '百度应用的地址'
  22423. * } );
  22424. * ```
  22425. */
  22426. //UE.plugins['webapp'] = function () {
  22427. // var me = this;
  22428. // function createInsertStr( obj, toIframe, addParagraph ) {
  22429. // return !toIframe ?
  22430. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  22431. // ' 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 + '" />' +
  22432. // (addParagraph ? '</p>' : '')
  22433. // :
  22434. // '<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>';
  22435. // }
  22436. //
  22437. // function switchImgAndIframe( img2frame ) {
  22438. // var tmpdiv,
  22439. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  22440. // for ( var i = 0, node; node = nodes[i++]; ) {
  22441. // if ( node.className != "edui-faked-webapp" ){
  22442. // continue;
  22443. // }
  22444. // tmpdiv = me.document.createElement( "div" );
  22445. // 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 );
  22446. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  22447. // }
  22448. // }
  22449. //
  22450. // me.addListener( "beforegetcontent", function () {
  22451. // switchImgAndIframe( true );
  22452. // } );
  22453. // me.addListener( 'aftersetcontent', function () {
  22454. // switchImgAndIframe( false );
  22455. // } );
  22456. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  22457. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  22458. // return;
  22459. // }
  22460. // switchImgAndIframe( false );
  22461. // } );
  22462. //
  22463. // me.commands['webapp'] = {
  22464. // execCommand:function ( cmd, obj ) {
  22465. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  22466. // }
  22467. // };
  22468. //};
  22469. UE.plugin.register('webapp', function() {
  22470. var me = this;
  22471. function createInsertStr(obj, toEmbed) {
  22472. return !toEmbed ?
  22473. '<img title="' + obj.title + '" width="' + obj.width + '" height="' + obj.height + '"' +
  22474. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="' + obj.logo + '" style="background:url(' + obj.logo
  22475. + ') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  22476. (obj.align && !obj.cssfloat ? 'align="' + obj.align + '"' : '') +
  22477. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  22478. '/>'
  22479. :
  22480. '<iframe class="edui-faked-webapp" title="' + obj.title + '" ' +
  22481. (obj.align && !obj.cssfloat ? 'align="' + obj.align + '"' : '') +
  22482. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  22483. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "' + obj.logo + '"></iframe>'
  22484. }
  22485. return {
  22486. outputRule: function (root) {
  22487. utils.each(root.getNodesByTagName('img'), function (node) {
  22488. var html;
  22489. if (node.getAttr('class') == 'edui-faked-webapp') {
  22490. html = createInsertStr({
  22491. title: node.getAttr('title'),
  22492. 'width': node.getAttr('width'),
  22493. 'height': node.getAttr('height'),
  22494. 'align': node.getAttr('align'),
  22495. 'cssfloat': node.getStyle('float'),
  22496. 'url': node.getAttr("_url"),
  22497. 'logo': node.getAttr('_logo_url')
  22498. }, true);
  22499. var embed = UE.uNode.createElement(html);
  22500. node.parentNode.replaceChild(embed, node);
  22501. }
  22502. })
  22503. },
  22504. inputRule: function (root) {
  22505. utils.each(root.getNodesByTagName('iframe'), function (node) {
  22506. if (node.getAttr('class') == 'edui-faked-webapp') {
  22507. var img = UE.uNode.createElement(createInsertStr({
  22508. title: node.getAttr('title'),
  22509. 'width': node.getAttr('width'),
  22510. 'height': node.getAttr('height'),
  22511. 'align': node.getAttr('align'),
  22512. 'cssfloat': node.getStyle('float'),
  22513. 'url': node.getAttr("src"),
  22514. 'logo': node.getAttr('logo_url')
  22515. }));
  22516. node.parentNode.replaceChild(img, node);
  22517. }
  22518. })
  22519. },
  22520. commands: {
  22521. /**
  22522. * 插入百度应用
  22523. * @command webapp
  22524. * @method execCommand
  22525. * @remind 需要百度APPKey
  22526. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  22527. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  22528. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  22529. * @example
  22530. * ```javascript
  22531. * //editor是编辑器实例
  22532. * //在编辑器里插入一个“植物大战僵尸”的APP
  22533. * editor.execCommand( 'webapp' , {
  22534. * title: '植物大战僵尸',
  22535. * width: 560,
  22536. * height: 465,
  22537. * logo: '应用展示的图片',
  22538. * url: '百度应用的地址'
  22539. * } );
  22540. * ```
  22541. */
  22542. 'webapp': {
  22543. execCommand: function(cmd, obj) {
  22544. var me = this,
  22545. str = createInsertStr(utils.extend(obj, {
  22546. align: 'none'
  22547. }), false);
  22548. me.execCommand("inserthtml", str);
  22549. },
  22550. queryCommandState: function () {
  22551. var me = this,
  22552. img = me.selection.getRange().getClosedNode(),
  22553. flag = img && (img.className == "edui-faked-webapp");
  22554. return flag ? 1 : 0;
  22555. }
  22556. }
  22557. }
  22558. }
  22559. });
  22560. // plugins/template.js
  22561. ///import core
  22562. ///import plugins\inserthtml.js
  22563. ///import plugins\cleardoc.js
  22564. ///commands 模板
  22565. ///commandsName template
  22566. ///commandsTitle 模板
  22567. ///commandsDialog dialogs\template
  22568. UE.plugins['template'] = function () {
  22569. UE.commands['template'] = {
  22570. execCommand: function (cmd, obj) {
  22571. obj.html && this.execCommand("inserthtml", obj.html);
  22572. }
  22573. };
  22574. this.addListener("click", function (type, evt) {
  22575. var el = evt.target || evt.srcElement,
  22576. range = this.selection.getRange();
  22577. var tnode = domUtils.findParent(el, function (node) {
  22578. if (node.className && domUtils.hasClass(node, "ue_t")) {
  22579. return node;
  22580. }
  22581. }, true);
  22582. tnode && range.selectNode(tnode).shrinkBoundary().select();
  22583. });
  22584. this.addListener("keydown", function (type, evt) {
  22585. var range = this.selection.getRange();
  22586. if (!range.collapsed) {
  22587. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  22588. var tnode = domUtils.findParent(range.startContainer, function (node) {
  22589. if (node.className && domUtils.hasClass(node, "ue_t")) {
  22590. return node;
  22591. }
  22592. }, true);
  22593. if (tnode) {
  22594. domUtils.removeClasses(tnode, ["ue_t"]);
  22595. }
  22596. }
  22597. }
  22598. });
  22599. };
  22600. // plugins/music.js
  22601. /**
  22602. * 插入音乐命令
  22603. * @file
  22604. */
  22605. UE.plugin.register('music', function() {
  22606. var me = this;
  22607. function creatInsertStr(url, width, height, align, cssfloat, toEmbed) {
  22608. return !toEmbed ?
  22609. '<img ' +
  22610. (align && !cssfloat ? 'align="' + align + '"' : '') +
  22611. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  22612. ' width="' + width + '" height="' + height + '" _url="' + url + '" class="edui-faked-music"' +
  22613. ' src="' + me.options.langPath + me.options.lang + '/images/music.png" />'
  22614. :
  22615. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  22616. ' src="' + url + '" width="' + width + '" height="' + height + '" ' + (align && !cssfloat ? 'align="' + align + '"' : '') +
  22617. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  22618. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  22619. }
  22620. return {
  22621. outputRule: function (root) {
  22622. utils.each(root.getNodesByTagName('img'), function (node) {
  22623. var html;
  22624. if (node.getAttr('class') == 'edui-faked-music') {
  22625. var cssfloat = node.getStyle('float');
  22626. var align = node.getAttr('align');
  22627. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  22628. var embed = UE.uNode.createElement(html);
  22629. node.parentNode.replaceChild(embed, node);
  22630. }
  22631. })
  22632. },
  22633. inputRule: function (root) {
  22634. utils.each(root.getNodesByTagName('embed'), function (node) {
  22635. if (node.getAttr('class') == 'edui-faked-music') {
  22636. var cssfloat = node.getStyle('float');
  22637. var align = node.getAttr('align');
  22638. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, false);
  22639. var img = UE.uNode.createElement(html);
  22640. node.parentNode.replaceChild(img, node);
  22641. }
  22642. })
  22643. },
  22644. commands: {
  22645. /**
  22646. * 插入音乐
  22647. * @command music
  22648. * @method execCommand
  22649. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  22650. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  22651. * @example
  22652. * ```javascript
  22653. * //editor是编辑器实例
  22654. * //在编辑器里插入一个“植物大战僵尸”的APP
  22655. * editor.execCommand( 'music' , {
  22656. * width: 400,
  22657. * height: 95,
  22658. * align: "center",
  22659. * url: "音乐地址"
  22660. * } );
  22661. * ```
  22662. */
  22663. 'music': {
  22664. execCommand: function (cmd, musicObj) {
  22665. var me = this,
  22666. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  22667. me.execCommand("inserthtml", str);
  22668. },
  22669. queryCommandState: function () {
  22670. var me = this,
  22671. img = me.selection.getRange().getClosedNode(),
  22672. flag = img && (img.className == "edui-faked-music");
  22673. return flag ? 1 : 0;
  22674. }
  22675. }
  22676. }
  22677. }
  22678. });
  22679. // plugins/autoupload.js
  22680. /**
  22681. * @description
  22682. * 1.拖放文件到编辑区域,自动上传并插入到选区
  22683. * 2.插入粘贴板的图片,自动上传并插入到选区
  22684. * @author Jinqn
  22685. * @date 2013-10-14
  22686. */
  22687. UE.plugin.register('autoupload', function() {
  22688. function sendAndInsertFile(file, editor) {
  22689. var me = editor;
  22690. //模拟数据
  22691. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  22692. loadingHtml, errorHandler, successHandler,
  22693. filetype = /image\/\w+/i.test(file.type) ? 'image' : 'file',
  22694. loadingId = 'loading_' + (+new Date()).toString(36);
  22695. fieldName = me.getOpt(filetype + 'FieldName');
  22696. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  22697. maxSize = me.getOpt(filetype + 'MaxSize');
  22698. allowFiles = me.getOpt(filetype + 'AllowFiles');
  22699. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  22700. errorHandler = function (title) {
  22701. var loader = me.document.getElementById(loadingId);
  22702. loader && domUtils.remove(loader);
  22703. me.fireEvent('showmessage', {
  22704. 'id': loadingId,
  22705. 'content': title,
  22706. 'type': 'error',
  22707. 'timeout': 4000
  22708. });
  22709. };
  22710. if (filetype == 'image') {
  22711. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  22712. me.options.themePath + me.options.theme +
  22713. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  22714. successHandler = function(data) {
  22715. var link = urlPrefix + data.url,
  22716. loader = me.document.getElementById(loadingId);
  22717. if (loader) {
  22718. loader.setAttribute('src', link);
  22719. loader.setAttribute('_src', link);
  22720. loader.setAttribute('title', data.title || '');
  22721. loader.setAttribute('alt', data.original || '');
  22722. loader.removeAttribute('id');
  22723. domUtils.removeClasses(loader, 'loadingclass');
  22724. }
  22725. };
  22726. } else {
  22727. loadingHtml = '<p>' +
  22728. '<img class="loadingclass" id="' + loadingId + '" src="' +
  22729. me.options.themePath + me.options.theme +
  22730. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  22731. '</p>';
  22732. successHandler = function(data) {
  22733. var link = urlPrefix + data.url,
  22734. loader = me.document.getElementById(loadingId);
  22735. var rng = me.selection.getRange(),
  22736. bk = rng.createBookmark();
  22737. rng.selectNode(loader).select();
  22738. me.execCommand('insertfile', { 'url': link });
  22739. rng.moveToBookmark(bk).select();
  22740. };
  22741. }
  22742. /* 插入loading的占位符 */
  22743. me.execCommand('inserthtml', loadingHtml);
  22744. /* 判断后端配置是否没有加载成功 */
  22745. if (!me.getOpt(filetype + 'ActionName')) {
  22746. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22747. return;
  22748. }
  22749. /* 判断文件大小是否超出限制 */
  22750. if (file.size > maxSize) {
  22751. errorHandler(me.getLang('autoupload.exceedSizeError'));
  22752. return;
  22753. }
  22754. /* 判断文件格式是否超出允许 */
  22755. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')) : '';
  22756. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22757. errorHandler(me.getLang('autoupload.exceedTypeError'));
  22758. return;
  22759. }
  22760. /* 创建Ajax并提交 */
  22761. var xhr = new XMLHttpRequest(),
  22762. fd = new FormData(),
  22763. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  22764. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  22765. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  22766. fd.append('type', 'ajax');
  22767. xhr.open("post", url, true);
  22768. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  22769. xhr.addEventListener('load', function (e) {
  22770. try {
  22771. var json = (new Function("return " + utils.trim(e.target.response)))();
  22772. if (json.state == 'SUCCESS' && json.url) {
  22773. successHandler(json);
  22774. } else {
  22775. errorHandler(json.state);
  22776. }
  22777. } catch (er) {
  22778. errorHandler(me.getLang('autoupload.loadError'));
  22779. }
  22780. });
  22781. xhr.send(fd);
  22782. }
  22783. function getPasteImage(e) {
  22784. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  22785. }
  22786. function getDropImage(e) {
  22787. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  22788. }
  22789. return {
  22790. outputRule: function(root) {
  22791. utils.each(root.getNodesByTagName('img'), function(n) {
  22792. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22793. n.parentNode.removeChild(n);
  22794. }
  22795. });
  22796. utils.each(root.getNodesByTagName('p'), function(n) {
  22797. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  22798. n.parentNode.removeChild(n);
  22799. }
  22800. });
  22801. },
  22802. bindEvents: {
  22803. //插入粘贴板的图片,拖放插入图片
  22804. 'ready': function(e) {
  22805. var me = this;
  22806. if (window.FormData && window.FileReader) {
  22807. domUtils.on(me.body, 'paste drop', function(e) {
  22808. var hasImg = false,
  22809. items;
  22810. //获取粘贴板文件列表或者拖放文件列表
  22811. items = e.type == 'paste' ? getPasteImage(e) : getDropImage(e);
  22812. if (items) {
  22813. var len = items.length,
  22814. file;
  22815. while (len--) {
  22816. file = items[len];
  22817. if (file.getAsFile) file = file.getAsFile();
  22818. if (file && file.size > 0) {
  22819. sendAndInsertFile(file, me);
  22820. hasImg = true;
  22821. }
  22822. }
  22823. hasImg && e.preventDefault();
  22824. }
  22825. });
  22826. //取消拖放图片时出现的文字光标位置提示
  22827. domUtils.on(me.body, 'dragover', function(e) {
  22828. if (e.dataTransfer.types[0] == 'Files') {
  22829. e.preventDefault();
  22830. }
  22831. });
  22832. //设置loading的样式
  22833. utils.cssRule('loading',
  22834. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22835. + this.options.themePath
  22836. + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  22837. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22838. + this.options.themePath
  22839. + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22840. '}',
  22841. this.document);
  22842. }
  22843. }
  22844. }
  22845. }
  22846. });
  22847. // plugins/autosave.js
  22848. UE.plugin.register('autosave', function() {
  22849. var me = this,
  22850. //无限循环保护
  22851. lastSaveTime = new Date(),
  22852. //最小保存间隔时间
  22853. MIN_TIME = 20,
  22854. //auto save key
  22855. saveKey = null;
  22856. function save(editor) {
  22857. var saveData;
  22858. if (new Date() - lastSaveTime < MIN_TIME) {
  22859. return;
  22860. }
  22861. if (!editor.hasContents()) {
  22862. //这里不能调用命令来删除, 会造成事件死循环
  22863. saveKey && me.removePreferences(saveKey);
  22864. return;
  22865. }
  22866. lastSaveTime = new Date();
  22867. editor._saveFlag = null;
  22868. saveData = me.body.innerHTML;
  22869. if (editor.fireEvent('beforeautosave', {
  22870. content: saveData,
  22871. }) === false) {
  22872. return;
  22873. }
  22874. me.setPreferences(saveKey, saveData);
  22875. editor.fireEvent('afterautosave', {
  22876. content: saveData,
  22877. });
  22878. }
  22879. return {
  22880. defaultOptions: {
  22881. //默认间隔时间
  22882. saveInterval: 500,
  22883. enableAutoSave: true, // HaoChuan9421
  22884. },
  22885. bindEvents: {
  22886. 'ready': function() {
  22887. var _suffix = '-drafts-data',
  22888. key = null;
  22889. if (me.key) {
  22890. key = me.key + _suffix;
  22891. } else {
  22892. key = (me.container.parentNode.id || 'ue-common') + _suffix;
  22893. }
  22894. //页面地址+编辑器ID 保持唯一
  22895. saveKey = (location.protocol + location.host + location.pathname).replace(/[.:\/]/g, '_') + key;
  22896. },
  22897. 'contentchange': function() {
  22898. // HaoChuan9421
  22899. if (!me.getOpt('enableAutoSave')) {
  22900. return;
  22901. }
  22902. if (!saveKey) {
  22903. return;
  22904. }
  22905. if (me._saveFlag) {
  22906. window.clearTimeout(me._saveFlag);
  22907. }
  22908. if (me.options.saveInterval > 0) {
  22909. me._saveFlag = window.setTimeout(function() {
  22910. save(me);
  22911. }, me.options.saveInterval);
  22912. } else {
  22913. save(me);
  22914. }
  22915. },
  22916. },
  22917. commands: {
  22918. 'clearlocaldata': {
  22919. execCommand: function(cmd, name) {
  22920. if (saveKey && me.getPreferences(saveKey)) {
  22921. me.removePreferences(saveKey);
  22922. }
  22923. },
  22924. notNeedUndo: true,
  22925. ignoreContentChange: true,
  22926. },
  22927. 'getlocaldata': {
  22928. execCommand: function(cmd, name) {
  22929. return saveKey ? me.getPreferences(saveKey) || '' : '';
  22930. },
  22931. notNeedUndo: true,
  22932. ignoreContentChange: true,
  22933. },
  22934. 'drafts': {
  22935. execCommand: function(cmd, name) {
  22936. if (saveKey) {
  22937. me.body.innerHTML = me.getPreferences(saveKey) || '<p>' + domUtils.fillHtml + '</p>';
  22938. me.focus(true);
  22939. }
  22940. },
  22941. queryCommandState: function() {
  22942. return saveKey ? (me.getPreferences(saveKey) === null ? -1 : 0) : -1;
  22943. },
  22944. notNeedUndo: true,
  22945. ignoreContentChange: true,
  22946. },
  22947. },
  22948. };
  22949. });
  22950. // plugins/charts.js
  22951. UE.plugin.register('charts', function() {
  22952. var me = this;
  22953. return {
  22954. bindEvents: {
  22955. 'chartserror': function () {
  22956. }
  22957. },
  22958. commands: {
  22959. 'charts': {
  22960. execCommand: function (cmd, data) {
  22961. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22962. flagText = [],
  22963. config = {};
  22964. if (!tableNode) {
  22965. return false;
  22966. }
  22967. if (!validData(tableNode)) {
  22968. me.fireEvent("chartserror");
  22969. return false;
  22970. }
  22971. config.title = data.title || '';
  22972. config.subTitle = data.subTitle || '';
  22973. config.xTitle = data.xTitle || '';
  22974. config.yTitle = data.yTitle || '';
  22975. config.suffix = data.suffix || '';
  22976. config.tip = data.tip || '';
  22977. //数据对齐方式
  22978. config.dataFormat = data.tableDataFormat || '';
  22979. //图表类型
  22980. config.chartType = data.chartType || 0;
  22981. for (var key in config) {
  22982. if (!config.hasOwnProperty(key)) {
  22983. continue;
  22984. }
  22985. flagText.push(key + ":" + config[key]);
  22986. }
  22987. tableNode.setAttribute("data-chart", flagText.join(";"));
  22988. domUtils.addClass(tableNode, "edui-charts-table");
  22989. },
  22990. queryCommandState: function(cmd, name) {
  22991. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22992. return tableNode && validData(tableNode) ? 0 : -1;
  22993. }
  22994. }
  22995. },
  22996. inputRule: function (root) {
  22997. utils.each(root.getNodesByTagName('table'), function (tableNode) {
  22998. if (tableNode.getAttr("data-chart") !== undefined) {
  22999. tableNode.setAttr("style");
  23000. }
  23001. })
  23002. },
  23003. outputRule: function(root) {
  23004. utils.each(root.getNodesByTagName('table'), function(tableNode) {
  23005. if (tableNode.getAttr("data-chart") !== undefined) {
  23006. tableNode.setAttr("style", "display: none;");
  23007. }
  23008. })
  23009. }
  23010. }
  23011. function validData(table) {
  23012. var firstRows = null,
  23013. cellCount = 0;
  23014. //行数不够
  23015. if (table.rows.length < 2) {
  23016. return false;
  23017. }
  23018. //列数不够
  23019. if (table.rows[0].cells.length < 2) {
  23020. return false;
  23021. }
  23022. //第一行所有cell必须是th
  23023. firstRows = table.rows[0].cells;
  23024. cellCount = firstRows.length;
  23025. for (var i = 0, cell; cell = firstRows[i]; i++) {
  23026. if (cell.tagName.toLowerCase() !== 'th') {
  23027. return false;
  23028. }
  23029. }
  23030. for (var i = 1, row; row = table.rows[i]; i++) {
  23031. //每行单元格数不匹配, 返回false
  23032. if (row.cells.length != cellCount) {
  23033. return false;
  23034. }
  23035. //第一列不是th也返回false
  23036. if (row.cells[0].tagName.toLowerCase() !== 'th') {
  23037. return false;
  23038. }
  23039. for (var j = 1, cell; cell = row.cells[j]; j++) {
  23040. var value = utils.trim((cell.innerText || cell.textContent || ''));
  23041. value = value.replace(new RegExp(UE.dom.domUtils.fillChar, 'g'), '').replace(/^\s+|\s+$/g, '');
  23042. //必须是数字
  23043. if (!/^\d*\.?\d+$/.test(value)) {
  23044. return false;
  23045. }
  23046. }
  23047. }
  23048. return true;
  23049. }
  23050. });
  23051. // plugins/section.js
  23052. /**
  23053. * 目录大纲支持插件
  23054. * @file
  23055. * @since 1.3.0
  23056. */
  23057. UE.plugin.register('section', function() {
  23058. /* 目录节点对象 */
  23059. function Section(option) {
  23060. this.tag = '';
  23061. this.level = -1,
  23062. this.dom = null;
  23063. this.nextSection = null;
  23064. this.previousSection = null;
  23065. this.parentSection = null;
  23066. this.startAddress = [];
  23067. this.endAddress = [];
  23068. this.children = [];
  23069. }
  23070. function getSection(option) {
  23071. var section = new Section();
  23072. return utils.extend(section, option);
  23073. }
  23074. function getNodeFromAddress(startAddress, root) {
  23075. var current = root;
  23076. for (var i = 0; i < startAddress.length; i++) {
  23077. if (!current.childNodes) return null;
  23078. current = current.childNodes[startAddress[i]];
  23079. }
  23080. return current;
  23081. }
  23082. var me = this;
  23083. return {
  23084. bindMultiEvents: {
  23085. type: 'aftersetcontent afterscencerestore',
  23086. handler: function () {
  23087. me.fireEvent('updateSections');
  23088. }
  23089. },
  23090. bindEvents: {
  23091. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  23092. 'ready': function () {
  23093. me.fireEvent('updateSections');
  23094. domUtils.on(me.body, 'drop paste', function () {
  23095. me.fireEvent('updateSections');
  23096. });
  23097. },
  23098. /* 执行paragraph命令之后 */
  23099. 'afterexeccommand': function (type, cmd) {
  23100. if (cmd == 'paragraph') {
  23101. me.fireEvent('updateSections');
  23102. }
  23103. },
  23104. /* 部分键盘操作,触发updateSections事件 */
  23105. 'keyup': function (type, e) {
  23106. var me = this,
  23107. range = me.selection.getRange();
  23108. if (range.collapsed != true) {
  23109. me.fireEvent('updateSections');
  23110. } else {
  23111. var keyCode = e.keyCode || e.which;
  23112. if (keyCode == 13 || keyCode == 8 || keyCode == 46) {
  23113. me.fireEvent('updateSections');
  23114. }
  23115. }
  23116. }
  23117. },
  23118. commands: {
  23119. 'getsections': {
  23120. execCommand: function (cmd, levels) {
  23121. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  23122. for (var i = 0; i < levelFn.length; i++) {
  23123. if (typeof levelFn[i] == 'string') {
  23124. levelFn[i] = function (fn) {
  23125. return function (node) {
  23126. return node.tagName == fn.toUpperCase()
  23127. };
  23128. }(levelFn[i]);
  23129. } else if (typeof levelFn[i] != 'function') {
  23130. levelFn[i] = function (node) {
  23131. return null;
  23132. }
  23133. }
  23134. }
  23135. function getSectionLevel(node) {
  23136. for (var i = 0; i < levelFn.length; i++) {
  23137. if (levelFn[i](node)) return i;
  23138. }
  23139. return -1;
  23140. }
  23141. var me = this,
  23142. Directory = getSection({ 'level': -1, 'title': 'root' }),
  23143. previous = Directory;
  23144. function traversal(node, Directory) {
  23145. var level,
  23146. tmpSection = null,
  23147. parent,
  23148. child,
  23149. children = node.childNodes;
  23150. for (var i = 0, len = children.length; i < len; i++) {
  23151. child = children[i];
  23152. level = getSectionLevel(child);
  23153. if (level >= 0) {
  23154. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  23155. current = getSection({
  23156. 'tag': child.tagName,
  23157. 'title': child.innerText || child.textContent || '',
  23158. 'level': level,
  23159. 'dom': child,
  23160. 'startAddress': utils.clone(address, []),
  23161. 'endAddress': utils.clone(address, []),
  23162. 'children': []
  23163. });
  23164. previous.nextSection = current;
  23165. current.previousSection = previous;
  23166. parent = previous;
  23167. while (level <= parent.level) {
  23168. parent = parent.parentSection;
  23169. }
  23170. current.parentSection = parent;
  23171. parent.children.push(current);
  23172. tmpSection = previous = current;
  23173. } else {
  23174. child.nodeType === 1 && traversal(child, Directory);
  23175. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1]++;
  23176. }
  23177. }
  23178. }
  23179. traversal(me.body, Directory);
  23180. return Directory;
  23181. },
  23182. notNeedUndo: true
  23183. },
  23184. 'movesection': {
  23185. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  23186. var me = this,
  23187. targetAddress,
  23188. target;
  23189. if (!sourceSection || !targetSection || targetSection.level == -1) return;
  23190. targetAddress = isAfter ? targetSection.endAddress : targetSection.startAddress;
  23191. target = getNodeFromAddress(targetAddress, me.body);
  23192. /* 判断目标地址是否被源章节包含 */
  23193. if (!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  23194. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  23195. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  23196. current,
  23197. nextNode;
  23198. if (isAfter) {
  23199. current = endNode;
  23200. while (current && !(domUtils.getPosition(startNode, current) & domUtils.POSITION_FOLLOWING)) {
  23201. nextNode = current.previousSibling;
  23202. domUtils.insertAfter(target, current);
  23203. if (current == startNode) break;
  23204. current = nextNode;
  23205. }
  23206. } else {
  23207. current = startNode;
  23208. while (current && !(domUtils.getPosition(current, endNode) & domUtils.POSITION_FOLLOWING)) {
  23209. nextNode = current.nextSibling;
  23210. target.parentNode.insertBefore(current, target);
  23211. if (current == endNode) break;
  23212. current = nextNode;
  23213. }
  23214. }
  23215. me.fireEvent('updateSections');
  23216. /* 获取地址的包含关系 */
  23217. function isContainsAddress(startAddress, endAddress, addressTarget) {
  23218. var isAfterStartAddress = false,
  23219. isBeforeEndAddress = false;
  23220. for (var i = 0; i < startAddress.length; i++) {
  23221. if (i >= addressTarget.length) break;
  23222. if (addressTarget[i] > startAddress[i]) {
  23223. isAfterStartAddress = true;
  23224. break;
  23225. } else if (addressTarget[i] < startAddress[i]) {
  23226. break;
  23227. }
  23228. }
  23229. for (var i = 0; i < endAddress.length; i++) {
  23230. if (i >= addressTarget.length) break;
  23231. if (addressTarget[i] < startAddress[i]) {
  23232. isBeforeEndAddress = true;
  23233. break;
  23234. } else if (addressTarget[i] > startAddress[i]) {
  23235. break;
  23236. }
  23237. }
  23238. return isAfterStartAddress && isBeforeEndAddress;
  23239. }
  23240. }
  23241. },
  23242. 'deletesection': {
  23243. execCommand: function (cmd, section, keepChildren) {
  23244. var me = this;
  23245. if (!section) return;
  23246. function getNodeFromAddress(startAddress) {
  23247. var current = me.body;
  23248. for (var i = 0; i < startAddress.length; i++) {
  23249. if (!current.childNodes) return null;
  23250. current = current.childNodes[startAddress[i]];
  23251. }
  23252. return current;
  23253. }
  23254. var startNode = getNodeFromAddress(section.startAddress),
  23255. endNode = getNodeFromAddress(section.endAddress),
  23256. current = startNode,
  23257. nextNode;
  23258. if (!keepChildren) {
  23259. while (current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition(current, endNode) & domUtils.POSITION_FOLLOWING)) {
  23260. nextNode = current.nextSibling;
  23261. domUtils.remove(current);
  23262. current = nextNode;
  23263. }
  23264. } else {
  23265. domUtils.remove(current);
  23266. }
  23267. me.fireEvent('updateSections');
  23268. }
  23269. },
  23270. 'selectsection': {
  23271. execCommand: function (cmd, section) {
  23272. if (!section && !section.dom) return false;
  23273. var me = this,
  23274. range = me.selection.getRange(),
  23275. address = {
  23276. 'startAddress': utils.clone(section.startAddress, []),
  23277. 'endAddress': utils.clone(section.endAddress, [])
  23278. };
  23279. address.endAddress[address.endAddress.length - 1]++;
  23280. range.moveToAddress(address).select().scrollToView();
  23281. return true;
  23282. },
  23283. notNeedUndo: true
  23284. },
  23285. 'scrolltosection': {
  23286. execCommand: function (cmd, section) {
  23287. if (!section && !section.dom) return false;
  23288. var me = this,
  23289. range = me.selection.getRange(),
  23290. address = {
  23291. 'startAddress': section.startAddress,
  23292. 'endAddress': section.endAddress
  23293. };
  23294. address.endAddress[address.endAddress.length - 1]++;
  23295. range.moveToAddress(address).scrollToView();
  23296. return true;
  23297. },
  23298. notNeedUndo: true
  23299. }
  23300. }
  23301. }
  23302. });
  23303. // plugins/simpleupload.js
  23304. /**
  23305. * @description
  23306. * 简单上传:点击按钮,直接选择文件上传。
  23307. * 原 UEditor 作者使用了 form 表单 + iframe 的方式上传
  23308. * 但由于同源策略的限制,父页面无法访问跨域的 iframe 内容
  23309. * 导致无法获取接口返回的数据,使得单图上传无法在跨域的情况下使用
  23310. * 这里改为普通的XHR上传,兼容到IE10+
  23311. * @author HaoChuan9421 <hc199421@gmail.com>
  23312. * @date 2018-12-20
  23313. */
  23314. UE.plugin.register('simpleupload', function() {
  23315. var me = this,
  23316. containerBtn,
  23317. timestrap = (+new Date()).toString(36);
  23318. function initUploadBtn() {
  23319. var w = containerBtn.offsetWidth || 20,
  23320. h = containerBtn.offsetHeight || 20,
  23321. 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;';
  23322. var form = document.createElement('form');
  23323. var input = document.createElement('input');
  23324. form.id = 'edui_form_' + timestrap;
  23325. form.enctype = 'multipart/form-data';
  23326. form.style = btnStyle;
  23327. input.id = 'edui_input_' + timestrap;
  23328. input.type = 'file';
  23329. input.accept = 'image/*';
  23330. input.name = me.options.imageFieldName;
  23331. input.style = btnStyle;
  23332. form.appendChild(input);
  23333. containerBtn.appendChild(form);
  23334. input.addEventListener('change', function(event) {
  23335. if (!input.value) return;
  23336. var loadingId = 'loading_' + (+new Date()).toString(36);
  23337. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  23338. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  23339. var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  23340. var allowFiles = me.getOpt('imageAllowFiles');
  23341. me.focus();
  23342. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  23343. function showErrorLoader(title) {
  23344. if (loadingId) {
  23345. var loader = me.document.getElementById(loadingId);
  23346. loader && domUtils.remove(loader);
  23347. me.fireEvent('showmessage', {
  23348. 'id': loadingId,
  23349. 'content': title,
  23350. 'type': 'error',
  23351. 'timeout': 4000
  23352. });
  23353. }
  23354. }
  23355. /* 判断后端配置是否没有加载成功 */
  23356. if (!me.getOpt('imageActionName')) {
  23357. showErrorLoader(me.getLang('autoupload.errorLoadConfig'));
  23358. return;
  23359. }
  23360. // 判断文件格式是否错误
  23361. var filename = input.value,
  23362. fileext = filename ? filename.substr(filename.lastIndexOf('.')) : '';
  23363. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  23364. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  23365. return;
  23366. }
  23367. var xhr = new XMLHttpRequest();
  23368. xhr.open('post', action, true);
  23369. if (me.options.headers && Object.prototype.toString.apply(me.options.headers) === '[object Object]') {
  23370. for (var key in me.options.headers) {
  23371. xhr.setRequestHeader(key, me.options.headers[key]);
  23372. }
  23373. }
  23374. xhr.onload = function() {
  23375. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
  23376. var res = JSON.parse(xhr.responseText);
  23377. var link = me.options.imageUrlPrefix + res.url;
  23378. if (res.state == 'SUCCESS' && res.url) {
  23379. loader = me.document.getElementById(loadingId);
  23380. loader.setAttribute('src', link);
  23381. loader.setAttribute('_src', link);
  23382. loader.setAttribute('title', res.title || '');
  23383. loader.setAttribute('alt', res.original || '');
  23384. loader.removeAttribute('id');
  23385. domUtils.removeClasses(loader, 'loadingclass');
  23386. me.fireEvent('contentchange');
  23387. } else {
  23388. showErrorLoader(res.state);
  23389. }
  23390. } else {
  23391. showErrorLoader(me.getLang('simpleupload.loadError'));
  23392. }
  23393. };
  23394. xhr.onerror = function() {
  23395. showErrorLoader(me.getLang('simpleupload.loadError'));
  23396. };
  23397. xhr.send(new FormData(form));
  23398. form.reset();
  23399. });
  23400. }
  23401. return {
  23402. bindEvents: {
  23403. 'ready': function() {
  23404. //设置loading的样式
  23405. utils.cssRule('loading',
  23406. '.loadingclass{display:inline-block;cursor:default;background: url(\'' +
  23407. this.options.themePath +
  23408. this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  23409. '.loaderrorclass{display:inline-block;cursor:default;background: url(\'' +
  23410. this.options.themePath +
  23411. this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  23412. '}',
  23413. this.document);
  23414. },
  23415. /* 初始化简单上传按钮 */
  23416. 'simpleuploadbtnready': function(type, container) {
  23417. containerBtn = container;
  23418. me.afterConfigReady(initUploadBtn);
  23419. },
  23420. },
  23421. outputRule: function(root) {
  23422. utils.each(root.getNodesByTagName('img'), function(n) {
  23423. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  23424. n.parentNode.removeChild(n);
  23425. }
  23426. });
  23427. },
  23428. };
  23429. });
  23430. // plugins/serverparam.js
  23431. /**
  23432. * 服务器提交的额外参数列表设置插件
  23433. * @file
  23434. * @since 1.2.6.1
  23435. */
  23436. UE.plugin.register('serverparam', function() {
  23437. var me = this,
  23438. serverParam = {};
  23439. return {
  23440. commands: {
  23441. /**
  23442. * 修改服务器提交的额外参数列表,清除所有项
  23443. * @command serverparam
  23444. * @method execCommand
  23445. * @param { String } cmd 命令字符串
  23446. * @example
  23447. * ```javascript
  23448. * editor.execCommand('serverparam');
  23449. * editor.queryCommandValue('serverparam'); //返回空
  23450. * ```
  23451. */
  23452. /**
  23453. * 修改服务器提交的额外参数列表,删除指定项
  23454. * @command serverparam
  23455. * @method execCommand
  23456. * @param { String } cmd 命令字符串
  23457. * @param { String } key 要清除的属性
  23458. * @example
  23459. * ```javascript
  23460. * editor.execCommand('serverparam', 'name'); //删除属性name
  23461. * ```
  23462. */
  23463. /**
  23464. * 修改服务器提交的额外参数列表,使用键值添加项
  23465. * @command serverparam
  23466. * @method execCommand
  23467. * @param { String } cmd 命令字符串
  23468. * @param { String } key 要添加的属性
  23469. * @param { String } value 要添加属性的值
  23470. * @example
  23471. * ```javascript
  23472. * editor.execCommand('serverparam', 'name', 'hello');
  23473. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  23474. * ```
  23475. */
  23476. /**
  23477. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  23478. * @command serverparam
  23479. * @method execCommand
  23480. * @param { String } cmd 命令字符串
  23481. * @param { Object } key 传入的键值对对象
  23482. * @example
  23483. * ```javascript
  23484. * editor.execCommand('serverparam', {'name': 'hello'});
  23485. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  23486. * ```
  23487. */
  23488. /**
  23489. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  23490. * @command serverparam
  23491. * @method execCommand
  23492. * @param { String } cmd 命令字符串
  23493. * @param { Function } key 自定义获取参数的函数
  23494. * @example
  23495. * ```javascript
  23496. * editor.execCommand('serverparam', function(editor){
  23497. * return {'key': 'value'};
  23498. * });
  23499. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  23500. * ```
  23501. */
  23502. /**
  23503. * 获取服务器提交的额外参数列表
  23504. * @command serverparam
  23505. * @method queryCommandValue
  23506. * @param { String } cmd 命令字符串
  23507. * @example
  23508. * ```javascript
  23509. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  23510. * ```
  23511. */
  23512. 'serverparam': {
  23513. execCommand: function (cmd, key, value) {
  23514. if (key === undefined || key === null) { //不传参数,清空列表
  23515. serverParam = {};
  23516. } else if (utils.isString(key)) { //传入键值
  23517. if (value === undefined || value === null) {
  23518. delete serverParam[key];
  23519. } else {
  23520. serverParam[key] = value;
  23521. }
  23522. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  23523. utils.extend(serverParam, key, true);
  23524. } else if (utils.isFunction(key)) { //传入函数,添加列表项
  23525. utils.extend(serverParam, key(), true);
  23526. }
  23527. },
  23528. queryCommandValue: function () {
  23529. return serverParam || {};
  23530. }
  23531. }
  23532. }
  23533. }
  23534. });
  23535. // plugins/insertfile.js
  23536. /**
  23537. * 插入附件
  23538. */
  23539. UE.plugin.register('insertfile', function() {
  23540. var me = this;
  23541. function getFileIcon(url) {
  23542. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  23543. maps = {
  23544. "rar": "icon_rar.gif",
  23545. "zip": "icon_rar.gif",
  23546. "tar": "icon_rar.gif",
  23547. "gz": "icon_rar.gif",
  23548. "bz2": "icon_rar.gif",
  23549. "doc": "icon_doc.gif",
  23550. "docx": "icon_doc.gif",
  23551. "pdf": "icon_pdf.gif",
  23552. "mp3": "icon_mp3.gif",
  23553. "xls": "icon_xls.gif",
  23554. "chm": "icon_chm.gif",
  23555. "ppt": "icon_ppt.gif",
  23556. "pptx": "icon_ppt.gif",
  23557. "avi": "icon_mv.gif",
  23558. "rmvb": "icon_mv.gif",
  23559. "wmv": "icon_mv.gif",
  23560. "flv": "icon_mv.gif",
  23561. "swf": "icon_mv.gif",
  23562. "rm": "icon_mv.gif",
  23563. "exe": "icon_exe.gif",
  23564. "psd": "icon_psd.gif",
  23565. "txt": "icon_txt.gif",
  23566. "jpg": "icon_jpg.gif",
  23567. "png": "icon_jpg.gif",
  23568. "jpeg": "icon_jpg.gif",
  23569. "gif": "icon_jpg.gif",
  23570. "ico": "icon_jpg.gif",
  23571. "bmp": "icon_jpg.gif"
  23572. };
  23573. return maps[ext] ? maps[ext] : maps['txt'];
  23574. }
  23575. return {
  23576. commands: {
  23577. 'insertfile': {
  23578. execCommand: function(command, filelist) {
  23579. filelist = utils.isArray(filelist) ? filelist : [filelist];
  23580. var i, item, icon, title,
  23581. html = '',
  23582. URL = me.getOpt('UEDITOR_HOME_URL'),
  23583. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '' : '/') + 'dialogs/attachment/fileTypeImages/';
  23584. for (i = 0; i < filelist.length; i++) {
  23585. item = filelist[i];
  23586. icon = iconDir + getFileIcon(item.url);
  23587. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  23588. html += '<p style="line-height: 16px;">' +
  23589. '<img style="vertical-align: middle; margin-right: 2px;" src="' + icon + '" _src="' + icon + '" />' +
  23590. '<a style="font-size:12px; color:#0066cc;" href="' + item.url + '" title="' + title + '">' + title + '</a>' +
  23591. '</p>';
  23592. }
  23593. me.execCommand('insertHtml', html);
  23594. }
  23595. }
  23596. }
  23597. }
  23598. });
  23599. // plugins/xssFilter.js
  23600. /**
  23601. * @file xssFilter.js
  23602. * @desc xss过滤器
  23603. * @author robbenmu
  23604. */
  23605. UE.plugins.xssFilter = function() {
  23606. var config = UEDITOR_CONFIG;
  23607. var whitList = config.whitList;
  23608. function filter(node) {
  23609. var tagName = node.tagName;
  23610. var attrs = node.attrs;
  23611. if (!whitList.hasOwnProperty(tagName)) {
  23612. node.parentNode.removeChild(node);
  23613. return false;
  23614. }
  23615. UE.utils.each(attrs, function(val, key) {
  23616. if (whitList[tagName].indexOf(key) === -1) {
  23617. node.setAttr(key);
  23618. }
  23619. });
  23620. }
  23621. // 添加inserthtml\paste等操作用的过滤规则
  23622. if (whitList && config.xssFilterRules) {
  23623. this.options.filterRules = function() {
  23624. var result = {};
  23625. UE.utils.each(whitList, function(val, key) {
  23626. result[key] = function(node) {
  23627. return filter(node);
  23628. };
  23629. });
  23630. return result;
  23631. }();
  23632. }
  23633. var tagList = [];
  23634. UE.utils.each(whitList, function(val, key) {
  23635. tagList.push(key);
  23636. });
  23637. // 添加input过滤规则
  23638. //
  23639. if (whitList && config.inputXssFilter) {
  23640. this.addInputRule(function(root) {
  23641. root.traversal(function(node) {
  23642. if (node.type !== 'element') {
  23643. return false;
  23644. }
  23645. filter(node);
  23646. });
  23647. });
  23648. }
  23649. // 添加output过滤规则
  23650. //
  23651. if (whitList && config.outputXssFilter) {
  23652. this.addOutputRule(function(root) {
  23653. root.traversal(function(node) {
  23654. if (node.type !== 'element') {
  23655. return false;
  23656. }
  23657. filter(node);
  23658. });
  23659. });
  23660. }
  23661. };
  23662. // ui/ui.js
  23663. var baidu = baidu || {};
  23664. baidu.editor = baidu.editor || {};
  23665. UE.ui = baidu.editor.ui = {};
  23666. // ui/uiutils.js
  23667. (function() {
  23668. var browser = baidu.editor.browser,
  23669. domUtils = baidu.editor.dom.domUtils;
  23670. var magic = '$EDITORUI';
  23671. var root = window[magic] = {};
  23672. var uidMagic = 'ID' + magic;
  23673. var uidCount = 0;
  23674. var uiUtils = baidu.editor.ui.uiUtils = {
  23675. uid: function (obj) {
  23676. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++uidCount) : ++uidCount);
  23677. },
  23678. hook: function (fn, callback) {
  23679. var dg;
  23680. if (fn && fn._callbacks) {
  23681. dg = fn;
  23682. } else {
  23683. dg = function () {
  23684. var q;
  23685. if (fn) {
  23686. q = fn.apply(this, arguments);
  23687. }
  23688. var callbacks = dg._callbacks;
  23689. var k = callbacks.length;
  23690. while (k--) {
  23691. var r = callbacks[k].apply(this, arguments);
  23692. if (q === undefined) {
  23693. q = r;
  23694. }
  23695. }
  23696. return q;
  23697. };
  23698. dg._callbacks = [];
  23699. }
  23700. dg._callbacks.push(callback);
  23701. return dg;
  23702. },
  23703. createElementByHtml: function (html) {
  23704. var el = document.createElement('div');
  23705. el.innerHTML = html;
  23706. el = el.firstChild;
  23707. el.parentNode.removeChild(el);
  23708. return el;
  23709. },
  23710. getViewportElement: function () {
  23711. return (browser.ie && browser.quirks) ?
  23712. document.body : document.documentElement;
  23713. },
  23714. getClientRect: function (element) {
  23715. var bcr;
  23716. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  23717. try {
  23718. bcr = element.getBoundingClientRect();
  23719. } catch (e) {
  23720. bcr = {left: 0, top: 0, height: 0, width: 0}
  23721. }
  23722. var rect = {
  23723. left: Math.round(bcr.left),
  23724. top: Math.round(bcr.top),
  23725. height: Math.round(bcr.bottom - bcr.top),
  23726. width: Math.round(bcr.right - bcr.left)
  23727. };
  23728. var doc;
  23729. while ((doc = element.ownerDocument) !== document &&
  23730. (element = domUtils.getWindow(doc).frameElement)) {
  23731. bcr = element.getBoundingClientRect();
  23732. rect.left += bcr.left;
  23733. rect.top += bcr.top;
  23734. }
  23735. rect.bottom = rect.top + rect.height;
  23736. rect.right = rect.left + rect.width;
  23737. return rect;
  23738. },
  23739. getViewportRect: function () {
  23740. var viewportEl = uiUtils.getViewportElement();
  23741. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  23742. var height = (window.innerHeight || viewportEl.clientHeight) | 0;
  23743. return {
  23744. left: 0,
  23745. top: 0,
  23746. height: height,
  23747. width: width,
  23748. bottom: height,
  23749. right: width
  23750. };
  23751. },
  23752. setViewportOffset: function (element, offset) {
  23753. var rect;
  23754. var fixedLayer = uiUtils.getFixedLayer();
  23755. if (element.parentNode === fixedLayer) {
  23756. element.style.left = offset.left + 'px';
  23757. element.style.top = offset.top + 'px';
  23758. } else {
  23759. domUtils.setViewportOffset(element, offset);
  23760. }
  23761. },
  23762. getEventOffset: function (evt) {
  23763. var el = evt.target || evt.srcElement;
  23764. var rect = uiUtils.getClientRect(el);
  23765. var offset = uiUtils.getViewportOffsetByEvent(evt);
  23766. return {
  23767. left: offset.left - rect.left,
  23768. top: offset.top - rect.top
  23769. };
  23770. },
  23771. getViewportOffsetByEvent: function (evt) {
  23772. var el = evt.target || evt.srcElement;
  23773. var frameEl = domUtils.getWindow(el).frameElement;
  23774. var offset = {
  23775. left: evt.clientX,
  23776. top: evt.clientY
  23777. };
  23778. if (frameEl && el.ownerDocument !== document) {
  23779. var rect = uiUtils.getClientRect(frameEl);
  23780. offset.left += rect.left;
  23781. offset.top += rect.top;
  23782. }
  23783. return offset;
  23784. },
  23785. setGlobal: function (id, obj) {
  23786. root[id] = obj;
  23787. return magic + '["' + id + '"]';
  23788. },
  23789. unsetGlobal: function (id) {
  23790. delete root[id];
  23791. },
  23792. copyAttributes: function (tgt, src) {
  23793. var attributes = src.attributes;
  23794. var k = attributes.length;
  23795. while (k--) {
  23796. var attrNode = attributes[k];
  23797. if (attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified)) {
  23798. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  23799. }
  23800. }
  23801. if (src.className) {
  23802. domUtils.addClass(tgt, src.className);
  23803. }
  23804. if (src.style.cssText) {
  23805. tgt.style.cssText += ';' + src.style.cssText;
  23806. }
  23807. },
  23808. removeStyle: function (el, styleName) {
  23809. if (el.style.removeProperty) {
  23810. el.style.removeProperty(styleName);
  23811. } else if (el.style.removeAttribute) {
  23812. el.style.removeAttribute(styleName);
  23813. } else throw '';
  23814. },
  23815. contains: function (elA, elB) {
  23816. return elA && elB && (elA === elB ? false : (
  23817. elA.contains ? elA.contains(elB) :
  23818. elA.compareDocumentPosition(elB) & 16
  23819. ));
  23820. },
  23821. startDrag: function (evt, callbacks, doc) {
  23822. var doc = doc || document;
  23823. var startX = evt.clientX;
  23824. var startY = evt.clientY;
  23825. function handleMouseMove(evt) {
  23826. var x = evt.clientX - startX;
  23827. var y = evt.clientY - startY;
  23828. callbacks.ondragmove(x, y, evt);
  23829. if (evt.stopPropagation) {
  23830. evt.stopPropagation();
  23831. } else {
  23832. evt.cancelBubble = true;
  23833. }
  23834. }
  23835. if (doc.addEventListener) {
  23836. function handleMouseUp(evt) {
  23837. doc.removeEventListener('mousemove', handleMouseMove, true);
  23838. doc.removeEventListener('mouseup', handleMouseUp, true);
  23839. window.removeEventListener('mouseup', handleMouseUp, true);
  23840. callbacks.ondragstop();
  23841. }
  23842. doc.addEventListener('mousemove', handleMouseMove, true);
  23843. doc.addEventListener('mouseup', handleMouseUp, true);
  23844. window.addEventListener('mouseup', handleMouseUp, true);
  23845. evt.preventDefault();
  23846. } else {
  23847. var elm = evt.srcElement;
  23848. elm.setCapture();
  23849. function releaseCaptrue() {
  23850. elm.releaseCapture();
  23851. elm.detachEvent('onmousemove', handleMouseMove);
  23852. elm.detachEvent('onmouseup', releaseCaptrue);
  23853. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  23854. callbacks.ondragstop();
  23855. }
  23856. elm.attachEvent('onmousemove', handleMouseMove);
  23857. elm.attachEvent('onmouseup', releaseCaptrue);
  23858. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  23859. evt.returnValue = false;
  23860. }
  23861. callbacks.ondragstart();
  23862. },
  23863. getFixedLayer: function () {
  23864. var layer = document.getElementById('edui_fixedlayer');
  23865. if (layer == null) {
  23866. layer = document.createElement('div');
  23867. layer.id = 'edui_fixedlayer';
  23868. document.body.appendChild(layer);
  23869. if (browser.ie && browser.version <= 8) {
  23870. layer.style.position = 'absolute';
  23871. bindFixedLayer();
  23872. setTimeout(updateFixedOffset);
  23873. } else {
  23874. layer.style.position = 'fixed';
  23875. }
  23876. layer.style.left = '0';
  23877. layer.style.top = '0';
  23878. layer.style.width = '0';
  23879. layer.style.height = '0';
  23880. }
  23881. return layer;
  23882. },
  23883. makeUnselectable: function (element) {
  23884. if (browser.opera || (browser.ie && browser.version < 9)) {
  23885. element.unselectable = 'on';
  23886. if (element.hasChildNodes()) {
  23887. for (var i = 0; i < element.childNodes.length; i++) {
  23888. if (element.childNodes[i].nodeType == 1) {
  23889. uiUtils.makeUnselectable(element.childNodes[i]);
  23890. }
  23891. }
  23892. }
  23893. } else {
  23894. if (element.style.MozUserSelect !== undefined) {
  23895. element.style.MozUserSelect = 'none';
  23896. } else if (element.style.WebkitUserSelect !== undefined) {
  23897. element.style.WebkitUserSelect = 'none';
  23898. } else if (element.style.KhtmlUserSelect !== undefined) {
  23899. element.style.KhtmlUserSelect = 'none';
  23900. }
  23901. }
  23902. }
  23903. };
  23904. function updateFixedOffset() {
  23905. var layer = document.getElementById('edui_fixedlayer');
  23906. uiUtils.setViewportOffset(layer, {
  23907. left: 0,
  23908. top: 0
  23909. });
  23910. // layer.style.display = 'none';
  23911. // layer.style.display = 'block';
  23912. //#trace: 1354
  23913. // setTimeout(updateFixedOffset);
  23914. }
  23915. function bindFixedLayer(adjOffset) {
  23916. domUtils.on(window, 'scroll', updateFixedOffset);
  23917. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  23918. }
  23919. })();
  23920. // ui/uibase.js
  23921. (function() {
  23922. var utils = baidu.editor.utils,
  23923. uiUtils = baidu.editor.ui.uiUtils,
  23924. EventBase = baidu.editor.EventBase,
  23925. UIBase = baidu.editor.ui.UIBase = function() {
  23926. };
  23927. UIBase.prototype = {
  23928. className: '',
  23929. uiName: '',
  23930. initOptions: function(options) {
  23931. var me = this;
  23932. for (var k in options) {
  23933. me[k] = options[k];
  23934. }
  23935. this.id = this.id || 'edui' + uiUtils.uid();
  23936. },
  23937. initUIBase: function() {
  23938. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23939. },
  23940. render: function(holder) {
  23941. var html = this.renderHtml();
  23942. var el = uiUtils.createElementByHtml(html);
  23943. //by xuheng 给每个node添加class
  23944. var list = domUtils.getElementsByTagName(el, "*");
  23945. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23946. var layer = document.getElementById('edui_fixedlayer');
  23947. for (var i = 0, node; node = list[i++];) {
  23948. domUtils.addClass(node, theme);
  23949. }
  23950. domUtils.addClass(el, theme);
  23951. if (layer) {
  23952. layer.className = "";
  23953. domUtils.addClass(layer, theme);
  23954. }
  23955. var seatEl = this.getDom();
  23956. if (seatEl != null) {
  23957. seatEl.parentNode.replaceChild(el, seatEl);
  23958. uiUtils.copyAttributes(el, seatEl);
  23959. } else {
  23960. if (typeof holder == 'string') {
  23961. holder = document.getElementById(holder);
  23962. }
  23963. holder = holder || uiUtils.getFixedLayer();
  23964. domUtils.addClass(holder, theme);
  23965. holder.appendChild(el);
  23966. }
  23967. this.postRender();
  23968. },
  23969. getDom: function (name) {
  23970. if (!name) {
  23971. return document.getElementById(this.id);
  23972. } else {
  23973. return document.getElementById(this.id + '_' + name);
  23974. }
  23975. },
  23976. postRender: function () {
  23977. this.fireEvent('postrender');
  23978. },
  23979. getHtmlTpl: function () {
  23980. return '';
  23981. },
  23982. formatHtml: function (tpl) {
  23983. var prefix = 'edui-' + this.uiName;
  23984. return (tpl
  23985. .replace(/##/g, this.id)
  23986. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23987. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23988. .replace(/\$\$/g, this._globalKey));
  23989. },
  23990. renderHtml: function () {
  23991. return this.formatHtml(this.getHtmlTpl());
  23992. },
  23993. dispose: function () {
  23994. var box = this.getDom();
  23995. if (box) baidu.editor.dom.domUtils.remove(box);
  23996. uiUtils.unsetGlobal(this.id);
  23997. }
  23998. };
  23999. utils.inherits(UIBase, EventBase);
  24000. })();
  24001. // ui/separator.js
  24002. (function () {
  24003. var utils = baidu.editor.utils,
  24004. UIBase = baidu.editor.ui.UIBase,
  24005. Separator = baidu.editor.ui.Separator = function (options) {
  24006. this.initOptions(options);
  24007. this.initSeparator();
  24008. };
  24009. Separator.prototype = {
  24010. uiName: 'separator',
  24011. initSeparator: function () {
  24012. this.initUIBase();
  24013. },
  24014. getHtmlTpl: function () {
  24015. return '<div id="##" class="edui-box %%"></div>';
  24016. }
  24017. };
  24018. utils.inherits(Separator, UIBase);
  24019. })();
  24020. // ui/mask.js
  24021. ///import core
  24022. ///import uicore
  24023. (function() {
  24024. var utils = baidu.editor.utils,
  24025. domUtils = baidu.editor.dom.domUtils,
  24026. UIBase = baidu.editor.ui.UIBase,
  24027. uiUtils = baidu.editor.ui.uiUtils;
  24028. var Mask = baidu.editor.ui.Mask = function (options) {
  24029. this.initOptions(options);
  24030. this.initUIBase();
  24031. };
  24032. Mask.prototype = {
  24033. getHtmlTpl: function () {
  24034. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  24035. },
  24036. postRender: function () {
  24037. var me = this;
  24038. domUtils.on(window, 'resize', function () {
  24039. setTimeout(function () {
  24040. if (!me.isHidden()) {
  24041. me._fill();
  24042. }
  24043. });
  24044. });
  24045. },
  24046. show: function (zIndex) {
  24047. this._fill();
  24048. this.getDom().style.display = '';
  24049. this.getDom().style.zIndex = zIndex;
  24050. },
  24051. hide: function () {
  24052. this.getDom().style.display = 'none';
  24053. this.getDom().style.zIndex = '';
  24054. },
  24055. isHidden: function () {
  24056. return this.getDom().style.display == 'none';
  24057. },
  24058. _onMouseDown: function () {
  24059. return false;
  24060. },
  24061. _onClick: function (e, target) {
  24062. this.fireEvent('click', e, target);
  24063. },
  24064. _fill: function () {
  24065. var el = this.getDom();
  24066. var vpRect = uiUtils.getViewportRect();
  24067. el.style.width = vpRect.width + 'px';
  24068. el.style.height = vpRect.height + 'px';
  24069. }
  24070. };
  24071. utils.inherits(Mask, UIBase);
  24072. })();
  24073. // ui/popup.js
  24074. ///import core
  24075. ///import uicore
  24076. (function() {
  24077. var utils = baidu.editor.utils,
  24078. uiUtils = baidu.editor.ui.uiUtils,
  24079. domUtils = baidu.editor.dom.domUtils,
  24080. UIBase = baidu.editor.ui.UIBase,
  24081. Popup = baidu.editor.ui.Popup = function(options) {
  24082. this.initOptions(options);
  24083. this.initPopup();
  24084. };
  24085. var allPopups = [];
  24086. function closeAllPopup(evt, el) {
  24087. for (var i = 0; i < allPopups.length; i++) {
  24088. var pop = allPopups[i];
  24089. if (!pop.isHidden()) {
  24090. if (pop.queryAutoHide(el) !== false) {
  24091. if (evt && /scroll/ig.test(evt.type) && pop.className == "edui-wordpastepop") return;
  24092. pop.hide();
  24093. }
  24094. }
  24095. }
  24096. if (allPopups.length)
  24097. pop.editor.fireEvent("afterhidepop");
  24098. }
  24099. Popup.postHide = closeAllPopup;
  24100. var ANCHOR_CLASSES = ['edui-anchor-topleft', 'edui-anchor-topright',
  24101. 'edui-anchor-bottomleft', 'edui-anchor-bottomright'];
  24102. Popup.prototype = {
  24103. SHADOW_RADIUS: 5,
  24104. content: null,
  24105. _hidden: false,
  24106. autoRender: true,
  24107. canSideLeft: true,
  24108. canSideUp: true,
  24109. initPopup: function () {
  24110. this.initUIBase();
  24111. allPopups.push(this);
  24112. },
  24113. getHtmlTpl: function () {
  24114. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  24115. ' <div id="##_body" class="edui-popup-body">' +
  24116. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  24117. ' <div class="edui-shadow"></div>' +
  24118. ' <div id="##_content" class="edui-popup-content">' +
  24119. this.getContentHtmlTpl() +
  24120. ' </div>' +
  24121. ' </div>' +
  24122. '</div>';
  24123. },
  24124. getContentHtmlTpl: function () {
  24125. if (this.content) {
  24126. if (typeof this.content == 'string') {
  24127. return this.content;
  24128. }
  24129. return this.content.renderHtml();
  24130. } else {
  24131. return ''
  24132. }
  24133. },
  24134. _UIBase_postRender: UIBase.prototype.postRender,
  24135. postRender: function() {
  24136. if (this.content instanceof UIBase) {
  24137. this.content.postRender();
  24138. }
  24139. //捕获鼠标滚轮
  24140. if (this.captureWheel && !this.captured) {
  24141. this.captured = true;
  24142. var winHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 80,
  24143. _height = this.getDom().offsetHeight,
  24144. _top = uiUtils.getClientRect(this.combox.getDom()).top,
  24145. content = this.getDom('content'),
  24146. ifr = this.getDom('body').getElementsByTagName('iframe'),
  24147. me = this;
  24148. ifr.length && (ifr = ifr[0]);
  24149. while (_top + _height > winHeight) {
  24150. _height -= 30;
  24151. }
  24152. content.style.height = _height + 'px';
  24153. //同步更改iframe高度
  24154. ifr && (ifr.style.height = _height + 'px');
  24155. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  24156. if (window.XMLHttpRequest) {
  24157. domUtils.on(content, ('onmousewheel' in document.body) ? 'mousewheel' : 'DOMMouseScroll', function(e) {
  24158. if (e.preventDefault) {
  24159. e.preventDefault();
  24160. } else {
  24161. e.returnValue = false;
  24162. }
  24163. if (e.wheelDelta) {
  24164. content.scrollTop -= (e.wheelDelta / 120) * 60;
  24165. } else {
  24166. content.scrollTop -= (e.detail / -3) * 60;
  24167. }
  24168. });
  24169. } else {
  24170. //ie6
  24171. domUtils.on(this.getDom(), 'mousewheel', function(e) {
  24172. e.returnValue = false;
  24173. me.getDom('content').scrollTop -= (e.wheelDelta / 120) * 60;
  24174. });
  24175. }
  24176. }
  24177. this.fireEvent('postRenderAfter');
  24178. this.hide(true);
  24179. this._UIBase_postRender();
  24180. },
  24181. _doAutoRender: function() {
  24182. if (!this.getDom() && this.autoRender) {
  24183. this.render();
  24184. }
  24185. },
  24186. mesureSize: function() {
  24187. var box = this.getDom('content');
  24188. return uiUtils.getClientRect(box);
  24189. },
  24190. fitSize: function() {
  24191. if (this.captureWheel && this.sized) {
  24192. return this.__size;
  24193. }
  24194. this.sized = true;
  24195. var popBodyEl = this.getDom('body');
  24196. popBodyEl.style.width = '';
  24197. popBodyEl.style.height = '';
  24198. var size = this.mesureSize();
  24199. if (this.captureWheel) {
  24200. popBodyEl.style.width = -(-20 - size.width) + 'px';
  24201. var height = parseInt(this.getDom('content').style.height, 10);
  24202. !window.isNaN(height) && (size.height = height);
  24203. } else {
  24204. popBodyEl.style.width = size.width + 'px';
  24205. }
  24206. popBodyEl.style.height = size.height + 'px';
  24207. this.__size = size;
  24208. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  24209. return size;
  24210. },
  24211. showAnchor: function(element, hoz) {
  24212. this.showAnchorRect(uiUtils.getClientRect(element), hoz);
  24213. },
  24214. showAnchorRect: function(rect, hoz, adj) {
  24215. this._doAutoRender();
  24216. var vpRect = uiUtils.getViewportRect();
  24217. this.getDom().style.visibility = 'hidden';
  24218. this._show();
  24219. var popSize = this.fitSize();
  24220. var sideLeft, sideUp, left, top;
  24221. if (hoz) {
  24222. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  24223. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  24224. left = (sideLeft ? rect.left - popSize.width : rect.right);
  24225. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  24226. } else {
  24227. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  24228. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  24229. left = (sideLeft ? rect.right - popSize.width : rect.left);
  24230. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  24231. }
  24232. var popEl = this.getDom();
  24233. uiUtils.setViewportOffset(popEl, {
  24234. left: left,
  24235. top: top
  24236. });
  24237. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  24238. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  24239. if (this.editor) {
  24240. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  24241. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  24242. }
  24243. this.getDom().style.visibility = 'visible';
  24244. },
  24245. showAt: function (offset) {
  24246. var left = offset.left;
  24247. var top = offset.top;
  24248. var rect = {
  24249. left: left,
  24250. top: top,
  24251. right: left,
  24252. bottom: top,
  24253. height: 0,
  24254. width: 0
  24255. };
  24256. this.showAnchorRect(rect, false, true);
  24257. },
  24258. _show: function () {
  24259. if (this._hidden) {
  24260. var box = this.getDom();
  24261. box.style.display = '';
  24262. this._hidden = false;
  24263. // if (box.setActive) {
  24264. // box.setActive();
  24265. // }
  24266. this.fireEvent('show');
  24267. }
  24268. },
  24269. isHidden: function () {
  24270. return this._hidden;
  24271. },
  24272. show: function () {
  24273. this._doAutoRender();
  24274. this._show();
  24275. },
  24276. hide: function (notNofity) {
  24277. if (!this._hidden && this.getDom()) {
  24278. this.getDom().style.display = 'none';
  24279. this._hidden = true;
  24280. if (!notNofity) {
  24281. this.fireEvent('hide');
  24282. }
  24283. }
  24284. },
  24285. queryAutoHide: function (el) {
  24286. return !el || !uiUtils.contains(this.getDom(), el);
  24287. }
  24288. };
  24289. utils.inherits(Popup, UIBase);
  24290. domUtils.on(document, 'mousedown', function(evt) {
  24291. var el = evt.target || evt.srcElement;
  24292. closeAllPopup(evt, el);
  24293. });
  24294. domUtils.on(window, 'scroll', function(evt, el) {
  24295. closeAllPopup(evt, el);
  24296. });
  24297. })();
  24298. // ui/colorpicker.js
  24299. ///import core
  24300. ///import uicore
  24301. (function () {
  24302. var utils = baidu.editor.utils,
  24303. UIBase = baidu.editor.ui.UIBase,
  24304. ColorPicker = baidu.editor.ui.ColorPicker = function (options) {
  24305. this.initOptions(options);
  24306. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  24307. this.initUIBase();
  24308. };
  24309. ColorPicker.prototype = {
  24310. getHtmlTpl: function () {
  24311. return genColorPicker(this.noColorText, this.editor);
  24312. },
  24313. _onTableClick: function (evt) {
  24314. var tgt = evt.target || evt.srcElement;
  24315. var color = tgt.getAttribute('data-color');
  24316. if (color) {
  24317. this.fireEvent('pickcolor', color);
  24318. }
  24319. },
  24320. _onTableOver: function (evt) {
  24321. var tgt = evt.target || evt.srcElement;
  24322. var color = tgt.getAttribute('data-color');
  24323. if (color) {
  24324. this.getDom('preview').style.backgroundColor = color;
  24325. }
  24326. },
  24327. _onTableOut: function () {
  24328. this.getDom('preview').style.backgroundColor = '';
  24329. },
  24330. _onPickNoColor: function () {
  24331. this.fireEvent('picknocolor');
  24332. }
  24333. };
  24334. utils.inherits(ColorPicker, UIBase);
  24335. var COLORS = (
  24336. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  24337. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  24338. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  24339. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  24340. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  24341. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  24342. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  24343. function genColorPicker(noColorText, editor) {
  24344. var html = '<div id="##" class="edui-colorpicker %%">' +
  24345. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  24346. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  24347. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">' + noColorText + '</div>' +
  24348. '</div>' +
  24349. '<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">' +
  24350. '<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>' +
  24351. '<tr class="edui-colorpicker-tablefirstrow" >';
  24352. for (var i = 0; i < COLORS.length; i++) {
  24353. if (i && i % 10 === 0) {
  24354. 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"' : '') + '>';
  24355. }
  24356. 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"' +
  24357. ' data-color="#' + COLORS[i] + '"' +
  24358. ' style="background-color:#' + COLORS[i] + ';border:solid #ccc;' +
  24359. (i < 10 || i >= 60 ? 'border-width:1px;' :
  24360. i >= 10 && i < 20 ? 'border-width:1px 1px 0 1px;' :
  24361. 'border-width:0 1px 0 1px;') +
  24362. '"' +
  24363. '></a></td>' : '';
  24364. }
  24365. html += '</tr></table></div>';
  24366. return html;
  24367. }
  24368. })();
  24369. // ui/tablepicker.js
  24370. ///import core
  24371. ///import uicore
  24372. (function() {
  24373. var utils = baidu.editor.utils,
  24374. uiUtils = baidu.editor.ui.uiUtils,
  24375. UIBase = baidu.editor.ui.UIBase;
  24376. var TablePicker = baidu.editor.ui.TablePicker = function (options) {
  24377. this.initOptions(options);
  24378. this.initTablePicker();
  24379. };
  24380. TablePicker.prototype = {
  24381. defaultNumRows: 10,
  24382. defaultNumCols: 10,
  24383. maxNumRows: 20,
  24384. maxNumCols: 20,
  24385. numRows: 10,
  24386. numCols: 10,
  24387. lengthOfCellSide: 22,
  24388. initTablePicker: function () {
  24389. this.initUIBase();
  24390. },
  24391. getHtmlTpl: function () {
  24392. var me = this;
  24393. return '<div id="##" class="edui-tablepicker %%">' +
  24394. '<div class="edui-tablepicker-body">' +
  24395. '<div class="edui-infoarea">' +
  24396. '<span id="##_label" class="edui-label"></span>' +
  24397. '</div>' +
  24398. '<div class="edui-pickarea"' +
  24399. ' onmousemove="$$._onMouseMove(event, this);"' +
  24400. ' onmouseover="$$._onMouseOver(event, this);"' +
  24401. ' onmouseout="$$._onMouseOut(event, this);"' +
  24402. ' onclick="$$._onClick(event, this);"' +
  24403. '>' +
  24404. '<div id="##_overlay" class="edui-overlay"></div>' +
  24405. '</div>' +
  24406. '</div>' +
  24407. '</div>';
  24408. },
  24409. _UIBase_render: UIBase.prototype.render,
  24410. render: function (holder) {
  24411. this._UIBase_render(holder);
  24412. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_row") + ' x 0' + this.editor.getLang("t_col");
  24413. },
  24414. _track: function (numCols, numRows) {
  24415. var style = this.getDom('overlay').style;
  24416. var sideLen = this.lengthOfCellSide;
  24417. style.width = numCols * sideLen + 'px';
  24418. style.height = numRows * sideLen + 'px';
  24419. var label = this.getDom('label');
  24420. label.innerHTML = numCols + this.editor.getLang("t_col") + ' x ' + numRows + this.editor.getLang("t_row");
  24421. this.numCols = numCols;
  24422. this.numRows = numRows;
  24423. },
  24424. _onMouseOver: function (evt, el) {
  24425. var rel = evt.relatedTarget || evt.fromElement;
  24426. if (!uiUtils.contains(el, rel) && el !== rel) {
  24427. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_col") + ' x 0' + this.editor.getLang("t_row");
  24428. this.getDom('overlay').style.visibility = '';
  24429. }
  24430. },
  24431. _onMouseOut: function (evt, el) {
  24432. var rel = evt.relatedTarget || evt.toElement;
  24433. if (!uiUtils.contains(el, rel) && el !== rel) {
  24434. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_col") + ' x 0' + this.editor.getLang("t_row");
  24435. this.getDom('overlay').style.visibility = 'hidden';
  24436. }
  24437. },
  24438. _onMouseMove: function (evt, el) {
  24439. var style = this.getDom('overlay').style;
  24440. var offset = uiUtils.getEventOffset(evt);
  24441. var sideLen = this.lengthOfCellSide;
  24442. var numCols = Math.ceil(offset.left / sideLen);
  24443. var numRows = Math.ceil(offset.top / sideLen);
  24444. this._track(numCols, numRows);
  24445. },
  24446. _onClick: function () {
  24447. this.fireEvent('picktable', this.numCols, this.numRows);
  24448. }
  24449. };
  24450. utils.inherits(TablePicker, UIBase);
  24451. })();
  24452. // ui/stateful.js
  24453. (function() {
  24454. var browser = baidu.editor.browser,
  24455. domUtils = baidu.editor.dom.domUtils,
  24456. uiUtils = baidu.editor.ui.uiUtils;
  24457. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  24458. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  24459. (browser.ie ? (
  24460. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  24461. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"')
  24462. : (
  24463. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  24464. ' onmouseout="$$.Stateful_onMouseOut(event, this);"'));
  24465. baidu.editor.ui.Stateful = {
  24466. alwalysHoverable: false,
  24467. target: null,//目标元素和this指向dom不一样
  24468. Stateful_init: function () {
  24469. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  24470. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  24471. },
  24472. Stateful_getHtmlTpl: function () {
  24473. var tpl = this._Stateful_dGetHtmlTpl();
  24474. // 使用function避免$转义
  24475. return tpl.replace(/stateful/g, function () {
  24476. return TPL_STATEFUL;
  24477. });
  24478. },
  24479. Stateful_onMouseEnter: function (evt, el) {
  24480. this.target = el;
  24481. if (!this.isDisabled() || this.alwalysHoverable) {
  24482. this.addState('hover');
  24483. this.fireEvent('over');
  24484. }
  24485. },
  24486. Stateful_onMouseLeave: function (evt, el) {
  24487. if (!this.isDisabled() || this.alwalysHoverable) {
  24488. this.removeState('hover');
  24489. this.removeState('active');
  24490. this.fireEvent('out');
  24491. }
  24492. },
  24493. Stateful_onMouseOver: function (evt, el) {
  24494. var rel = evt.relatedTarget;
  24495. if (!uiUtils.contains(el, rel) && el !== rel) {
  24496. this.Stateful_onMouseEnter(evt, el);
  24497. }
  24498. },
  24499. Stateful_onMouseOut: function (evt, el) {
  24500. var rel = evt.relatedTarget;
  24501. if (!uiUtils.contains(el, rel) && el !== rel) {
  24502. this.Stateful_onMouseLeave(evt, el);
  24503. }
  24504. },
  24505. Stateful_onMouseDown: function (evt, el) {
  24506. if (!this.isDisabled()) {
  24507. this.addState('active');
  24508. }
  24509. },
  24510. Stateful_onMouseUp: function (evt, el) {
  24511. if (!this.isDisabled()) {
  24512. this.removeState('active');
  24513. }
  24514. },
  24515. Stateful_postRender: function () {
  24516. if (this.disabled && !this.hasState('disabled')) {
  24517. this.addState('disabled');
  24518. }
  24519. },
  24520. hasState: function (state) {
  24521. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  24522. },
  24523. addState: function (state) {
  24524. if (!this.hasState(state)) {
  24525. this.getStateDom().className += ' edui-state-' + state;
  24526. }
  24527. },
  24528. removeState: function (state) {
  24529. if (this.hasState(state)) {
  24530. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  24531. }
  24532. },
  24533. getStateDom: function () {
  24534. return this.getDom('state');
  24535. },
  24536. isChecked: function () {
  24537. return this.hasState('checked');
  24538. },
  24539. setChecked: function (checked) {
  24540. if (!this.isDisabled() && checked) {
  24541. this.addState('checked');
  24542. } else {
  24543. this.removeState('checked');
  24544. }
  24545. },
  24546. isDisabled: function () {
  24547. return this.hasState('disabled');
  24548. },
  24549. setDisabled: function (disabled) {
  24550. if (disabled) {
  24551. this.removeState('hover');
  24552. this.removeState('checked');
  24553. this.removeState('active');
  24554. this.addState('disabled');
  24555. } else {
  24556. this.removeState('disabled');
  24557. }
  24558. }
  24559. };
  24560. })();
  24561. // ui/button.js
  24562. ///import core
  24563. ///import uicore
  24564. ///import ui/stateful.js
  24565. (function () {
  24566. var utils = baidu.editor.utils,
  24567. UIBase = baidu.editor.ui.UIBase,
  24568. Stateful = baidu.editor.ui.Stateful,
  24569. Button = baidu.editor.ui.Button = function (options) {
  24570. if (options.name) {
  24571. var btnName = options.name;
  24572. var cssRules = options.cssRules;
  24573. if (!options.className) {
  24574. options.className = 'edui-for-' + btnName;
  24575. }
  24576. options.cssRules = '.edui-default .edui-for-' + btnName + ' .edui-icon {' + cssRules + '}'
  24577. }
  24578. this.initOptions(options);
  24579. this.initButton();
  24580. };
  24581. Button.prototype = {
  24582. uiName: 'button',
  24583. label: '',
  24584. title: '',
  24585. showIcon: true,
  24586. showText: true,
  24587. cssRules: '',
  24588. initButton: function () {
  24589. this.initUIBase();
  24590. this.Stateful_init();
  24591. if (this.cssRules) {
  24592. utils.cssRule('edui-customize-' + this.name + '-style', this.cssRules);
  24593. }
  24594. },
  24595. getHtmlTpl: function () {
  24596. return '<div id="##" class="edui-box %%">' +
  24597. '<div id="##_state" stateful>' +
  24598. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  24599. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  24600. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  24601. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  24602. '</div>' +
  24603. '</div>' +
  24604. '</div></div>';
  24605. },
  24606. postRender: function () {
  24607. this.Stateful_postRender();
  24608. this.setDisabled(this.disabled)
  24609. },
  24610. _onMouseDown: function (e) {
  24611. var target = e.target || e.srcElement,
  24612. tagName = target && target.tagName && target.tagName.toLowerCase();
  24613. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24614. return false;
  24615. }
  24616. },
  24617. _onClick: function () {
  24618. if (!this.isDisabled()) {
  24619. this.fireEvent('click');
  24620. }
  24621. },
  24622. setTitle: function (text) {
  24623. var label = this.getDom('label');
  24624. label.innerHTML = text;
  24625. }
  24626. };
  24627. utils.inherits(Button, UIBase);
  24628. utils.extend(Button.prototype, Stateful);
  24629. })();
  24630. // ui/splitbutton.js
  24631. ///import core
  24632. ///import uicore
  24633. ///import ui/stateful.js
  24634. (function () {
  24635. var utils = baidu.editor.utils,
  24636. uiUtils = baidu.editor.ui.uiUtils,
  24637. domUtils = baidu.editor.dom.domUtils,
  24638. UIBase = baidu.editor.ui.UIBase,
  24639. Stateful = baidu.editor.ui.Stateful,
  24640. SplitButton = baidu.editor.ui.SplitButton = function (options) {
  24641. this.initOptions(options);
  24642. this.initSplitButton();
  24643. };
  24644. SplitButton.prototype = {
  24645. popup: null,
  24646. uiName: 'splitbutton',
  24647. title: '',
  24648. initSplitButton: function () {
  24649. this.initUIBase();
  24650. this.Stateful_init();
  24651. var me = this;
  24652. if (this.popup != null) {
  24653. var popup = this.popup;
  24654. this.popup = null;
  24655. this.setPopup(popup);
  24656. }
  24657. },
  24658. _UIBase_postRender: UIBase.prototype.postRender,
  24659. postRender: function () {
  24660. this.Stateful_postRender();
  24661. this._UIBase_postRender();
  24662. },
  24663. setPopup: function (popup) {
  24664. if (this.popup === popup) return;
  24665. if (this.popup != null) {
  24666. this.popup.dispose();
  24667. }
  24668. popup.addListener('show', utils.bind(this._onPopupShow, this));
  24669. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  24670. popup.addListener('postrender', utils.bind(function () {
  24671. popup.getDom('body').appendChild(
  24672. uiUtils.createElementByHtml('<div id="' +
  24673. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  24674. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  24675. );
  24676. popup.getDom().className += ' ' + this.className;
  24677. }, this));
  24678. this.popup = popup;
  24679. },
  24680. _onPopupShow: function () {
  24681. this.addState('opened');
  24682. },
  24683. _onPopupHide: function () {
  24684. this.removeState('opened');
  24685. },
  24686. getHtmlTpl: function () {
  24687. return '<div id="##" class="edui-box %%">' +
  24688. '<div ' + (this.title ? 'title="' + this.title + '"' : '') + ' id="##_state" stateful><div class="%%-body">' +
  24689. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  24690. '<div class="edui-box edui-icon"></div>' +
  24691. '</div>' +
  24692. '<div class="edui-box edui-splitborder"></div>' +
  24693. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  24694. '</div></div></div>';
  24695. },
  24696. showPopup: function () {
  24697. // 当popup往上弹出的时候,做特殊处理
  24698. var rect = uiUtils.getClientRect(this.getDom());
  24699. rect.top -= this.popup.SHADOW_RADIUS;
  24700. rect.height += this.popup.SHADOW_RADIUS;
  24701. this.popup.showAnchorRect(rect);
  24702. },
  24703. _onArrowClick: function (event, el) {
  24704. if (!this.isDisabled()) {
  24705. this.showPopup();
  24706. }
  24707. },
  24708. _onButtonClick: function () {
  24709. if (!this.isDisabled()) {
  24710. this.fireEvent('buttonclick');
  24711. }
  24712. }
  24713. };
  24714. utils.inherits(SplitButton, UIBase);
  24715. utils.extend(SplitButton.prototype, Stateful, true);
  24716. })();
  24717. // ui/colorbutton.js
  24718. ///import core
  24719. ///import uicore
  24720. ///import ui/colorpicker.js
  24721. ///import ui/popup.js
  24722. ///import ui/splitbutton.js
  24723. (function () {
  24724. var utils = baidu.editor.utils,
  24725. uiUtils = baidu.editor.ui.uiUtils,
  24726. ColorPicker = baidu.editor.ui.ColorPicker,
  24727. Popup = baidu.editor.ui.Popup,
  24728. SplitButton = baidu.editor.ui.SplitButton,
  24729. ColorButton = baidu.editor.ui.ColorButton = function (options) {
  24730. this.initOptions(options);
  24731. this.initColorButton();
  24732. };
  24733. ColorButton.prototype = {
  24734. initColorButton: function () {
  24735. var me = this;
  24736. this.popup = new Popup({
  24737. content: new ColorPicker({
  24738. noColorText: me.editor.getLang("clearColor"),
  24739. editor: me.editor,
  24740. onpickcolor: function (t, color) {
  24741. me._onPickColor(color);
  24742. },
  24743. onpicknocolor: function (t, color) {
  24744. me._onPickNoColor(color);
  24745. }
  24746. }),
  24747. editor: me.editor
  24748. });
  24749. this.initSplitButton();
  24750. },
  24751. _SplitButton_postRender: SplitButton.prototype.postRender,
  24752. postRender: function () {
  24753. this._SplitButton_postRender();
  24754. this.getDom('button_body').appendChild(
  24755. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  24756. );
  24757. this.getDom().className += ' edui-colorbutton';
  24758. },
  24759. setColor: function (color) {
  24760. this.getDom('colorlump').style.backgroundColor = color;
  24761. this.color = color;
  24762. },
  24763. _onPickColor: function (color) {
  24764. if (this.fireEvent('pickcolor', color) !== false) {
  24765. this.setColor(color);
  24766. this.popup.hide();
  24767. }
  24768. },
  24769. _onPickNoColor: function (color) {
  24770. if (this.fireEvent('picknocolor') !== false) {
  24771. this.popup.hide();
  24772. }
  24773. }
  24774. };
  24775. utils.inherits(ColorButton, SplitButton);
  24776. })();
  24777. // ui/tablebutton.js
  24778. ///import core
  24779. ///import uicore
  24780. ///import ui/popup.js
  24781. ///import ui/tablepicker.js
  24782. ///import ui/splitbutton.js
  24783. (function () {
  24784. var utils = baidu.editor.utils,
  24785. Popup = baidu.editor.ui.Popup,
  24786. TablePicker = baidu.editor.ui.TablePicker,
  24787. SplitButton = baidu.editor.ui.SplitButton,
  24788. TableButton = baidu.editor.ui.TableButton = function (options) {
  24789. this.initOptions(options);
  24790. this.initTableButton();
  24791. };
  24792. TableButton.prototype = {
  24793. initTableButton: function () {
  24794. var me = this;
  24795. this.popup = new Popup({
  24796. content: new TablePicker({
  24797. editor: me.editor,
  24798. onpicktable: function (t, numCols, numRows) {
  24799. me._onPickTable(numCols, numRows);
  24800. }
  24801. }),
  24802. 'editor': me.editor
  24803. });
  24804. this.initSplitButton();
  24805. },
  24806. _onPickTable: function (numCols, numRows) {
  24807. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  24808. this.popup.hide();
  24809. }
  24810. }
  24811. };
  24812. utils.inherits(TableButton, SplitButton);
  24813. })();
  24814. // ui/autotypesetpicker.js
  24815. ///import core
  24816. ///import uicore
  24817. (function() {
  24818. var utils = baidu.editor.utils,
  24819. UIBase = baidu.editor.ui.UIBase;
  24820. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  24821. this.initOptions(options);
  24822. this.initAutoTypeSetPicker();
  24823. };
  24824. AutoTypeSetPicker.prototype = {
  24825. initAutoTypeSetPicker: function () {
  24826. this.initUIBase();
  24827. },
  24828. getHtmlTpl: function () {
  24829. var me = this.editor,
  24830. opt = me.options.autotypeset,
  24831. lang = me.getLang("autoTypeSet");
  24832. var textAlignInputName = 'textAlignValue' + me.uid,
  24833. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  24834. symbolConverInputName = 'symbolConverValue' + me.uid;
  24835. return '<div id="##" class="edui-autotypesetpicker %%">' +
  24836. '<div class="edui-autotypesetpicker-body">' +
  24837. '<table >' +
  24838. '<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>' +
  24839. '<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>' +
  24840. '<tr>' +
  24841. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "") + '>' + lang.alignment + '</td>' +
  24842. '<td colspan="2" id="' + textAlignInputName + '">' +
  24843. '<input type="radio" name="' + textAlignInputName + '" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24844. '<input type="radio" name="' + textAlignInputName + '" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24845. '<input type="radio" name="' + textAlignInputName + '" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24846. '</td>' +
  24847. '</tr>' +
  24848. '<tr>' +
  24849. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "") + '>' + lang.imageFloat + '</td>' +
  24850. '<td nowrap id="' + imageBlockInputName + '">' +
  24851. '<input type="radio" name="' + imageBlockInputName + '" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  24852. '<input type="radio" name="' + imageBlockInputName + '" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24853. '<input type="radio" name="' + imageBlockInputName + '" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24854. '<input type="radio" name="' + imageBlockInputName + '" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24855. '</td>' +
  24856. '</tr>' +
  24857. '<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>' +
  24858. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "") + '>' + lang.removeHtml + '</td></tr>' +
  24859. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "") + '>' + lang.pasteFilter + '</td></tr>' +
  24860. '<tr>' +
  24861. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "") + '>' + lang.symbol + '</td>' +
  24862. '<td id="' + symbolConverInputName + '">' +
  24863. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "") + '>' + lang.bdc2sb +
  24864. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "") + '>' + lang.tobdc + '' +
  24865. '</td>' +
  24866. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  24867. '</tr>' +
  24868. '</table>' +
  24869. '</div>' +
  24870. '</div>';
  24871. },
  24872. _UIBase_render: UIBase.prototype.render
  24873. };
  24874. utils.inherits(AutoTypeSetPicker, UIBase);
  24875. })();
  24876. // ui/autotypesetbutton.js
  24877. ///import core
  24878. ///import uicore
  24879. ///import ui/popup.js
  24880. ///import ui/autotypesetpicker.js
  24881. ///import ui/splitbutton.js
  24882. (function() {
  24883. var utils = baidu.editor.utils,
  24884. Popup = baidu.editor.ui.Popup,
  24885. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  24886. SplitButton = baidu.editor.ui.SplitButton,
  24887. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function(options) {
  24888. this.initOptions(options);
  24889. this.initAutoTypeSetButton();
  24890. };
  24891. function getPara(me) {
  24892. var opt = {},
  24893. cont = me.getDom(),
  24894. editorId = me.editor.uid,
  24895. inputType = null,
  24896. attrName = null,
  24897. ipts = domUtils.getElementsByTagName(cont, "input");
  24898. for (var i = ipts.length - 1, ipt; ipt = ipts[i--];) {
  24899. inputType = ipt.getAttribute("type");
  24900. if (inputType == "checkbox") {
  24901. attrName = ipt.getAttribute("name");
  24902. opt[attrName] && delete opt[attrName];
  24903. if (ipt.checked) {
  24904. var attrValue = document.getElementById(attrName + "Value" + editorId);
  24905. if (attrValue) {
  24906. if (/input/ig.test(attrValue.tagName)) {
  24907. opt[attrName] = attrValue.value;
  24908. } else {
  24909. var iptChilds = attrValue.getElementsByTagName("input");
  24910. for (var j = iptChilds.length - 1, iptchild; iptchild = iptChilds[j--];) {
  24911. if (iptchild.checked) {
  24912. opt[attrName] = iptchild.value;
  24913. break;
  24914. }
  24915. }
  24916. }
  24917. } else {
  24918. opt[attrName] = true;
  24919. }
  24920. } else {
  24921. opt[attrName] = false;
  24922. }
  24923. } else {
  24924. opt[ipt.getAttribute("value")] = ipt.checked;
  24925. }
  24926. }
  24927. var selects = domUtils.getElementsByTagName(cont, "select");
  24928. for (var i = 0, si; si = selects[i++];) {
  24929. var attr = si.getAttribute('name');
  24930. opt[attr] = opt[attr] ? si.value : '';
  24931. }
  24932. utils.extend(me.editor.options.autotypeset, opt);
  24933. me.editor.setPreferences('autotypeset', opt);
  24934. }
  24935. AutoTypeSetButton.prototype = {
  24936. initAutoTypeSetButton: function() {
  24937. var me = this;
  24938. this.popup = new Popup({
  24939. //传入配置参数
  24940. content: new AutoTypeSetPicker({editor: me.editor}),
  24941. 'editor': me.editor,
  24942. hide: function () {
  24943. if (!this._hidden && this.getDom()) {
  24944. getPara(this);
  24945. this.getDom().style.display = 'none';
  24946. this._hidden = true;
  24947. this.fireEvent('hide');
  24948. }
  24949. }
  24950. });
  24951. var flag = 0;
  24952. this.popup.addListener('postRenderAfter', function () {
  24953. var popupUI = this;
  24954. if (flag) return;
  24955. var cont = this.getDom(),
  24956. btn = cont.getElementsByTagName('button')[0];
  24957. btn.onclick = function () {
  24958. getPara(popupUI);
  24959. me.editor.execCommand('autotypeset');
  24960. popupUI.hide()
  24961. };
  24962. domUtils.on(cont, 'click', function(e) {
  24963. var target = e.target || e.srcElement,
  24964. editorId = me.editor.uid;
  24965. if (target && target.tagName == 'INPUT') {
  24966. // 点击图片浮动的checkbox,去除对应的radio
  24967. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24968. var checked = target.checked,
  24969. radioTd = document.getElementById(target.name + 'Value' + editorId),
  24970. radios = radioTd.getElementsByTagName('input'),
  24971. defalutSelect = {
  24972. 'imageBlockLine': 'none',
  24973. 'textAlign': 'left',
  24974. 'symbolConver': 'tobdc'
  24975. };
  24976. for (var i = 0; i < radios.length; i++) {
  24977. if (checked) {
  24978. if (radios[i].value == defalutSelect[target.name]) {
  24979. radios[i].checked = 'checked';
  24980. }
  24981. } else {
  24982. radios[i].checked = false;
  24983. }
  24984. }
  24985. }
  24986. // 点击radio,选中对应的checkbox
  24987. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24988. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24989. checkboxs && (checkboxs[0].checked = true);
  24990. }
  24991. getPara(popupUI);
  24992. }
  24993. });
  24994. flag = 1;
  24995. });
  24996. this.initSplitButton();
  24997. }
  24998. };
  24999. utils.inherits(AutoTypeSetButton, SplitButton);
  25000. })();
  25001. // ui/cellalignpicker.js
  25002. ///import core
  25003. ///import uicore
  25004. (function() {
  25005. var utils = baidu.editor.utils,
  25006. Popup = baidu.editor.ui.Popup,
  25007. Stateful = baidu.editor.ui.Stateful,
  25008. UIBase = baidu.editor.ui.UIBase;
  25009. /**
  25010. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  25011. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  25012. * @update 2013/4/2 hancong03@baidu.com
  25013. */
  25014. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function(options) {
  25015. this.initOptions(options);
  25016. this.initSelected();
  25017. this.initCellAlignPicker();
  25018. };
  25019. CellAlignPicker.prototype = {
  25020. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  25021. initSelected: function() {
  25022. var status = {
  25023. valign: {
  25024. top: 0,
  25025. middle: 1,
  25026. bottom: 2
  25027. },
  25028. align: {
  25029. left: 0,
  25030. center: 1,
  25031. right: 2
  25032. },
  25033. count: 3
  25034. },
  25035. result = -1;
  25036. if (this.selected) {
  25037. this.selectedIndex = status.valign[this.selected.valign] * status.count + status.align[this.selected.align];
  25038. }
  25039. },
  25040. initCellAlignPicker: function() {
  25041. this.initUIBase();
  25042. this.Stateful_init();
  25043. },
  25044. getHtmlTpl: function() {
  25045. var alignType = ['left', 'center', 'right'],
  25046. COUNT = 9,
  25047. tempClassName = null,
  25048. tempIndex = -1,
  25049. tmpl = [];
  25050. for (var i = 0; i < COUNT; i++) {
  25051. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  25052. tempIndex = i % 3;
  25053. tempIndex === 0 && tmpl.push('<tr>');
  25054. tmpl.push('<td index="' + i + '" ' + tempClassName + ' stateful><div class="edui-icon edui-' + alignType[tempIndex] + '"></div></td>');
  25055. tempIndex === 2 && tmpl.push('</tr>');
  25056. }
  25057. return '<div id="##" class="edui-cellalignpicker %%">' +
  25058. '<div class="edui-cellalignpicker-body">' +
  25059. '<table onclick="$$._onClick(event);">' +
  25060. tmpl.join('') +
  25061. '</table>' +
  25062. '</div>' +
  25063. '</div>';
  25064. },
  25065. getStateDom: function () {
  25066. return this.target;
  25067. },
  25068. _onClick: function (evt) {
  25069. var target = evt.target || evt.srcElement;
  25070. if (/icon/.test(target.className)) {
  25071. this.items[target.parentNode.getAttribute("index")].onclick();
  25072. Popup.postHide(evt);
  25073. }
  25074. },
  25075. _UIBase_render: UIBase.prototype.render
  25076. };
  25077. utils.inherits(CellAlignPicker, UIBase);
  25078. utils.extend(CellAlignPicker.prototype, Stateful, true);
  25079. })();
  25080. // ui/pastepicker.js
  25081. ///import core
  25082. ///import uicore
  25083. (function() {
  25084. var utils = baidu.editor.utils,
  25085. Stateful = baidu.editor.ui.Stateful,
  25086. uiUtils = baidu.editor.ui.uiUtils,
  25087. UIBase = baidu.editor.ui.UIBase;
  25088. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  25089. this.initOptions(options);
  25090. this.initPastePicker();
  25091. };
  25092. PastePicker.prototype = {
  25093. initPastePicker: function () {
  25094. this.initUIBase();
  25095. this.Stateful_init();
  25096. },
  25097. getHtmlTpl: function () {
  25098. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  25099. '<div class="edui-pastecontainer">' +
  25100. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  25101. '<div class="edui-button">' +
  25102. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  25103. '<div class="edui-richtxticon"></div></div>' +
  25104. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  25105. '<div class="edui-tagicon"></div></div>' +
  25106. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  25107. '<div class="edui-plaintxticon"></div></div>' +
  25108. '</div>' +
  25109. '</div>' +
  25110. '</div>'
  25111. },
  25112. getStateDom: function () {
  25113. return this.target;
  25114. },
  25115. format: function (param) {
  25116. this.editor.ui._isTransfer = true;
  25117. this.editor.fireEvent('pasteTransfer', param);
  25118. },
  25119. _onClick: function (cur) {
  25120. var node = domUtils.getNextDomNode(cur),
  25121. screenHt = uiUtils.getViewportRect().height,
  25122. subPop = uiUtils.getClientRect(node);
  25123. if ((subPop.top + subPop.height) > screenHt)
  25124. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  25125. else
  25126. node.style.top = "";
  25127. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  25128. node.style.visibility = "visible";
  25129. domUtils.addClass(cur, "edui-state-opened");
  25130. } else {
  25131. node.style.visibility = "hidden";
  25132. domUtils.removeClasses(cur, "edui-state-opened")
  25133. }
  25134. },
  25135. _UIBase_render: UIBase.prototype.render
  25136. };
  25137. utils.inherits(PastePicker, UIBase);
  25138. utils.extend(PastePicker.prototype, Stateful, true);
  25139. })();
  25140. // ui/toolbar.js
  25141. (function () {
  25142. var utils = baidu.editor.utils,
  25143. uiUtils = baidu.editor.ui.uiUtils,
  25144. UIBase = baidu.editor.ui.UIBase,
  25145. Toolbar = baidu.editor.ui.Toolbar = function (options) {
  25146. this.initOptions(options);
  25147. this.initToolbar();
  25148. };
  25149. Toolbar.prototype = {
  25150. items: null,
  25151. initToolbar: function () {
  25152. this.items = this.items || [];
  25153. this.initUIBase();
  25154. },
  25155. add: function (item, index) {
  25156. if (index === undefined) {
  25157. this.items.push(item);
  25158. } else {
  25159. this.items.splice(index, 0, item)
  25160. }
  25161. },
  25162. getHtmlTpl: function () {
  25163. var buff = [];
  25164. for (var i = 0; i < this.items.length; i++) {
  25165. buff[i] = this.items[i].renderHtml();
  25166. }
  25167. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  25168. buff.join('') +
  25169. '</div>'
  25170. },
  25171. postRender: function () {
  25172. var box = this.getDom();
  25173. for (var i = 0; i < this.items.length; i++) {
  25174. this.items[i].postRender();
  25175. }
  25176. uiUtils.makeUnselectable(box);
  25177. },
  25178. _onMouseDown: function (e) {
  25179. var target = e.target || e.srcElement,
  25180. tagName = target && target.tagName && target.tagName.toLowerCase();
  25181. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  25182. return false;
  25183. }
  25184. }
  25185. };
  25186. utils.inherits(Toolbar, UIBase);
  25187. })();
  25188. // ui/menu.js
  25189. ///import core
  25190. ///import uicore
  25191. ///import ui\popup.js
  25192. ///import ui\stateful.js
  25193. (function() {
  25194. var utils = baidu.editor.utils,
  25195. domUtils = baidu.editor.dom.domUtils,
  25196. uiUtils = baidu.editor.ui.uiUtils,
  25197. UIBase = baidu.editor.ui.UIBase,
  25198. Popup = baidu.editor.ui.Popup,
  25199. Stateful = baidu.editor.ui.Stateful,
  25200. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  25201. Menu = baidu.editor.ui.Menu = function(options) {
  25202. this.initOptions(options);
  25203. this.initMenu();
  25204. };
  25205. var menuSeparator = {
  25206. renderHtml: function () {
  25207. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  25208. },
  25209. postRender: function () {
  25210. },
  25211. queryAutoHide: function () {
  25212. return true;
  25213. }
  25214. };
  25215. Menu.prototype = {
  25216. items: null,
  25217. uiName: 'menu',
  25218. initMenu: function () {
  25219. this.items = this.items || [];
  25220. this.initPopup();
  25221. this.initItems();
  25222. },
  25223. initItems: function () {
  25224. for (var i = 0; i < this.items.length; i++) {
  25225. var item = this.items[i];
  25226. if (item == '-') {
  25227. this.items[i] = this.getSeparator();
  25228. } else if (!(item instanceof MenuItem)) {
  25229. item.editor = this.editor;
  25230. item.theme = this.editor.options.theme;
  25231. this.items[i] = this.createItem(item);
  25232. }
  25233. }
  25234. },
  25235. getSeparator: function () {
  25236. return menuSeparator;
  25237. },
  25238. createItem: function (item) {
  25239. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  25240. item.menu = this;
  25241. return new MenuItem(item);
  25242. },
  25243. _Popup_getContentHtmlTpl: Popup.prototype.getContentHtmlTpl,
  25244. getContentHtmlTpl: function () {
  25245. if (this.items.length == 0) {
  25246. return this._Popup_getContentHtmlTpl();
  25247. }
  25248. var buff = [];
  25249. for (var i = 0; i < this.items.length; i++) {
  25250. var item = this.items[i];
  25251. buff[i] = item.renderHtml();
  25252. }
  25253. return ('<div class="%%-body">' + buff.join('') + '</div>');
  25254. },
  25255. _Popup_postRender: Popup.prototype.postRender,
  25256. postRender: function () {
  25257. var me = this;
  25258. for (var i = 0; i < this.items.length; i++) {
  25259. var item = this.items[i];
  25260. item.ownerMenu = this;
  25261. item.postRender();
  25262. }
  25263. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  25264. evt = evt || event;
  25265. var rel = evt.relatedTarget || evt.fromElement;
  25266. var el = me.getDom();
  25267. if (!uiUtils.contains(el, rel) && el !== rel) {
  25268. me.fireEvent('over');
  25269. }
  25270. });
  25271. this._Popup_postRender();
  25272. },
  25273. queryAutoHide: function (el) {
  25274. if (el) {
  25275. if (uiUtils.contains(this.getDom(), el)) {
  25276. return false;
  25277. }
  25278. for (var i = 0; i < this.items.length; i++) {
  25279. var item = this.items[i];
  25280. if (item.queryAutoHide(el) === false) {
  25281. return false;
  25282. }
  25283. }
  25284. }
  25285. },
  25286. clearItems: function () {
  25287. for (var i = 0; i < this.items.length; i++) {
  25288. var item = this.items[i];
  25289. clearTimeout(item._showingTimer);
  25290. clearTimeout(item._closingTimer);
  25291. if (item.subMenu) {
  25292. item.subMenu.destroy();
  25293. }
  25294. }
  25295. this.items = [];
  25296. },
  25297. destroy: function () {
  25298. if (this.getDom()) {
  25299. domUtils.remove(this.getDom());
  25300. }
  25301. this.clearItems();
  25302. },
  25303. dispose: function () {
  25304. this.destroy();
  25305. }
  25306. };
  25307. utils.inherits(Menu, Popup);
  25308. /**
  25309. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  25310. * @type {Function}
  25311. */
  25312. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  25313. this.initOptions(options);
  25314. this.initUIBase();
  25315. this.Stateful_init();
  25316. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  25317. if (options.className && options.className.indexOf("aligntd") != -1) {
  25318. var me = this;
  25319. //获取单元格对齐初始状态
  25320. this.subMenu.selected = this.editor.queryCommandValue('cellalignment');
  25321. this.subMenu = new Popup({
  25322. content: new CellAlignPicker(this.subMenu),
  25323. parentMenu: me,
  25324. editor: me.editor,
  25325. destroy: function () {
  25326. if (this.getDom()) {
  25327. domUtils.remove(this.getDom());
  25328. }
  25329. }
  25330. });
  25331. this.subMenu.addListener("postRenderAfter", function () {
  25332. domUtils.on(this.getDom(), "mouseover", function () {
  25333. me.addState('opened');
  25334. });
  25335. });
  25336. } else {
  25337. this.subMenu = new Menu(this.subMenu);
  25338. }
  25339. }
  25340. };
  25341. MenuItem.prototype = {
  25342. label: '',
  25343. subMenu: null,
  25344. ownerMenu: null,
  25345. uiName: 'menuitem',
  25346. alwalysHoverable: true,
  25347. getHtmlTpl: function () {
  25348. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  25349. '<div class="%%-body">' +
  25350. this.renderLabelHtml() +
  25351. '</div>' +
  25352. '</div>';
  25353. },
  25354. postRender: function () {
  25355. var me = this;
  25356. this.addListener('over', function () {
  25357. me.ownerMenu.fireEvent('submenuover', me);
  25358. if (me.subMenu) {
  25359. me.delayShowSubMenu();
  25360. }
  25361. });
  25362. if (this.subMenu) {
  25363. this.getDom().className += ' edui-hassubmenu';
  25364. this.subMenu.render();
  25365. this.addListener('out', function () {
  25366. me.delayHideSubMenu();
  25367. });
  25368. this.subMenu.addListener('over', function () {
  25369. clearTimeout(me._closingTimer);
  25370. me._closingTimer = null;
  25371. me.addState('opened');
  25372. });
  25373. this.ownerMenu.addListener('hide', function () {
  25374. me.hideSubMenu();
  25375. });
  25376. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  25377. if (subMenu !== me) {
  25378. me.delayHideSubMenu();
  25379. }
  25380. });
  25381. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  25382. this.subMenu.queryAutoHide = function (el) {
  25383. if (el && uiUtils.contains(me.getDom(), el)) {
  25384. return false;
  25385. }
  25386. return this._bakQueryAutoHide(el);
  25387. };
  25388. }
  25389. this.getDom().style.tabIndex = '-1';
  25390. uiUtils.makeUnselectable(this.getDom());
  25391. this.Stateful_postRender();
  25392. },
  25393. delayShowSubMenu: function () {
  25394. var me = this;
  25395. if (!me.isDisabled()) {
  25396. me.addState('opened');
  25397. clearTimeout(me._showingTimer);
  25398. clearTimeout(me._closingTimer);
  25399. me._closingTimer = null;
  25400. me._showingTimer = setTimeout(function () {
  25401. me.showSubMenu();
  25402. }, 250);
  25403. }
  25404. },
  25405. delayHideSubMenu: function () {
  25406. var me = this;
  25407. if (!me.isDisabled()) {
  25408. me.removeState('opened');
  25409. clearTimeout(me._showingTimer);
  25410. if (!me._closingTimer) {
  25411. me._closingTimer = setTimeout(function () {
  25412. if (!me.hasState('opened')) {
  25413. me.hideSubMenu();
  25414. }
  25415. me._closingTimer = null;
  25416. }, 400);
  25417. }
  25418. }
  25419. },
  25420. renderLabelHtml: function () {
  25421. return '<div class="edui-arrow"></div>' +
  25422. '<div class="edui-box edui-icon"></div>' +
  25423. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  25424. },
  25425. getStateDom: function () {
  25426. return this.getDom();
  25427. },
  25428. queryAutoHide: function (el) {
  25429. if (this.subMenu && this.hasState('opened')) {
  25430. return this.subMenu.queryAutoHide(el);
  25431. }
  25432. },
  25433. _onClick: function (event, this_) {
  25434. if (this.hasState('disabled')) return;
  25435. if (this.fireEvent('click', event, this_) !== false) {
  25436. if (this.subMenu) {
  25437. this.showSubMenu();
  25438. } else {
  25439. Popup.postHide(event);
  25440. }
  25441. }
  25442. },
  25443. showSubMenu: function () {
  25444. var rect = uiUtils.getClientRect(this.getDom());
  25445. rect.right -= 5;
  25446. rect.left += 2;
  25447. rect.width -= 7;
  25448. rect.top -= 4;
  25449. rect.bottom += 4;
  25450. rect.height += 8;
  25451. this.subMenu.showAnchorRect(rect, true, true);
  25452. },
  25453. hideSubMenu: function () {
  25454. this.subMenu.hide();
  25455. }
  25456. };
  25457. utils.inherits(MenuItem, UIBase);
  25458. utils.extend(MenuItem.prototype, Stateful, true);
  25459. })();
  25460. // ui/combox.js
  25461. ///import core
  25462. ///import uicore
  25463. ///import ui/menu.js
  25464. ///import ui/splitbutton.js
  25465. (function () {
  25466. // todo: menu和item提成通用list
  25467. var utils = baidu.editor.utils,
  25468. uiUtils = baidu.editor.ui.uiUtils,
  25469. Menu = baidu.editor.ui.Menu,
  25470. SplitButton = baidu.editor.ui.SplitButton,
  25471. Combox = baidu.editor.ui.Combox = function (options) {
  25472. this.initOptions(options);
  25473. this.initCombox();
  25474. };
  25475. Combox.prototype = {
  25476. uiName: 'combox',
  25477. onbuttonclick: function () {
  25478. this.showPopup();
  25479. },
  25480. initCombox: function () {
  25481. var me = this;
  25482. this.items = this.items || [];
  25483. for (var i = 0; i < this.items.length; i++) {
  25484. var item = this.items[i];
  25485. item.uiName = 'listitem';
  25486. item.index = i;
  25487. item.onclick = function () {
  25488. me.selectByIndex(this.index);
  25489. };
  25490. }
  25491. this.popup = new Menu({
  25492. items: this.items,
  25493. uiName: 'list',
  25494. editor: this.editor,
  25495. captureWheel: true,
  25496. combox: this
  25497. });
  25498. this.initSplitButton();
  25499. },
  25500. _SplitButton_postRender: SplitButton.prototype.postRender,
  25501. postRender: function () {
  25502. this._SplitButton_postRender();
  25503. this.setLabel(this.label || '');
  25504. this.setValue(this.initValue || '');
  25505. },
  25506. showPopup: function () {
  25507. var rect = uiUtils.getClientRect(this.getDom());
  25508. rect.top += 1;
  25509. rect.bottom -= 1;
  25510. rect.height -= 2;
  25511. this.popup.showAnchorRect(rect);
  25512. },
  25513. getValue: function () {
  25514. return this.value;
  25515. },
  25516. setValue: function (value) {
  25517. var index = this.indexByValue(value);
  25518. if (index != -1) {
  25519. this.selectedIndex = index;
  25520. this.setLabel(this.items[index].label);
  25521. this.value = this.items[index].value;
  25522. } else {
  25523. this.selectedIndex = -1;
  25524. this.setLabel(this.getLabelForUnknowValue(value));
  25525. this.value = value;
  25526. }
  25527. },
  25528. setLabel: function (label) {
  25529. this.getDom('button_body').innerHTML = label;
  25530. this.label = label;
  25531. },
  25532. getLabelForUnknowValue: function (value) {
  25533. return value;
  25534. },
  25535. indexByValue: function (value) {
  25536. for (var i = 0; i < this.items.length; i++) {
  25537. if (value == this.items[i].value) {
  25538. return i;
  25539. }
  25540. }
  25541. return -1;
  25542. },
  25543. getItem: function (index) {
  25544. return this.items[index];
  25545. },
  25546. selectByIndex: function (index) {
  25547. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  25548. this.selectedIndex = index;
  25549. this.value = this.items[index].value;
  25550. this.setLabel(this.items[index].label);
  25551. }
  25552. }
  25553. };
  25554. utils.inherits(Combox, SplitButton);
  25555. })();
  25556. // ui/dialog.js
  25557. ///import core
  25558. ///import uicore
  25559. ///import ui/mask.js
  25560. ///import ui/button.js
  25561. (function () {
  25562. var utils = baidu.editor.utils,
  25563. domUtils = baidu.editor.dom.domUtils,
  25564. uiUtils = baidu.editor.ui.uiUtils,
  25565. Mask = baidu.editor.ui.Mask,
  25566. UIBase = baidu.editor.ui.UIBase,
  25567. Button = baidu.editor.ui.Button,
  25568. Dialog = baidu.editor.ui.Dialog = function (options) {
  25569. if (options.name) {
  25570. var name = options.name;
  25571. var cssRules = options.cssRules;
  25572. if (!options.className) {
  25573. options.className = 'edui-for-' + name;
  25574. }
  25575. if (cssRules) {
  25576. options.cssRules = '.edui-default .edui-for-' + name + ' .edui-dialog-content {' + cssRules + '}'
  25577. }
  25578. }
  25579. this.initOptions(utils.extend({
  25580. autoReset: true,
  25581. draggable: true,
  25582. onok: function () {
  25583. },
  25584. oncancel: function () {
  25585. },
  25586. onclose: function (t, ok) {
  25587. return ok ? this.onok() : this.oncancel();
  25588. },
  25589. //是否控制dialog中的scroll事件, 默认为不阻止
  25590. holdScroll: false
  25591. }, options));
  25592. this.initDialog();
  25593. };
  25594. var modalMask;
  25595. var dragMask;
  25596. var activeDialog;
  25597. Dialog.prototype = {
  25598. draggable: false,
  25599. uiName: 'dialog',
  25600. initDialog: function () {
  25601. var me = this,
  25602. theme = this.editor.options.theme;
  25603. if (this.cssRules) {
  25604. utils.cssRule('edui-customize-' + this.name + '-style', this.cssRules);
  25605. }
  25606. this.initUIBase();
  25607. this.modalMask = (modalMask || (modalMask = new Mask({
  25608. className: 'edui-dialog-modalmask',
  25609. theme: theme,
  25610. onclick: function () {
  25611. activeDialog && activeDialog.close(false);
  25612. }
  25613. })));
  25614. this.dragMask = (dragMask || (dragMask = new Mask({
  25615. className: 'edui-dialog-dragmask',
  25616. theme: theme
  25617. })));
  25618. this.closeButton = new Button({
  25619. className: 'edui-dialog-closebutton',
  25620. title: me.closeDialog,
  25621. theme: theme,
  25622. onclick: function () {
  25623. me.close(false);
  25624. }
  25625. });
  25626. this.fullscreen && this.initResizeEvent();
  25627. if (this.buttons) {
  25628. for (var i = 0; i < this.buttons.length; i++) {
  25629. if (!(this.buttons[i] instanceof Button)) {
  25630. this.buttons[i] = new Button(utils.extend(this.buttons[i], {
  25631. editor: this.editor
  25632. }, true));
  25633. }
  25634. }
  25635. }
  25636. },
  25637. initResizeEvent: function () {
  25638. var me = this;
  25639. domUtils.on(window, "resize", function () {
  25640. if (me._hidden || me._hidden === undefined) {
  25641. return;
  25642. }
  25643. if (me.__resizeTimer) {
  25644. window.clearTimeout(me.__resizeTimer);
  25645. }
  25646. me.__resizeTimer = window.setTimeout(function() {
  25647. me.__resizeTimer = null;
  25648. var dialogWrapNode = me.getDom(),
  25649. contentNode = me.getDom('content'),
  25650. wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode),
  25651. contentRect = UE.ui.uiUtils.getClientRect(contentNode),
  25652. vpRect = uiUtils.getViewportRect();
  25653. contentNode.style.width = (vpRect.width - wrapRect.width + contentRect.width) + "px";
  25654. contentNode.style.height = (vpRect.height - wrapRect.height + contentRect.height) + "px";
  25655. dialogWrapNode.style.width = vpRect.width + "px";
  25656. dialogWrapNode.style.height = vpRect.height + "px";
  25657. me.fireEvent("resize");
  25658. }, 100);
  25659. });
  25660. },
  25661. fitSize: function() {
  25662. var popBodyEl = this.getDom('body');
  25663. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  25664. // uiUtils.removeStyle(popBodyEl, 'width');
  25665. // uiUtils.removeStyle(popBodyEl, 'height');
  25666. // }
  25667. var size = this.mesureSize();
  25668. popBodyEl.style.width = size.width + 'px';
  25669. popBodyEl.style.height = size.height + 'px';
  25670. return size;
  25671. },
  25672. safeSetOffset: function(offset) {
  25673. var me = this;
  25674. var el = me.getDom();
  25675. var vpRect = uiUtils.getViewportRect();
  25676. var rect = uiUtils.getClientRect(el);
  25677. var left = offset.left;
  25678. if (left + rect.width > vpRect.right) {
  25679. left = vpRect.right - rect.width;
  25680. }
  25681. var top = offset.top;
  25682. if (top + rect.height > vpRect.bottom) {
  25683. top = vpRect.bottom - rect.height;
  25684. }
  25685. el.style.left = Math.max(left, 0) + 'px';
  25686. el.style.top = Math.max(top, 0) + 'px';
  25687. },
  25688. showAtCenter: function() {
  25689. var vpRect = uiUtils.getViewportRect();
  25690. if (!this.fullscreen) {
  25691. this.getDom().style.display = '';
  25692. var popSize = this.fitSize();
  25693. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  25694. var left = vpRect.width / 2 - popSize.width / 2;
  25695. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  25696. var popEl = this.getDom();
  25697. this.safeSetOffset({
  25698. left: Math.max(left | 0, 0),
  25699. top: Math.max(top | 0, 0)
  25700. });
  25701. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  25702. popEl.className += ' edui-state-centered';
  25703. }
  25704. } else {
  25705. var dialogWrapNode = this.getDom(),
  25706. contentNode = this.getDom('content');
  25707. dialogWrapNode.style.display = "block";
  25708. var wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode),
  25709. contentRect = UE.ui.uiUtils.getClientRect(contentNode);
  25710. dialogWrapNode.style.left = "-100000px";
  25711. contentNode.style.width = (vpRect.width - wrapRect.width + contentRect.width) + "px";
  25712. contentNode.style.height = (vpRect.height - wrapRect.height + contentRect.height) + "px";
  25713. dialogWrapNode.style.width = vpRect.width + "px";
  25714. dialogWrapNode.style.height = vpRect.height + "px";
  25715. dialogWrapNode.style.left = 0;
  25716. //保存环境的overflow值
  25717. this._originalContext = {
  25718. html: {
  25719. overflowX: document.documentElement.style.overflowX,
  25720. overflowY: document.documentElement.style.overflowY
  25721. },
  25722. body: {
  25723. overflowX: document.body.style.overflowX,
  25724. overflowY: document.body.style.overflowY
  25725. }
  25726. };
  25727. document.documentElement.style.overflowX = 'hidden';
  25728. document.documentElement.style.overflowY = 'hidden';
  25729. document.body.style.overflowX = 'hidden';
  25730. document.body.style.overflowY = 'hidden';
  25731. }
  25732. this._show();
  25733. },
  25734. getContentHtml: function() {
  25735. var contentHtml = '';
  25736. if (typeof this.content == 'string') {
  25737. contentHtml = this.content;
  25738. } else if (this.iframeUrl) {
  25739. contentHtml = '<span id="' + this.id + '_contmask" class="dialogcontmask"></span><iframe id="' + this.id +
  25740. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="' + this.iframeUrl + '"></iframe>';
  25741. }
  25742. return contentHtml;
  25743. },
  25744. getHtmlTpl: function() {
  25745. var footHtml = '';
  25746. if (this.buttons) {
  25747. var buff = [];
  25748. for (var i = 0; i < this.buttons.length; i++) {
  25749. buff[i] = this.buttons[i].renderHtml();
  25750. }
  25751. footHtml = '<div class="%%-foot">' +
  25752. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  25753. '</div>';
  25754. }
  25755. return '<div id="##" class="%%"><div ' + (!this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"') + '><div id="##_body" class="%%-body">' +
  25756. '<div class="%%-shadow"></div>' +
  25757. '<div id="##_titlebar" class="%%-titlebar">' +
  25758. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  25759. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  25760. '</div>' +
  25761. this.closeButton.renderHtml() +
  25762. '</div>' +
  25763. '<div id="##_content" class="%%-content">' + (this.autoReset ? '' : this.getContentHtml()) + '</div>' +
  25764. footHtml +
  25765. '</div></div></div>';
  25766. },
  25767. postRender: function() {
  25768. // todo: 保持居中/记住上次关闭位置选项
  25769. if (!this.modalMask.getDom()) {
  25770. this.modalMask.render();
  25771. this.modalMask.hide();
  25772. }
  25773. if (!this.dragMask.getDom()) {
  25774. this.dragMask.render();
  25775. this.dragMask.hide();
  25776. }
  25777. var me = this;
  25778. this.addListener('show', function() {
  25779. me.modalMask.show(this.getDom().style.zIndex - 2);
  25780. });
  25781. this.addListener('hide', function() {
  25782. me.modalMask.hide();
  25783. });
  25784. if (this.buttons) {
  25785. for (var i = 0; i < this.buttons.length; i++) {
  25786. this.buttons[i].postRender();
  25787. }
  25788. }
  25789. domUtils.on(window, 'resize', function() {
  25790. setTimeout(function() {
  25791. if (!me.isHidden()) {
  25792. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  25793. }
  25794. });
  25795. });
  25796. //hold住scroll事件,防止dialog的滚动影响页面
  25797. // if( this.holdScroll ) {
  25798. //
  25799. // if( !me.iframeUrl ) {
  25800. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  25801. // domUtils.preventDefault(e);
  25802. // } );
  25803. // } else {
  25804. // me.addListener('dialogafterreset', function(){
  25805. // window.setTimeout(function(){
  25806. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  25807. //
  25808. // if( browser.ie ) {
  25809. //
  25810. // var timer = window.setInterval(function(){
  25811. //
  25812. // if( iframeWindow.document && iframeWindow.document.body ) {
  25813. // window.clearInterval( timer );
  25814. // timer = null;
  25815. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  25816. // domUtils.preventDefault(e);
  25817. // } );
  25818. // }
  25819. //
  25820. // }, 100);
  25821. //
  25822. // } else {
  25823. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  25824. // domUtils.preventDefault(e);
  25825. // } );
  25826. // }
  25827. //
  25828. // }, 1);
  25829. // });
  25830. // }
  25831. //
  25832. // }
  25833. this._hide();
  25834. },
  25835. mesureSize: function () {
  25836. var body = this.getDom('body');
  25837. var width = uiUtils.getClientRect(this.getDom('content')).width;
  25838. var dialogBodyStyle = body.style;
  25839. dialogBodyStyle.width = width;
  25840. return uiUtils.getClientRect(body);
  25841. },
  25842. _onTitlebarMouseDown: function (evt, el) {
  25843. if (this.draggable) {
  25844. var rect;
  25845. var vpRect = uiUtils.getViewportRect();
  25846. var me = this;
  25847. uiUtils.startDrag(evt, {
  25848. ondragstart: function () {
  25849. rect = uiUtils.getClientRect(me.getDom());
  25850. me.getDom('contmask').style.visibility = 'visible';
  25851. me.dragMask.show(me.getDom().style.zIndex - 1);
  25852. },
  25853. ondragmove: function (x, y) {
  25854. var left = rect.left + x;
  25855. var top = rect.top + y;
  25856. me.safeSetOffset({
  25857. left: left,
  25858. top: top
  25859. });
  25860. },
  25861. ondragstop: function () {
  25862. me.getDom('contmask').style.visibility = 'hidden';
  25863. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  25864. me.dragMask.hide();
  25865. }
  25866. });
  25867. }
  25868. },
  25869. reset: function () {
  25870. this.getDom('content').innerHTML = this.getContentHtml();
  25871. this.fireEvent('dialogafterreset');
  25872. },
  25873. _show: function () {
  25874. if (this._hidden) {
  25875. this.getDom().style.display = '';
  25876. //要高过编辑器的zindxe
  25877. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  25878. this._hidden = false;
  25879. this.fireEvent('show');
  25880. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  25881. }
  25882. },
  25883. isHidden: function () {
  25884. return this._hidden;
  25885. },
  25886. _hide: function () {
  25887. if (!this._hidden) {
  25888. var wrapNode = this.getDom();
  25889. wrapNode.style.display = 'none';
  25890. wrapNode.style.zIndex = '';
  25891. wrapNode.style.width = '';
  25892. wrapNode.style.height = '';
  25893. this._hidden = true;
  25894. this.fireEvent('hide');
  25895. }
  25896. },
  25897. open: function () {
  25898. if (this.autoReset) {
  25899. //有可能还没有渲染
  25900. try {
  25901. this.reset();
  25902. } catch (e) {
  25903. this.render();
  25904. this.open()
  25905. }
  25906. }
  25907. this.showAtCenter();
  25908. if (this.iframeUrl) {
  25909. try {
  25910. this.getDom('iframe').focus();
  25911. } catch (ex) {
  25912. }
  25913. }
  25914. activeDialog = this;
  25915. },
  25916. _onCloseButtonClick: function (evt, el) {
  25917. this.close(false);
  25918. },
  25919. close: function (ok) {
  25920. if (this.fireEvent('close', ok) !== false) {
  25921. //还原环境
  25922. if (this.fullscreen) {
  25923. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  25924. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  25925. document.body.style.overflowX = this._originalContext.body.overflowX;
  25926. document.body.style.overflowY = this._originalContext.body.overflowY;
  25927. delete this._originalContext;
  25928. }
  25929. this._hide();
  25930. //销毁content
  25931. var content = this.getDom('content');
  25932. var iframe = this.getDom('iframe');
  25933. if (content && iframe) {
  25934. var doc = iframe.contentDocument || iframe.contentWindow.document;
  25935. doc && (doc.body.innerHTML = '');
  25936. domUtils.remove(content);
  25937. }
  25938. }
  25939. }
  25940. };
  25941. utils.inherits(Dialog, UIBase);
  25942. })();
  25943. // ui/menubutton.js
  25944. ///import core
  25945. ///import uicore
  25946. ///import ui/menu.js
  25947. ///import ui/splitbutton.js
  25948. (function () {
  25949. var utils = baidu.editor.utils,
  25950. Menu = baidu.editor.ui.Menu,
  25951. SplitButton = baidu.editor.ui.SplitButton,
  25952. MenuButton = baidu.editor.ui.MenuButton = function (options) {
  25953. this.initOptions(options);
  25954. this.initMenuButton();
  25955. };
  25956. MenuButton.prototype = {
  25957. initMenuButton: function () {
  25958. var me = this;
  25959. this.uiName = "menubutton";
  25960. this.popup = new Menu({
  25961. items: me.items,
  25962. className: me.className,
  25963. editor: me.editor
  25964. });
  25965. this.popup.addListener('show', function () {
  25966. var list = this;
  25967. for (var i = 0; i < list.items.length; i++) {
  25968. list.items[i].removeState('checked');
  25969. if (list.items[i].value == me._value) {
  25970. list.items[i].addState('checked');
  25971. this.value = me._value;
  25972. }
  25973. }
  25974. });
  25975. this.initSplitButton();
  25976. },
  25977. setValue: function (value) {
  25978. this._value = value;
  25979. }
  25980. };
  25981. utils.inherits(MenuButton, SplitButton);
  25982. })();
  25983. // ui/multiMenu.js
  25984. ///import core
  25985. ///import uicore
  25986. ///commands 表情
  25987. (function() {
  25988. var utils = baidu.editor.utils,
  25989. Popup = baidu.editor.ui.Popup,
  25990. SplitButton = baidu.editor.ui.SplitButton,
  25991. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options) {
  25992. this.initOptions(options);
  25993. this.initMultiMenu();
  25994. };
  25995. MultiMenuPop.prototype = {
  25996. initMultiMenu: function () {
  25997. var me = this;
  25998. this.popup = new Popup({
  25999. content: '',
  26000. editor: me.editor,
  26001. iframe_rendered: false,
  26002. onshow: function () {
  26003. if (!this.iframe_rendered) {
  26004. this.iframe_rendered = true;
  26005. this.getDom('content').innerHTML = '<iframe id="' + me.id + '_iframe" src="' + me.iframeUrl + '" frameborder="0"></iframe>';
  26006. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  26007. }
  26008. }
  26009. // canSideUp:false,
  26010. // canSideLeft:false
  26011. });
  26012. this.onbuttonclick = function () {
  26013. this.showPopup();
  26014. };
  26015. this.initSplitButton();
  26016. }
  26017. };
  26018. utils.inherits(MultiMenuPop, SplitButton);
  26019. })();
  26020. // ui/shortcutmenu.js
  26021. (function() {
  26022. var UI = baidu.editor.ui,
  26023. UIBase = UI.UIBase,
  26024. uiUtils = UI.uiUtils,
  26025. utils = baidu.editor.utils,
  26026. domUtils = baidu.editor.dom.domUtils;
  26027. var allMenus = [],//存储所有快捷菜单
  26028. timeID,
  26029. isSubMenuShow = false;//是否有子pop显示
  26030. var ShortCutMenu = UI.ShortCutMenu = function(options) {
  26031. this.initOptions(options);
  26032. this.initShortCutMenu();
  26033. };
  26034. ShortCutMenu.postHide = hideAllMenu;
  26035. ShortCutMenu.prototype = {
  26036. isHidden: true,
  26037. SPACE: 5,
  26038. initShortCutMenu: function() {
  26039. this.items = this.items || [];
  26040. this.initUIBase();
  26041. this.initItems();
  26042. this.initEvent();
  26043. allMenus.push(this);
  26044. },
  26045. initEvent: function() {
  26046. var me = this,
  26047. doc = me.editor.document;
  26048. domUtils.on(doc, "mousemove", function (e) {
  26049. if (me.isHidden === false) {
  26050. //有pop显示就不隐藏快捷菜单
  26051. if (me.getSubMenuMark() || me.eventType == "contextmenu") return;
  26052. var flag = true,
  26053. el = me.getDom(),
  26054. wt = el.offsetWidth,
  26055. ht = el.offsetHeight,
  26056. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  26057. distanceY = ht / 2,//距离中心Y标准
  26058. x = Math.abs(e.screenX - me.left),//离中心距离横坐标
  26059. y = Math.abs(e.screenY - me.top);//离中心距离纵坐标
  26060. clearTimeout(timeID);
  26061. timeID = setTimeout(function () {
  26062. if (y > 0 && y < distanceY) {
  26063. me.setOpacity(el, "1");
  26064. } else if (y > distanceY && y < distanceY + 70) {
  26065. me.setOpacity(el, "0.5");
  26066. flag = false;
  26067. } else if (y > distanceY + 70 && y < distanceY + 140) {
  26068. me.hide();
  26069. }
  26070. if (flag && x > 0 && x < distanceX) {
  26071. me.setOpacity(el, "1")
  26072. } else if (x > distanceX && x < distanceX + 70) {
  26073. me.setOpacity(el, "0.5")
  26074. } else if (x > distanceX + 70 && x < distanceX + 140) {
  26075. me.hide();
  26076. }
  26077. });
  26078. }
  26079. });
  26080. //ie\ff下 mouseout不准
  26081. if (browser.chrome) {
  26082. domUtils.on(doc, "mouseout", function (e) {
  26083. var relatedTgt = e.relatedTarget || e.toElement;
  26084. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  26085. me.hide();
  26086. }
  26087. });
  26088. }
  26089. me.editor.addListener("afterhidepop", function () {
  26090. if (!me.isHidden) {
  26091. isSubMenuShow = true;
  26092. }
  26093. });
  26094. },
  26095. initItems: function() {
  26096. if (utils.isArray(this.items)) {
  26097. for (var i = 0, len = this.items.length; i < len; i++) {
  26098. var item = this.items[i].toLowerCase();
  26099. if (UI[item]) {
  26100. this.items[i] = new UI[item](this.editor);
  26101. this.items[i].className += " edui-shortcutsubmenu ";
  26102. }
  26103. }
  26104. }
  26105. },
  26106. setOpacity: function (el, value) {
  26107. if (browser.ie && browser.version < 9) {
  26108. el.style.filter = "alpha(opacity = " + parseFloat(value) * 100 + ");"
  26109. } else {
  26110. el.style.opacity = value;
  26111. }
  26112. },
  26113. getSubMenuMark: function () {
  26114. isSubMenuShow = false;
  26115. var layerEle = uiUtils.getFixedLayer();
  26116. var list = domUtils.getElementsByTagName(layerEle, "div", function (node) {
  26117. return domUtils.hasClass(node, "edui-shortcutsubmenu edui-popup")
  26118. });
  26119. for (var i = 0, node; node = list[i++];) {
  26120. if (node.style.display != "none") {
  26121. isSubMenuShow = true;
  26122. }
  26123. }
  26124. return isSubMenuShow;
  26125. },
  26126. show: function (e, hasContextmenu) {
  26127. var me = this,
  26128. offset = {},
  26129. el = this.getDom(),
  26130. fixedlayer = uiUtils.getFixedLayer();
  26131. function setPos(offset) {
  26132. if (offset.left < 0) {
  26133. offset.left = 0;
  26134. }
  26135. if (offset.top < 0) {
  26136. offset.top = 0;
  26137. }
  26138. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  26139. }
  26140. function setPosByCxtMenu(menu) {
  26141. if (!menu.tagName) {
  26142. menu = menu.getDom();
  26143. }
  26144. offset.left = parseInt(menu.style.left);
  26145. offset.top = parseInt(menu.style.top);
  26146. offset.top -= el.offsetHeight + 15;
  26147. setPos(offset);
  26148. }
  26149. me.eventType = e.type;
  26150. el.style.cssText = "display:block;left:-9999px";
  26151. if (e.type == "contextmenu" && hasContextmenu) {
  26152. var menu = domUtils.getElementsByTagName(fixedlayer, "div", "edui-contextmenu")[0];
  26153. if (menu) {
  26154. setPosByCxtMenu(menu)
  26155. } else {
  26156. me.editor.addListener("aftershowcontextmenu", function (type, menu) {
  26157. setPosByCxtMenu(menu);
  26158. });
  26159. }
  26160. } else {
  26161. offset = uiUtils.getViewportOffsetByEvent(e);
  26162. offset.top -= el.offsetHeight + me.SPACE;
  26163. offset.left += me.SPACE + 20;
  26164. setPos(offset);
  26165. me.setOpacity(el, 0.2);
  26166. }
  26167. me.isHidden = false;
  26168. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  26169. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  26170. if (me.editor) {
  26171. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  26172. fixedlayer.style.zIndex = el.style.zIndex - 1;
  26173. }
  26174. },
  26175. hide: function () {
  26176. if (this.getDom()) {
  26177. this.getDom().style.display = "none";
  26178. }
  26179. this.isHidden = true;
  26180. },
  26181. postRender: function () {
  26182. if (utils.isArray(this.items)) {
  26183. for (var i = 0, item; item = this.items[i++];) {
  26184. item.postRender();
  26185. }
  26186. }
  26187. },
  26188. getHtmlTpl: function () {
  26189. var buff;
  26190. if (utils.isArray(this.items)) {
  26191. buff = [];
  26192. for (var i = 0; i < this.items.length; i++) {
  26193. buff[i] = this.items[i].renderHtml();
  26194. }
  26195. buff = buff.join("");
  26196. } else {
  26197. buff = this.items;
  26198. }
  26199. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  26200. buff +
  26201. '</div>';
  26202. }
  26203. };
  26204. utils.inherits(ShortCutMenu, UIBase);
  26205. function hideAllMenu(e) {
  26206. var tgt = e.target || e.srcElement,
  26207. cur = domUtils.findParent(tgt, function (node) {
  26208. return domUtils.hasClass(node, "edui-shortcutmenu") || domUtils.hasClass(node, "edui-popup");
  26209. }, true);
  26210. if (!cur) {
  26211. for (var i = 0, menu; menu = allMenus[i++];) {
  26212. menu.hide()
  26213. }
  26214. }
  26215. }
  26216. domUtils.on(document, 'mousedown', function(e) {
  26217. hideAllMenu(e);
  26218. });
  26219. domUtils.on(window, 'scroll', function(e) {
  26220. hideAllMenu(e);
  26221. });
  26222. })();
  26223. // ui/breakline.js
  26224. (function () {
  26225. var utils = baidu.editor.utils,
  26226. UIBase = baidu.editor.ui.UIBase,
  26227. Breakline = baidu.editor.ui.Breakline = function (options) {
  26228. this.initOptions(options);
  26229. this.initSeparator();
  26230. };
  26231. Breakline.prototype = {
  26232. uiName: 'Breakline',
  26233. initSeparator: function () {
  26234. this.initUIBase();
  26235. },
  26236. getHtmlTpl: function () {
  26237. return '<br/>';
  26238. }
  26239. };
  26240. utils.inherits(Breakline, UIBase);
  26241. })();
  26242. // ui/message.js
  26243. ///import core
  26244. ///import uicore
  26245. (function() {
  26246. var utils = baidu.editor.utils,
  26247. domUtils = baidu.editor.dom.domUtils,
  26248. UIBase = baidu.editor.ui.UIBase,
  26249. Message = baidu.editor.ui.Message = function(options) {
  26250. this.initOptions(options);
  26251. this.initMessage();
  26252. };
  26253. Message.prototype = {
  26254. initMessage: function() {
  26255. this.initUIBase();
  26256. },
  26257. getHtmlTpl: function() {
  26258. return '<div id="##" class="edui-message %%">' +
  26259. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  26260. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  26261. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  26262. ' <div class="edui-shadow"></div>' +
  26263. ' <div id="##_content" class="edui-message-content">' +
  26264. ' </div>' +
  26265. ' </div>' +
  26266. '</div>';
  26267. },
  26268. reset: function(opt) {
  26269. var me = this;
  26270. if (!opt.keepshow) {
  26271. clearTimeout(this.timer);
  26272. me.timer = setTimeout(function() {
  26273. me.hide();
  26274. }, opt.timeout || 4000);
  26275. }
  26276. opt.content !== undefined && me.setContent(opt.content);
  26277. opt.type !== undefined && me.setType(opt.type);
  26278. me.show();
  26279. },
  26280. postRender: function () {
  26281. var me = this,
  26282. closer = this.getDom('closer');
  26283. closer && domUtils.on(closer, 'click', function () {
  26284. me.hide();
  26285. });
  26286. },
  26287. setContent: function (content) {
  26288. this.getDom('content').innerHTML = content;
  26289. },
  26290. setType: function (type) {
  26291. type = type || 'info';
  26292. var body = this.getDom('body');
  26293. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  26294. },
  26295. getContent: function () {
  26296. return this.getDom('content').innerHTML;
  26297. },
  26298. getType: function () {
  26299. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  26300. return arr ? arr[1] : '';
  26301. },
  26302. show: function () {
  26303. this.getDom().style.display = 'block';
  26304. },
  26305. hide: function () {
  26306. var dom = this.getDom();
  26307. if (dom) {
  26308. dom.style.display = 'none';
  26309. dom.parentNode && dom.parentNode.removeChild(dom);
  26310. }
  26311. }
  26312. };
  26313. utils.inherits(Message, UIBase);
  26314. })();
  26315. // adapter/editorui.js
  26316. //ui跟编辑器的适配層
  26317. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  26318. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  26319. (function() {
  26320. var utils = baidu.editor.utils;
  26321. var editorui = baidu.editor.ui;
  26322. var _Dialog = editorui.Dialog;
  26323. editorui.buttons = {};
  26324. editorui.Dialog = function(options) {
  26325. var dialog = new _Dialog(options);
  26326. dialog.addListener('hide', function() {
  26327. if (dialog.editor) {
  26328. var editor = dialog.editor;
  26329. try {
  26330. if (browser.gecko) {
  26331. var y = editor.window.scrollY,
  26332. x = editor.window.scrollX;
  26333. editor.body.focus();
  26334. editor.window.scrollTo(x, y);
  26335. } else {
  26336. editor.focus();
  26337. }
  26338. } catch (ex) {
  26339. }
  26340. }
  26341. });
  26342. return dialog;
  26343. };
  26344. var iframeUrlMap = {
  26345. 'anchor': '~/dialogs/anchor/anchor.html',
  26346. 'insertimage': '~/dialogs/image/image.html',
  26347. 'link': '~/dialogs/link/link.html',
  26348. 'spechars': '~/dialogs/spechars/spechars.html',
  26349. 'searchreplace': '~/dialogs/searchreplace/searchreplace.html',
  26350. 'map': '~/dialogs/map/map.html',
  26351. 'gmap': '~/dialogs/gmap/gmap.html',
  26352. 'insertvideo': '~/dialogs/video/video.html',
  26353. 'help': '~/dialogs/help/help.html',
  26354. 'preview': '~/dialogs/preview/preview.html',
  26355. 'emotion': '~/dialogs/emotion/emotion.html',
  26356. 'wordimage': '~/dialogs/wordimage/wordimage.html',
  26357. 'attachment': '~/dialogs/attachment/attachment.html',
  26358. 'insertframe': '~/dialogs/insertframe/insertframe.html',
  26359. 'edittip': '~/dialogs/table/edittip.html',
  26360. 'edittable': '~/dialogs/table/edittable.html',
  26361. 'edittd': '~/dialogs/table/edittd.html',
  26362. 'webapp': '~/dialogs/webapp/webapp.html',
  26363. 'snapscreen': '~/dialogs/snapscreen/snapscreen.html',
  26364. 'scrawl': '~/dialogs/scrawl/scrawl.html',
  26365. 'music': '~/dialogs/music/music.html',
  26366. 'template': '~/dialogs/template/template.html',
  26367. 'background': '~/dialogs/background/background.html',
  26368. 'charts': '~/dialogs/charts/charts.html'
  26369. };
  26370. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  26371. var btnCmds = ['undo', 'redo', 'formatmatch',
  26372. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  26373. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  26374. 'blockquote', 'pasteplain', 'pagebreak',
  26375. 'selectall', 'print', 'horizontal', 'removeformat', 'time', 'date', 'unlink',
  26376. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  26377. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  26378. for (var i = 0, ci; ci = btnCmds[i++];) {
  26379. ci = ci.toLowerCase();
  26380. editorui[ci] = function (cmd) {
  26381. return function (editor) {
  26382. var ui = new editorui.Button({
  26383. className: 'edui-for-' + cmd,
  26384. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  26385. onclick: function () {
  26386. editor.execCommand(cmd);
  26387. },
  26388. theme: editor.options.theme,
  26389. showText: false
  26390. });
  26391. editorui.buttons[cmd] = ui;
  26392. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26393. var state = editor.queryCommandState(cmd);
  26394. if (state == -1) {
  26395. ui.setDisabled(true);
  26396. ui.setChecked(false);
  26397. } else {
  26398. if (!uiReady) {
  26399. ui.setDisabled(false);
  26400. ui.setChecked(state);
  26401. }
  26402. }
  26403. });
  26404. return ui;
  26405. };
  26406. }(ci);
  26407. }
  26408. //清除文档
  26409. editorui.cleardoc = function (editor) {
  26410. var ui = new editorui.Button({
  26411. className: 'edui-for-cleardoc',
  26412. title: editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  26413. theme: editor.options.theme,
  26414. onclick: function () {
  26415. if (confirm(editor.getLang("confirmClear"))) {
  26416. editor.execCommand('cleardoc');
  26417. }
  26418. }
  26419. });
  26420. editorui.buttons["cleardoc"] = ui;
  26421. editor.addListener('selectionchange', function () {
  26422. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  26423. });
  26424. return ui;
  26425. };
  26426. //排版,图片排版,文字方向
  26427. var typeset = {
  26428. 'justify': ['left', 'right', 'center', 'justify'],
  26429. 'imagefloat': ['none', 'left', 'center', 'right'],
  26430. 'directionality': ['ltr', 'rtl']
  26431. };
  26432. for (var p in typeset) {
  26433. (function (cmd, val) {
  26434. for (var i = 0, ci; ci = val[i++];) {
  26435. (function (cmd2) {
  26436. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  26437. var ui = new editorui.Button({
  26438. className: 'edui-for-' + cmd.replace('float', '') + cmd2,
  26439. title: editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  26440. theme: editor.options.theme,
  26441. onclick: function () {
  26442. editor.execCommand(cmd, cmd2);
  26443. }
  26444. });
  26445. editorui.buttons[cmd] = ui;
  26446. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26447. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  26448. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  26449. });
  26450. return ui;
  26451. };
  26452. })(ci)
  26453. }
  26454. })(p, typeset[p])
  26455. }
  26456. //字体颜色和背景颜色
  26457. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  26458. editorui[ci] = function (cmd) {
  26459. return function (editor) {
  26460. var ui = new editorui.ColorButton({
  26461. className: 'edui-for-' + cmd,
  26462. color: 'default',
  26463. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  26464. editor: editor,
  26465. onpickcolor: function (t, color) {
  26466. editor.execCommand(cmd, color);
  26467. },
  26468. onpicknocolor: function () {
  26469. editor.execCommand(cmd, 'default');
  26470. this.setColor('transparent');
  26471. this.color = 'default';
  26472. },
  26473. onbuttonclick: function () {
  26474. editor.execCommand(cmd, this.color);
  26475. }
  26476. });
  26477. editorui.buttons[cmd] = ui;
  26478. editor.addListener('selectionchange', function () {
  26479. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  26480. });
  26481. return ui;
  26482. };
  26483. }(ci);
  26484. }
  26485. var dialogBtns = {
  26486. noOk: ['searchreplace', 'help', 'spechars', 'webapp', 'preview'],
  26487. ok: ['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  26488. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  26489. };
  26490. for (var p in dialogBtns) {
  26491. (function (type, vals) {
  26492. for (var i = 0, ci; ci = vals[i++];) {
  26493. //todo opera下存在问题
  26494. if (browser.opera && ci === "searchreplace") {
  26495. continue;
  26496. }
  26497. (function (cmd) {
  26498. editorui[cmd] = function (editor, iframeUrl, title) {
  26499. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  26500. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  26501. var dialog;
  26502. //没有iframeUrl不创建dialog
  26503. if (iframeUrl) {
  26504. dialog = new editorui.Dialog(utils.extend({
  26505. iframeUrl: editor.ui.mapUrl(iframeUrl),
  26506. editor: editor,
  26507. className: 'edui-for-' + cmd,
  26508. title: title,
  26509. holdScroll: cmd === 'insertimage',
  26510. fullscreen: /charts|preview/.test(cmd),
  26511. closeDialog: editor.getLang("closeDialog")
  26512. }, type == 'ok' ? {
  26513. buttons: [
  26514. {
  26515. className: 'edui-okbutton',
  26516. label: editor.getLang("ok"),
  26517. editor: editor,
  26518. onclick: function () {
  26519. dialog.close(true);
  26520. }
  26521. },
  26522. {
  26523. className: 'edui-cancelbutton',
  26524. label: editor.getLang("cancel"),
  26525. editor: editor,
  26526. onclick: function () {
  26527. dialog.close(false);
  26528. }
  26529. }
  26530. ]
  26531. } : {}));
  26532. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  26533. }
  26534. var ui = new editorui.Button({
  26535. className: 'edui-for-' + cmd,
  26536. title: title,
  26537. onclick: function () {
  26538. if (dialog) {
  26539. switch (cmd) {
  26540. case "wordimage":
  26541. var images = editor.execCommand("wordimage");
  26542. if (images && images.length) {
  26543. dialog.render();
  26544. dialog.open();
  26545. }
  26546. break;
  26547. case "scrawl":
  26548. if (editor.queryCommandState("scrawl") != -1) {
  26549. dialog.render();
  26550. dialog.open();
  26551. }
  26552. break;
  26553. default:
  26554. dialog.render();
  26555. dialog.open();
  26556. }
  26557. }
  26558. },
  26559. theme: editor.options.theme,
  26560. disabled: (cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || (cmd == 'charts')
  26561. });
  26562. editorui.buttons[cmd] = ui;
  26563. editor.addListener('selectionchange', function () {
  26564. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  26565. var unNeedCheckState = {'edittable': 1};
  26566. if (cmd in unNeedCheckState) return;
  26567. var state = editor.queryCommandState(cmd);
  26568. if (ui.getDom()) {
  26569. ui.setDisabled(state == -1);
  26570. ui.setChecked(state);
  26571. }
  26572. });
  26573. return ui;
  26574. };
  26575. })(ci.toLowerCase())
  26576. }
  26577. })(p, dialogBtns[p]);
  26578. }
  26579. editorui.snapscreen = function (editor, iframeUrl, title) {
  26580. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  26581. var ui = new editorui.Button({
  26582. className: 'edui-for-snapscreen',
  26583. title: title,
  26584. onclick: function () {
  26585. editor.execCommand("snapscreen");
  26586. },
  26587. theme: editor.options.theme
  26588. });
  26589. editorui.buttons['snapscreen'] = ui;
  26590. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  26591. if (iframeUrl) {
  26592. var dialog = new editorui.Dialog({
  26593. iframeUrl: editor.ui.mapUrl(iframeUrl),
  26594. editor: editor,
  26595. className: 'edui-for-snapscreen',
  26596. title: title,
  26597. buttons: [
  26598. {
  26599. className: 'edui-okbutton',
  26600. label: editor.getLang("ok"),
  26601. editor: editor,
  26602. onclick: function () {
  26603. dialog.close(true);
  26604. }
  26605. },
  26606. {
  26607. className: 'edui-cancelbutton',
  26608. label: editor.getLang("cancel"),
  26609. editor: editor,
  26610. onclick: function () {
  26611. dialog.close(false);
  26612. }
  26613. }
  26614. ]
  26615. });
  26616. dialog.render();
  26617. editor.ui._dialogs["snapscreenDialog"] = dialog;
  26618. }
  26619. editor.addListener('selectionchange', function () {
  26620. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  26621. });
  26622. return ui;
  26623. };
  26624. editorui.insertcode = function (editor, list, title) {
  26625. list = editor.options['insertcode'] || [];
  26626. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  26627. // if (!list.length) return;
  26628. var items = [];
  26629. utils.each(list, function (key, val) {
  26630. items.push({
  26631. label: key,
  26632. value: val,
  26633. theme: editor.options.theme,
  26634. renderLabelHtml: function () {
  26635. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  26636. }
  26637. });
  26638. });
  26639. var ui = new editorui.Combox({
  26640. editor: editor,
  26641. items: items,
  26642. onselect: function(t, index) {
  26643. editor.execCommand('insertcode', this.items[index].value);
  26644. },
  26645. onbuttonclick: function() {
  26646. this.showPopup();
  26647. },
  26648. title: title,
  26649. initValue: title,
  26650. className: 'edui-for-insertcode',
  26651. indexByValue: function(value) {
  26652. if (value) {
  26653. for (var i = 0, ci; ci = this.items[i]; i++) {
  26654. if (ci.value.indexOf(value) != -1)
  26655. return i;
  26656. }
  26657. }
  26658. return -1;
  26659. }
  26660. });
  26661. editorui.buttons['insertcode'] = ui;
  26662. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26663. if (!uiReady) {
  26664. var state = editor.queryCommandState('insertcode');
  26665. if (state == -1) {
  26666. ui.setDisabled(true);
  26667. } else {
  26668. ui.setDisabled(false);
  26669. var value = editor.queryCommandValue('insertcode');
  26670. if (!value) {
  26671. ui.setValue(title);
  26672. return;
  26673. }
  26674. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  26675. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  26676. ui.setValue(value);
  26677. }
  26678. }
  26679. });
  26680. return ui;
  26681. };
  26682. editorui.fontfamily = function(editor, list, title) {
  26683. list = editor.options['fontfamily'] || [];
  26684. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  26685. if (!list.length) return;
  26686. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  26687. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  26688. (function (key, val) {
  26689. items.push({
  26690. label: key,
  26691. value: val,
  26692. theme: editor.options.theme,
  26693. renderLabelHtml: function () {
  26694. return '<div class="edui-label %%-label" style="font-family:' +
  26695. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  26696. }
  26697. });
  26698. })(ci.label || langLabel, ci.val)
  26699. }
  26700. var ui = new editorui.Combox({
  26701. editor: editor,
  26702. items: items,
  26703. onselect: function (t, index) {
  26704. editor.execCommand('FontFamily', this.items[index].value);
  26705. },
  26706. onbuttonclick: function () {
  26707. this.showPopup();
  26708. },
  26709. title: title,
  26710. initValue: title,
  26711. className: 'edui-for-fontfamily',
  26712. indexByValue: function (value) {
  26713. if (value) {
  26714. for (var i = 0, ci; ci = this.items[i]; i++) {
  26715. if (ci.value.indexOf(value) != -1)
  26716. return i;
  26717. }
  26718. }
  26719. return -1;
  26720. }
  26721. });
  26722. editorui.buttons['fontfamily'] = ui;
  26723. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26724. if (!uiReady) {
  26725. var state = editor.queryCommandState('FontFamily');
  26726. if (state == -1) {
  26727. ui.setDisabled(true);
  26728. } else {
  26729. ui.setDisabled(false);
  26730. var value = editor.queryCommandValue('FontFamily');
  26731. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  26732. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  26733. ui.setValue(value);
  26734. }
  26735. }
  26736. });
  26737. return ui;
  26738. };
  26739. editorui.fontsize = function (editor, list, title) {
  26740. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  26741. list = list || editor.options['fontsize'] || [];
  26742. if (!list.length) return;
  26743. var items = [];
  26744. for (var i = 0; i < list.length; i++) {
  26745. var size = list[i] + 'px';
  26746. items.push({
  26747. label: size,
  26748. value: size,
  26749. theme: editor.options.theme,
  26750. renderLabelHtml: function () {
  26751. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  26752. this.value + '">' + (this.label || '') + '</div>';
  26753. }
  26754. });
  26755. }
  26756. var ui = new editorui.Combox({
  26757. editor: editor,
  26758. items: items,
  26759. title: title,
  26760. initValue: title,
  26761. onselect: function (t, index) {
  26762. editor.execCommand('FontSize', this.items[index].value);
  26763. },
  26764. onbuttonclick: function () {
  26765. this.showPopup();
  26766. },
  26767. className: 'edui-for-fontsize'
  26768. });
  26769. editorui.buttons['fontsize'] = ui;
  26770. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26771. if (!uiReady) {
  26772. var state = editor.queryCommandState('FontSize');
  26773. if (state == -1) {
  26774. ui.setDisabled(true);
  26775. } else {
  26776. ui.setDisabled(false);
  26777. ui.setValue(editor.queryCommandValue('FontSize'));
  26778. }
  26779. }
  26780. });
  26781. return ui;
  26782. };
  26783. editorui.paragraph = function (editor, list, title) {
  26784. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  26785. list = editor.options['paragraph'] || [];
  26786. if (utils.isEmptyObject(list)) return;
  26787. var items = [];
  26788. for (var i in list) {
  26789. items.push({
  26790. value: i,
  26791. label: list[i] || editor.getLang("paragraph")[i],
  26792. theme: editor.options.theme,
  26793. renderLabelHtml: function () {
  26794. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  26795. }
  26796. })
  26797. }
  26798. var ui = new editorui.Combox({
  26799. editor: editor,
  26800. items: items,
  26801. title: title,
  26802. initValue: title,
  26803. className: 'edui-for-paragraph',
  26804. onselect: function (t, index) {
  26805. editor.execCommand('Paragraph', this.items[index].value);
  26806. },
  26807. onbuttonclick: function () {
  26808. this.showPopup();
  26809. }
  26810. });
  26811. editorui.buttons['paragraph'] = ui;
  26812. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26813. if (!uiReady) {
  26814. var state = editor.queryCommandState('Paragraph');
  26815. if (state == -1) {
  26816. ui.setDisabled(true);
  26817. } else {
  26818. ui.setDisabled(false);
  26819. var value = editor.queryCommandValue('Paragraph');
  26820. var index = ui.indexByValue(value);
  26821. if (index != -1) {
  26822. ui.setValue(value);
  26823. } else {
  26824. ui.setValue(ui.initValue);
  26825. }
  26826. }
  26827. }
  26828. });
  26829. return ui;
  26830. };
  26831. //自定义标题
  26832. editorui.customstyle = function (editor) {
  26833. var list = editor.options['customstyle'] || [],
  26834. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  26835. if (!list.length) return;
  26836. var langCs = editor.getLang('customstyle');
  26837. for (var i = 0, items = [], t; t = list[i++];) {
  26838. (function (t) {
  26839. var ck = {};
  26840. ck.label = t.label ? t.label : langCs[t.name];
  26841. ck.style = t.style;
  26842. ck.className = t.className;
  26843. ck.tag = t.tag;
  26844. items.push({
  26845. label: ck.label,
  26846. value: ck,
  26847. theme: editor.options.theme,
  26848. renderLabelHtml: function () {
  26849. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  26850. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  26851. + '</div>';
  26852. }
  26853. });
  26854. })(t);
  26855. }
  26856. var ui = new editorui.Combox({
  26857. editor: editor,
  26858. items: items,
  26859. title: title,
  26860. initValue: title,
  26861. className: 'edui-for-customstyle',
  26862. onselect: function (t, index) {
  26863. editor.execCommand('customstyle', this.items[index].value);
  26864. },
  26865. onbuttonclick: function () {
  26866. this.showPopup();
  26867. },
  26868. indexByValue: function (value) {
  26869. for (var i = 0, ti; ti = this.items[i++];) {
  26870. if (ti.label == value) {
  26871. return i - 1
  26872. }
  26873. }
  26874. return -1;
  26875. }
  26876. });
  26877. editorui.buttons['customstyle'] = ui;
  26878. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26879. if (!uiReady) {
  26880. var state = editor.queryCommandState('customstyle');
  26881. if (state == -1) {
  26882. ui.setDisabled(true);
  26883. } else {
  26884. ui.setDisabled(false);
  26885. var value = editor.queryCommandValue('customstyle');
  26886. var index = ui.indexByValue(value);
  26887. if (index != -1) {
  26888. ui.setValue(value);
  26889. } else {
  26890. ui.setValue(ui.initValue);
  26891. }
  26892. }
  26893. }
  26894. });
  26895. return ui;
  26896. };
  26897. editorui.inserttable = function (editor, iframeUrl, title) {
  26898. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  26899. var ui = new editorui.TableButton({
  26900. editor: editor,
  26901. title: title,
  26902. className: 'edui-for-inserttable',
  26903. onpicktable: function (t, numCols, numRows) {
  26904. editor.execCommand('InsertTable', {numRows: numRows, numCols: numCols, border: 1});
  26905. },
  26906. onbuttonclick: function () {
  26907. this.showPopup();
  26908. }
  26909. });
  26910. editorui.buttons['inserttable'] = ui;
  26911. editor.addListener('selectionchange', function () {
  26912. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  26913. });
  26914. return ui;
  26915. };
  26916. editorui.lineheight = function (editor) {
  26917. var val = editor.options.lineheight || [];
  26918. if (!val.length) return;
  26919. for (var i = 0, ci, items = []; ci = val[i++];) {
  26920. items.push({
  26921. //todo:写死了
  26922. label: ci,
  26923. value: ci,
  26924. theme: editor.options.theme,
  26925. onclick: function () {
  26926. editor.execCommand("lineheight", this.value);
  26927. }
  26928. })
  26929. }
  26930. var ui = new editorui.MenuButton({
  26931. editor: editor,
  26932. className: 'edui-for-lineheight',
  26933. title: editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  26934. items: items,
  26935. onbuttonclick: function () {
  26936. var value = editor.queryCommandValue('LineHeight') || this.value;
  26937. editor.execCommand("LineHeight", value);
  26938. }
  26939. });
  26940. editorui.buttons['lineheight'] = ui;
  26941. editor.addListener('selectionchange', function () {
  26942. var state = editor.queryCommandState('LineHeight');
  26943. if (state == -1) {
  26944. ui.setDisabled(true);
  26945. } else {
  26946. ui.setDisabled(false);
  26947. var value = editor.queryCommandValue('LineHeight');
  26948. value && ui.setValue((value + '').replace(/cm/, ''));
  26949. ui.setChecked(state)
  26950. }
  26951. });
  26952. return ui;
  26953. };
  26954. var rowspacings = ['top', 'bottom'];
  26955. for (var r = 0, ri; ri = rowspacings[r++];) {
  26956. (function (cmd) {
  26957. editorui['rowspacing' + cmd] = function (editor) {
  26958. var val = editor.options['rowspacing' + cmd] || [];
  26959. if (!val.length) return null;
  26960. for (var i = 0, ci, items = []; ci = val[i++];) {
  26961. items.push({
  26962. label: ci,
  26963. value: ci,
  26964. theme: editor.options.theme,
  26965. onclick: function () {
  26966. editor.execCommand("rowspacing", this.value, cmd);
  26967. }
  26968. })
  26969. }
  26970. var ui = new editorui.MenuButton({
  26971. editor: editor,
  26972. className: 'edui-for-rowspacing' + cmd,
  26973. title: editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26974. items: items,
  26975. onbuttonclick: function () {
  26976. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26977. editor.execCommand("rowspacing", value, cmd);
  26978. }
  26979. });
  26980. editorui.buttons[cmd] = ui;
  26981. editor.addListener('selectionchange', function () {
  26982. var state = editor.queryCommandState('rowspacing', cmd);
  26983. if (state == -1) {
  26984. ui.setDisabled(true);
  26985. } else {
  26986. ui.setDisabled(false);
  26987. var value = editor.queryCommandValue('rowspacing', cmd);
  26988. value && ui.setValue((value + '').replace(/%/, ''));
  26989. ui.setChecked(state)
  26990. }
  26991. });
  26992. return ui;
  26993. }
  26994. })(ri)
  26995. }
  26996. //有序,无序列表
  26997. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26998. for (var l = 0, cl; cl = lists[l++];) {
  26999. (function (cmd) {
  27000. editorui[cmd] = function (editor) {
  27001. var vals = editor.options[cmd],
  27002. _onMenuClick = function () {
  27003. editor.execCommand(cmd, this.value);
  27004. }, items = [];
  27005. for (var i in vals) {
  27006. items.push({
  27007. label: vals[i] || editor.getLang()[cmd][i] || "",
  27008. value: i,
  27009. theme: editor.options.theme,
  27010. onclick: _onMenuClick
  27011. })
  27012. }
  27013. var ui = new editorui.MenuButton({
  27014. editor: editor,
  27015. className: 'edui-for-' + cmd,
  27016. title: editor.getLang("labelMap." + cmd) || '',
  27017. 'items': items,
  27018. onbuttonclick: function () {
  27019. var value = editor.queryCommandValue(cmd) || this.value;
  27020. editor.execCommand(cmd, value);
  27021. }
  27022. });
  27023. editorui.buttons[cmd] = ui;
  27024. editor.addListener('selectionchange', function () {
  27025. var state = editor.queryCommandState(cmd);
  27026. if (state == -1) {
  27027. ui.setDisabled(true);
  27028. } else {
  27029. ui.setDisabled(false);
  27030. var value = editor.queryCommandValue(cmd);
  27031. ui.setValue(value);
  27032. ui.setChecked(state)
  27033. }
  27034. });
  27035. return ui;
  27036. };
  27037. })(cl)
  27038. }
  27039. editorui.fullscreen = function (editor, title) {
  27040. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  27041. var ui = new editorui.Button({
  27042. className: 'edui-for-fullscreen',
  27043. title: title,
  27044. theme: editor.options.theme,
  27045. onclick: function () {
  27046. if (editor.ui) {
  27047. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  27048. }
  27049. this.setChecked(editor.ui.isFullScreen());
  27050. }
  27051. });
  27052. editorui.buttons['fullscreen'] = ui;
  27053. editor.addListener('selectionchange', function () {
  27054. var state = editor.queryCommandState('fullscreen');
  27055. ui.setDisabled(state == -1);
  27056. ui.setChecked(editor.ui.isFullScreen());
  27057. });
  27058. return ui;
  27059. };
  27060. // 表情
  27061. editorui["emotion"] = function (editor, iframeUrl) {
  27062. var cmd = "emotion";
  27063. var ui = new editorui.MultiMenuPop({
  27064. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  27065. editor: editor,
  27066. className: 'edui-for-' + cmd,
  27067. iframeUrl: editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  27068. });
  27069. editorui.buttons[cmd] = ui;
  27070. editor.addListener('selectionchange', function () {
  27071. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  27072. });
  27073. return ui;
  27074. };
  27075. editorui.autotypeset = function (editor) {
  27076. var ui = new editorui.AutoTypeSetButton({
  27077. editor: editor,
  27078. title: editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  27079. className: 'edui-for-autotypeset',
  27080. onbuttonclick: function () {
  27081. editor.execCommand('autotypeset')
  27082. }
  27083. });
  27084. editorui.buttons['autotypeset'] = ui;
  27085. editor.addListener('selectionchange', function () {
  27086. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  27087. });
  27088. return ui;
  27089. };
  27090. /* 简单上传插件 */
  27091. editorui["simpleupload"] = function (editor) {
  27092. var name = 'simpleupload',
  27093. ui = new editorui.Button({
  27094. className: 'edui-for-' + name,
  27095. title: editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  27096. onclick: function () {
  27097. },
  27098. theme: editor.options.theme,
  27099. showText: false
  27100. });
  27101. editorui.buttons[name] = ui;
  27102. editor.addListener('ready', function () {
  27103. var b = ui.getDom('body'),
  27104. iconSpan = b.children[0];
  27105. editor.fireEvent('simpleuploadbtnready', iconSpan);
  27106. });
  27107. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  27108. var state = editor.queryCommandState(name);
  27109. if (state == -1) {
  27110. ui.setDisabled(true);
  27111. ui.setChecked(false);
  27112. } else {
  27113. if (!uiReady) {
  27114. ui.setDisabled(false);
  27115. ui.setChecked(state);
  27116. }
  27117. }
  27118. });
  27119. return ui;
  27120. };
  27121. })();
  27122. // adapter/editor.js
  27123. ///import core
  27124. ///commands 全屏
  27125. ///commandsName FullScreen
  27126. ///commandsTitle 全屏
  27127. (function() {
  27128. var utils = baidu.editor.utils,
  27129. uiUtils = baidu.editor.ui.uiUtils,
  27130. UIBase = baidu.editor.ui.UIBase,
  27131. domUtils = baidu.editor.dom.domUtils;
  27132. var nodeStack = [];
  27133. function EditorUI(options) {
  27134. this.initOptions(options);
  27135. this.initEditorUI();
  27136. }
  27137. EditorUI.prototype = {
  27138. uiName: 'editor',
  27139. initEditorUI: function() {
  27140. this.editor.ui = this;
  27141. this._dialogs = {};
  27142. this.initUIBase();
  27143. this._initToolbars();
  27144. var editor = this.editor,
  27145. me = this;
  27146. editor.addListener('ready', function () {
  27147. //提供getDialog方法
  27148. editor.getDialog = function (name) {
  27149. return editor.ui._dialogs[name + "Dialog"];
  27150. };
  27151. domUtils.on(editor.window, 'scroll', function (evt) {
  27152. baidu.editor.ui.Popup.postHide(evt);
  27153. });
  27154. //提供编辑器实时宽高(全屏时宽高不变化)
  27155. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  27156. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  27157. //display bottom-bar label based on config
  27158. if (editor.options.elementPathEnabled) {
  27159. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  27160. }
  27161. if (editor.options.wordCount) {
  27162. function countFn() {
  27163. setCount(editor, me);
  27164. domUtils.un(editor.document, "click", arguments.callee);
  27165. }
  27166. domUtils.on(editor.document, "click", countFn);
  27167. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  27168. }
  27169. editor.ui._scale();
  27170. if (editor.options.scaleEnabled) {
  27171. if (editor.autoHeightEnabled) {
  27172. editor.disableAutoHeight();
  27173. }
  27174. me.enableScale();
  27175. } else {
  27176. me.disableScale();
  27177. }
  27178. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  27179. editor.ui.getDom('elementpath').style.display = "none";
  27180. editor.ui.getDom('wordcount').style.display = "none";
  27181. editor.ui.getDom('scale').style.display = "none";
  27182. }
  27183. if (!editor.selection.isFocus()) return;
  27184. editor.fireEvent('selectionchange', false, true);
  27185. });
  27186. editor.addListener('mousedown', function (t, evt) {
  27187. var el = evt.target || evt.srcElement;
  27188. baidu.editor.ui.Popup.postHide(evt, el);
  27189. baidu.editor.ui.ShortCutMenu.postHide(evt);
  27190. });
  27191. editor.addListener("delcells", function () {
  27192. if (UE.ui['edittip']) {
  27193. new UE.ui['edittip'](editor);
  27194. }
  27195. editor.getDialog('edittip').open();
  27196. });
  27197. var pastePop, isPaste = false, timer;
  27198. editor.addListener("afterpaste", function () {
  27199. if (editor.queryCommandState('pasteplain'))
  27200. return;
  27201. if (baidu.editor.ui.PastePicker) {
  27202. pastePop = new baidu.editor.ui.Popup({
  27203. content: new baidu.editor.ui.PastePicker({editor: editor}),
  27204. editor: editor,
  27205. className: 'edui-wordpastepop'
  27206. });
  27207. pastePop.render();
  27208. }
  27209. isPaste = true;
  27210. });
  27211. editor.addListener("afterinserthtml", function () {
  27212. clearTimeout(timer);
  27213. timer = setTimeout(function () {
  27214. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  27215. if (pastePop.isHidden()) {
  27216. var span = domUtils.createElement(editor.document, 'span', {
  27217. 'style': "line-height:0px;",
  27218. 'innerHTML': '\ufeff'
  27219. }),
  27220. range = editor.selection.getRange();
  27221. range.insertNode(span);
  27222. var tmp = getDomNode(span, 'firstChild', 'previousSibling');
  27223. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  27224. domUtils.remove(span);
  27225. } else {
  27226. pastePop.show();
  27227. }
  27228. delete editor.ui._isTransfer;
  27229. isPaste = false;
  27230. }
  27231. }, 200)
  27232. });
  27233. editor.addListener('contextmenu', function (t, evt) {
  27234. baidu.editor.ui.Popup.postHide(evt);
  27235. });
  27236. editor.addListener('keydown', function (t, evt) {
  27237. if (pastePop) pastePop.dispose(evt);
  27238. var keyCode = evt.keyCode || evt.which;
  27239. if (evt.altKey && keyCode == 90) {
  27240. UE.ui.buttons['fullscreen'].onclick();
  27241. }
  27242. });
  27243. editor.addListener('wordcount', function (type) {
  27244. setCount(this, me);
  27245. });
  27246. function setCount(editor, ui) {
  27247. editor.setOpt({
  27248. wordCount: true,
  27249. maximumWords: 10000,
  27250. wordCountMsg: editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  27251. wordOverFlowMsg: editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  27252. });
  27253. var opt = editor.options,
  27254. max = opt.maximumWords,
  27255. msg = opt.wordCountMsg,
  27256. errMsg = opt.wordOverFlowMsg,
  27257. countDom = ui.getDom('wordcount');
  27258. if (!opt.wordCount) {
  27259. return;
  27260. }
  27261. var count = editor.getContentLength(true);
  27262. if (count > max) {
  27263. countDom.innerHTML = errMsg;
  27264. editor.fireEvent("wordcountoverflow");
  27265. } else {
  27266. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  27267. }
  27268. }
  27269. editor.addListener('selectionchange', function () {
  27270. if (editor.options.elementPathEnabled) {
  27271. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  27272. }
  27273. if (editor.options.scaleEnabled) {
  27274. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  27275. }
  27276. });
  27277. var popup = new baidu.editor.ui.Popup({
  27278. editor: editor,
  27279. content: '',
  27280. className: 'edui-bubble',
  27281. _onEditButtonClick: function() {
  27282. this.hide();
  27283. editor.ui._dialogs.linkDialog.open();
  27284. },
  27285. _onImgEditButtonClick: function(name) {
  27286. this.hide();
  27287. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  27288. },
  27289. _onImgSetFloat: function (value) {
  27290. this.hide();
  27291. editor.execCommand("imagefloat", value);
  27292. },
  27293. _setIframeAlign: function (value) {
  27294. var frame = popup.anchorEl;
  27295. var newFrame = frame.cloneNode(true);
  27296. switch (value) {
  27297. case -2:
  27298. newFrame.setAttribute("align", "");
  27299. break;
  27300. case -1:
  27301. newFrame.setAttribute("align", "left");
  27302. break;
  27303. case 1:
  27304. newFrame.setAttribute("align", "right");
  27305. break;
  27306. }
  27307. frame.parentNode.insertBefore(newFrame, frame);
  27308. domUtils.remove(frame);
  27309. popup.anchorEl = newFrame;
  27310. popup.showAnchor(popup.anchorEl);
  27311. },
  27312. _updateIframe: function () {
  27313. var frame = editor._iframe = popup.anchorEl;
  27314. if (domUtils.hasClass(frame, 'ueditor_baidumap')) {
  27315. editor.selection.getRange().selectNode(frame).select();
  27316. editor.ui._dialogs.mapDialog.open();
  27317. popup.hide();
  27318. } else {
  27319. editor.ui._dialogs.insertframeDialog.open();
  27320. popup.hide();
  27321. }
  27322. },
  27323. _onRemoveButtonClick: function (cmdName) {
  27324. editor.execCommand(cmdName);
  27325. this.hide();
  27326. },
  27327. queryAutoHide: function (el) {
  27328. if (el && el.ownerDocument == editor.document) {
  27329. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  27330. return el !== popup.anchorEl;
  27331. }
  27332. }
  27333. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  27334. }
  27335. });
  27336. popup.render();
  27337. if (editor.options.imagePopup) {
  27338. editor.addListener('mouseover', function (t, evt) {
  27339. evt = evt || window.event;
  27340. var el = evt.target || evt.srcElement;
  27341. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  27342. var html = popup.formatHtml(
  27343. '<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;' +
  27344. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  27345. if (html) {
  27346. popup.getDom('content').innerHTML = html;
  27347. popup.anchorEl = el;
  27348. popup.showAnchor(popup.anchorEl);
  27349. } else {
  27350. popup.hide();
  27351. }
  27352. }
  27353. });
  27354. editor.addListener('selectionchange', function (t, causeByUi) {
  27355. if (!causeByUi) return;
  27356. var html = '', str = "",
  27357. img = editor.selection.getRange().getClosedNode(),
  27358. dialogs = editor.ui._dialogs;
  27359. if (img && img.tagName == 'IMG') {
  27360. var dialogName = 'insertimageDialog';
  27361. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  27362. dialogName = "insertvideoDialog"
  27363. }
  27364. if (img.className.indexOf("edui-faked-webapp") != -1) {
  27365. dialogName = "webappDialog"
  27366. }
  27367. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  27368. dialogName = "mapDialog"
  27369. }
  27370. if (img.className.indexOf("edui-faked-music") != -1) {
  27371. dialogName = "musicDialog"
  27372. }
  27373. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  27374. dialogName = "gmapDialog"
  27375. }
  27376. if (img.getAttribute("anchorname")) {
  27377. dialogName = "anchorDialog";
  27378. html = popup.formatHtml(
  27379. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  27380. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  27381. }
  27382. if (img.getAttribute("word_img")) {
  27383. //todo 放到dialog去做查询
  27384. editor.word_img = [img.getAttribute("word_img")];
  27385. dialogName = "wordimageDialog"
  27386. }
  27387. if (domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  27388. dialogName = "";
  27389. }
  27390. if (!dialogs[dialogName]) {
  27391. return;
  27392. }
  27393. str = '<nobr>' + editor.getLang("property") + ': ' +
  27394. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  27395. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  27396. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  27397. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;' +
  27398. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  27399. !html && (html = popup.formatHtml(str))
  27400. }
  27401. if (editor.ui._dialogs.linkDialog) {
  27402. var link = editor.queryCommandValue('link');
  27403. var url;
  27404. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  27405. var txt = url;
  27406. if (url.length > 30) {
  27407. txt = url.substring(0, 20) + "...";
  27408. }
  27409. if (html) {
  27410. html += '<div style="height:5px;"></div>'
  27411. }
  27412. html += popup.formatHtml(
  27413. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  27414. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  27415. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  27416. popup.showAnchor(link);
  27417. }
  27418. }
  27419. if (html) {
  27420. popup.getDom('content').innerHTML = html;
  27421. popup.anchorEl = img || link;
  27422. popup.showAnchor(popup.anchorEl);
  27423. } else {
  27424. popup.hide();
  27425. }
  27426. });
  27427. }
  27428. },
  27429. _initToolbars: function () {
  27430. var editor = this.editor;
  27431. var toolbars = this.toolbars || [];
  27432. var toolbarUis = [];
  27433. for (var i = 0; i < toolbars.length; i++) {
  27434. var toolbar = toolbars[i];
  27435. var toolbarUi = new baidu.editor.ui.Toolbar({ theme: editor.options.theme });
  27436. for (var j = 0; j < toolbar.length; j++) {
  27437. var toolbarItem = toolbar[j];
  27438. var toolbarItemUi = null;
  27439. if (typeof toolbarItem == 'string') {
  27440. toolbarItem = toolbarItem.toLowerCase();
  27441. if (toolbarItem == '|') {
  27442. toolbarItem = 'Separator';
  27443. }
  27444. if (toolbarItem == '||') {
  27445. toolbarItem = 'Breakline';
  27446. }
  27447. if (baidu.editor.ui[toolbarItem]) {
  27448. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  27449. }
  27450. //fullscreen这里单独处理一下,放到首行去
  27451. if (toolbarItem == 'fullscreen') {
  27452. if (toolbarUis && toolbarUis[0]) {
  27453. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  27454. } else {
  27455. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  27456. }
  27457. continue;
  27458. }
  27459. } else {
  27460. toolbarItemUi = toolbarItem;
  27461. }
  27462. if (toolbarItemUi && toolbarItemUi.id) {
  27463. toolbarUi.add(toolbarItemUi);
  27464. }
  27465. }
  27466. toolbarUis[i] = toolbarUi;
  27467. }
  27468. //接受外部定制的UI(修复因 utils.each 无法准确的循环出对象的全部元素而导致的自定义 UI 不符合预期的 BUG by HaoChuan9421)
  27469. // utils.each(UE._customizeUI,function(obj,key){
  27470. // var itemUI,index;
  27471. // if(obj.id && obj.id != editor.key){
  27472. // return false;
  27473. // }
  27474. // itemUI = obj.execFn.call(editor,editor,key);
  27475. // if(itemUI){
  27476. // index = obj.index;
  27477. // if(index === undefined){
  27478. // index = toolbarUi.items.length;
  27479. // }
  27480. // toolbarUi.add(itemUI,index)
  27481. // }
  27482. // });
  27483. for (var key in UE._customizeUI) {
  27484. var obj = UE._customizeUI[key];
  27485. var itemUI, index;
  27486. if (!obj.id || obj.id == editor.key) {
  27487. itemUI = obj.execFn.call(editor, editor, key);
  27488. if (itemUI) {
  27489. index = obj.index;
  27490. if (index === undefined) {
  27491. index = toolbarUi.items.length;
  27492. }
  27493. toolbarUi.add(itemUI, index);
  27494. }
  27495. }
  27496. }
  27497. this.toolbars = toolbarUis;
  27498. },
  27499. getHtmlTpl: function () {
  27500. return '<div id="##" class="%%">' +
  27501. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  27502. (this.toolbars.length ?
  27503. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  27504. this.renderToolbarBoxHtml() +
  27505. '</div></div>' : '') +
  27506. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  27507. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  27508. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  27509. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  27510. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  27511. '</div>' +
  27512. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  27513. '</div>' +
  27514. '<div id="##_iframeholder" class="%%-iframeholder">' +
  27515. '</div>' +
  27516. //modify wdcount by matao
  27517. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  27518. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  27519. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  27520. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  27521. '</tr></table></div>' +
  27522. '<div id="##_scalelayer"></div>' +
  27523. '</div>';
  27524. },
  27525. showWordImageDialog: function () {
  27526. this._dialogs['wordimageDialog'].open();
  27527. },
  27528. renderToolbarBoxHtml: function () {
  27529. var buff = [];
  27530. for (var i = 0; i < this.toolbars.length; i++) {
  27531. buff.push(this.toolbars[i].renderHtml());
  27532. }
  27533. return buff.join('');
  27534. },
  27535. setFullScreen: function (fullscreen) {
  27536. var editor = this.editor,
  27537. container = editor.container.parentNode.parentNode;
  27538. if (this._fullscreen != fullscreen) {
  27539. this._fullscreen = fullscreen;
  27540. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  27541. if (baidu.editor.browser.gecko) {
  27542. var bk = editor.selection.getRange().createBookmark();
  27543. }
  27544. if (fullscreen) {
  27545. while (container.tagName != "BODY") {
  27546. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  27547. nodeStack.push(position);
  27548. container.style.position = "static";
  27549. container = container.parentNode;
  27550. }
  27551. this._bakHtmlOverflow = document.documentElement.style.overflow;
  27552. this._bakBodyOverflow = document.body.style.overflow;
  27553. this._bakAutoHeight = this.editor.autoHeightEnabled;
  27554. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  27555. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  27556. if (this._bakAutoHeight) {
  27557. //当全屏时不能执行自动长高
  27558. editor.autoHeightEnabled = false;
  27559. this.editor.disableAutoHeight();
  27560. }
  27561. document.documentElement.style.overflow = 'hidden';
  27562. //修复,滚动条不收起的问题
  27563. window.scrollTo(0, window.scrollY);
  27564. this._bakCssText = this.getDom().style.cssText;
  27565. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  27566. editor.iframe.parentNode.style.width = '';
  27567. this._updateFullScreen();
  27568. } else {
  27569. while (container.tagName != "BODY") {
  27570. container.style.position = nodeStack.shift();
  27571. container = container.parentNode;
  27572. }
  27573. this.getDom().style.cssText = this._bakCssText;
  27574. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  27575. if (this._bakAutoHeight) {
  27576. editor.autoHeightEnabled = true;
  27577. this.editor.enableAutoHeight();
  27578. }
  27579. document.documentElement.style.overflow = this._bakHtmlOverflow;
  27580. document.body.style.overflow = this._bakBodyOverflow;
  27581. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  27582. window.scrollTo(0, this._bakScrollTop);
  27583. }
  27584. if (browser.gecko && editor.body.contentEditable === 'true') {
  27585. var input = document.createElement('input');
  27586. document.body.appendChild(input);
  27587. editor.body.contentEditable = false;
  27588. setTimeout(function () {
  27589. input.focus();
  27590. setTimeout(function () {
  27591. editor.body.contentEditable = true;
  27592. editor.fireEvent('fullscreenchanged', fullscreen);
  27593. editor.selection.getRange().moveToBookmark(bk).select(true);
  27594. baidu.editor.dom.domUtils.remove(input);
  27595. fullscreen && window.scroll(0, 0);
  27596. }, 0)
  27597. }, 0)
  27598. }
  27599. if (editor.body.contentEditable === 'true') {
  27600. this.editor.fireEvent('fullscreenchanged', fullscreen);
  27601. this.triggerLayout();
  27602. }
  27603. }
  27604. },
  27605. _updateFullScreen: function() {
  27606. if (this._fullscreen) {
  27607. var vpRect = uiUtils.getViewportRect();
  27608. 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);
  27609. uiUtils.setViewportOffset(this.getDom(), { left: 0, top: this.editor.options.topOffset || 0 });
  27610. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0), true);
  27611. //不手动调一下,会导致全屏失效
  27612. if (browser.gecko) {
  27613. try {
  27614. window.onresize();
  27615. } catch (e) {
  27616. }
  27617. }
  27618. }
  27619. },
  27620. _updateElementPath: function() {
  27621. var bottom = this.getDom('elementpath'), list;
  27622. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  27623. var buff = [];
  27624. for (var i = 0, ci; ci = list[i]; i++) {
  27625. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  27626. }
  27627. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  27628. } else {
  27629. bottom.style.display = 'none'
  27630. }
  27631. },
  27632. disableElementPath: function () {
  27633. var bottom = this.getDom('elementpath');
  27634. bottom.innerHTML = '';
  27635. bottom.style.display = 'none';
  27636. this.elementPathEnabled = false;
  27637. },
  27638. enableElementPath: function () {
  27639. var bottom = this.getDom('elementpath');
  27640. bottom.style.display = '';
  27641. this.elementPathEnabled = true;
  27642. this._updateElementPath();
  27643. },
  27644. _scale: function () {
  27645. var doc = document,
  27646. editor = this.editor,
  27647. editorHolder = editor.container,
  27648. editorDocument = editor.document,
  27649. toolbarBox = this.getDom("toolbarbox"),
  27650. bottombar = this.getDom("bottombar"),
  27651. scale = this.getDom("scale"),
  27652. scalelayer = this.getDom("scalelayer");
  27653. var isMouseMove = false,
  27654. position = null,
  27655. minEditorHeight = 0,
  27656. minEditorWidth = editor.options.minFrameWidth,
  27657. pageX = 0,
  27658. pageY = 0,
  27659. scaleWidth = 0,
  27660. scaleHeight = 0;
  27661. function down() {
  27662. position = domUtils.getXY(editorHolder);
  27663. if (!minEditorHeight) {
  27664. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  27665. }
  27666. 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:"
  27667. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  27668. domUtils.on(doc, "mousemove", move);
  27669. domUtils.on(editorDocument, "mouseup", up);
  27670. domUtils.on(doc, "mouseup", up);
  27671. }
  27672. var me = this;
  27673. //by xuheng 全屏时关掉缩放
  27674. this.editor.addListener('fullscreenchanged', function(e, fullScreen) {
  27675. if (fullScreen) {
  27676. me.disableScale();
  27677. } else {
  27678. if (me.editor.options.scaleEnabled) {
  27679. me.enableScale();
  27680. var tmpNode = me.editor.document.createElement('span');
  27681. me.editor.body.appendChild(tmpNode);
  27682. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  27683. domUtils.remove(tmpNode)
  27684. }
  27685. }
  27686. });
  27687. function move(event) {
  27688. clearSelection();
  27689. var e = event || window.event;
  27690. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  27691. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  27692. scaleWidth = pageX - position.x;
  27693. scaleHeight = pageY - position.y;
  27694. if (scaleWidth >= minEditorWidth) {
  27695. isMouseMove = true;
  27696. scalelayer.style.width = scaleWidth + 'px';
  27697. }
  27698. if (scaleHeight >= minEditorHeight) {
  27699. isMouseMove = true;
  27700. scalelayer.style.height = scaleHeight + "px";
  27701. }
  27702. }
  27703. function up() {
  27704. if (isMouseMove) {
  27705. isMouseMove = false;
  27706. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  27707. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  27708. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2, true);
  27709. }
  27710. if (scalelayer) {
  27711. scalelayer.style.display = "none";
  27712. }
  27713. clearSelection();
  27714. domUtils.un(doc, "mousemove", move);
  27715. domUtils.un(editorDocument, "mouseup", up);
  27716. domUtils.un(doc, "mouseup", up);
  27717. }
  27718. function clearSelection() {
  27719. if (browser.ie)
  27720. doc.selection.clear();
  27721. else
  27722. window.getSelection().removeAllRanges();
  27723. }
  27724. this.enableScale = function () {
  27725. //trace:2868
  27726. if (editor.queryCommandState("source") == 1) return;
  27727. scale.style.display = "";
  27728. this.scaleEnabled = true;
  27729. domUtils.on(scale, "mousedown", down);
  27730. };
  27731. this.disableScale = function () {
  27732. scale.style.display = "none";
  27733. this.scaleEnabled = false;
  27734. domUtils.un(scale, "mousedown", down);
  27735. };
  27736. },
  27737. isFullScreen: function () {
  27738. return this._fullscreen;
  27739. },
  27740. postRender: function () {
  27741. UIBase.prototype.postRender.call(this);
  27742. for (var i = 0; i < this.toolbars.length; i++) {
  27743. this.toolbars[i].postRender();
  27744. }
  27745. var me = this;
  27746. var timerId,
  27747. domUtils = baidu.editor.dom.domUtils,
  27748. updateFullScreenTime = function () {
  27749. clearTimeout(timerId);
  27750. timerId = setTimeout(function () {
  27751. me._updateFullScreen();
  27752. });
  27753. };
  27754. domUtils.on(window, 'resize', updateFullScreenTime);
  27755. me.addListener('destroy', function () {
  27756. domUtils.un(window, 'resize', updateFullScreenTime);
  27757. clearTimeout(timerId);
  27758. })
  27759. },
  27760. showToolbarMsg: function (msg, flag) {
  27761. this.getDom('toolbarmsg_label').innerHTML = msg;
  27762. this.getDom('toolbarmsg').style.display = '';
  27763. //
  27764. if (!flag) {
  27765. var w = this.getDom('upload_dialog');
  27766. w.style.display = 'none';
  27767. }
  27768. },
  27769. hideToolbarMsg: function () {
  27770. this.getDom('toolbarmsg').style.display = 'none';
  27771. },
  27772. mapUrl: function (url) {
  27773. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  27774. },
  27775. triggerLayout: function () {
  27776. var dom = this.getDom();
  27777. if (dom.style.zoom == '1') {
  27778. dom.style.zoom = '100%';
  27779. } else {
  27780. dom.style.zoom = '1';
  27781. }
  27782. }
  27783. };
  27784. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  27785. var instances = {};
  27786. UE.ui.Editor = function (options) {
  27787. var editor = new UE.Editor(options);
  27788. editor.options.editor = editor;
  27789. utils.loadFile(document, {
  27790. href: editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  27791. tag: "link",
  27792. type: "text/css",
  27793. rel: "stylesheet"
  27794. });
  27795. var oldRender = editor.render;
  27796. editor.render = function (holder) {
  27797. if (holder.constructor === String) {
  27798. editor.key = holder;
  27799. instances[holder] = editor;
  27800. }
  27801. utils.domReady(function () {
  27802. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  27803. function renderUI() {
  27804. editor.setOpt({
  27805. labelMap: editor.options.labelMap || editor.getLang('labelMap')
  27806. });
  27807. new EditorUI(editor.options);
  27808. if (holder) {
  27809. if (holder.constructor === String) {
  27810. holder = document.getElementById(holder);
  27811. }
  27812. holder && holder.getAttribute('name') && (editor.options.textarea = holder.getAttribute('name'));
  27813. if (holder && /script|textarea/ig.test(holder.tagName)) {
  27814. var newDiv = document.createElement('div');
  27815. holder.parentNode.insertBefore(newDiv, holder);
  27816. var cont = holder.value || holder.innerHTML;
  27817. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  27818. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  27819. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  27820. .replace(/>[\n\r\t]+</g, '><');
  27821. holder.className && (newDiv.className = holder.className);
  27822. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  27823. if (/textarea/i.test(holder.tagName)) {
  27824. editor.textarea = holder;
  27825. editor.textarea.style.display = 'none';
  27826. } else {
  27827. holder.parentNode.removeChild(holder);
  27828. }
  27829. if (holder.id) {
  27830. newDiv.id = holder.id;
  27831. domUtils.removeAttributes(holder, 'id');
  27832. }
  27833. holder = newDiv;
  27834. holder.innerHTML = '';
  27835. }
  27836. }
  27837. domUtils.addClass(holder, "edui-" + editor.options.theme);
  27838. editor.ui.render(holder);
  27839. var opt = editor.options;
  27840. //给实例添加一个编辑器的容器引用
  27841. editor.container = editor.ui.getDom();
  27842. var parents = domUtils.findParents(holder, true);
  27843. var displays = [];
  27844. for (var i = 0, ci; ci = parents[i]; i++) {
  27845. displays[i] = ci.style.display;
  27846. ci.style.display = 'block'
  27847. }
  27848. if (opt.initialFrameWidth) {
  27849. opt.minFrameWidth = opt.initialFrameWidth;
  27850. } else {
  27851. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  27852. var styleWidth = holder.style.width;
  27853. if (/%$/.test(styleWidth)) {
  27854. opt.initialFrameWidth = styleWidth;
  27855. }
  27856. }
  27857. if (opt.initialFrameHeight) {
  27858. opt.minFrameHeight = opt.initialFrameHeight;
  27859. } else {
  27860. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  27861. }
  27862. for (var i = 0, ci; ci = parents[i]; i++) {
  27863. ci.style.display = displays[i]
  27864. }
  27865. //编辑器最外容器设置了高度,会导致,编辑器不占位
  27866. //todo 先去掉,没有找到原因
  27867. if (holder.style.height) {
  27868. holder.style.height = ''
  27869. }
  27870. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  27871. editor.container.style.zIndex = opt.zIndex;
  27872. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  27873. editor.fireEvent("afteruiready");
  27874. }
  27875. })
  27876. };
  27877. return editor;
  27878. };
  27879. /**
  27880. * @file
  27881. * @name UE
  27882. * @short UE
  27883. * @desc UEditor的顶部命名空间
  27884. */
  27885. /**
  27886. * @name getEditor
  27887. * @since 1.2.4+
  27888. * @grammar UE.getEditor(id,[opt]) => Editor实例
  27889. * @desc 提供一个全局的方法得到编辑器实例
  27890. *
  27891. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  27892. * * ''opt'' 编辑器的可选参数
  27893. * @example
  27894. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  27895. * this.setContent('hello')
  27896. * }});
  27897. * UE.getEditor('containerId'); //返回刚创建的实例
  27898. *
  27899. */
  27900. UE.getEditor = function(id, opt) {
  27901. var editor = instances[id];
  27902. if (!editor) {
  27903. editor = instances[id] = new UE.ui.Editor(opt);
  27904. editor.render(id);
  27905. }
  27906. return editor;
  27907. };
  27908. UE.delEditor = function (id) {
  27909. var editor;
  27910. if (editor = instances[id]) {
  27911. editor.key && editor.destroy();
  27912. delete instances[id]
  27913. }
  27914. };
  27915. UE.registerUI = function (uiName, fn, index, editorId) {
  27916. utils.each(uiName.split(/\s+/), function (name) {
  27917. UE._customizeUI[name] = {
  27918. id: editorId,
  27919. execFn: fn,
  27920. index: index
  27921. };
  27922. })
  27923. }
  27924. })();
  27925. // adapter/message.js
  27926. UE.registerUI('message', function(editor) {
  27927. var editorui = baidu.editor.ui;
  27928. var Message = editorui.Message;
  27929. var holder;
  27930. var _messageItems = [];
  27931. var me = editor;
  27932. me.addListener('ready', function () {
  27933. holder = document.getElementById(me.ui.id + '_message_holder');
  27934. updateHolderPos();
  27935. setTimeout(function () {
  27936. updateHolderPos();
  27937. }, 500);
  27938. });
  27939. me.addListener('showmessage', function (type, opt) {
  27940. opt = utils.isString(opt) ? {
  27941. 'content': opt
  27942. } : opt;
  27943. var message = new Message({
  27944. 'timeout': opt.timeout,
  27945. 'type': opt.type,
  27946. 'content': opt.content,
  27947. 'keepshow': opt.keepshow,
  27948. 'editor': me
  27949. }),
  27950. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27951. message.render(holder);
  27952. _messageItems[mid] = message;
  27953. message.reset(opt);
  27954. updateHolderPos();
  27955. return mid;
  27956. });
  27957. me.addListener('updatemessage', function (type, id, opt) {
  27958. opt = utils.isString(opt) ? {
  27959. 'content': opt
  27960. } : opt;
  27961. var message = _messageItems[id];
  27962. message.render(holder);
  27963. message && message.reset(opt);
  27964. });
  27965. me.addListener('hidemessage', function(type, id) {
  27966. var message = _messageItems[id];
  27967. message && message.hide();
  27968. });
  27969. function updateHolderPos() {
  27970. var toolbarbox = me.ui.getDom('toolbarbox');
  27971. if (toolbarbox) {
  27972. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27973. }
  27974. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27975. }
  27976. });
  27977. // adapter/autosave.js
  27978. UE.registerUI('autosave', function(editor) {
  27979. var timer = null, uid = null;
  27980. editor.on('afterautosave', function() {
  27981. clearTimeout(timer);
  27982. timer = setTimeout(function () {
  27983. if (uid) {
  27984. editor.trigger('hidemessage', uid);
  27985. }
  27986. uid = editor.trigger('showmessage', {
  27987. content: editor.getLang('autosave.success'),
  27988. timeout: 2000
  27989. });
  27990. }, 2000)
  27991. })
  27992. });
  27993. })();