ueditor.all.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Thu May 29 2014 16:47:49 GMT+0800 (中国标准时间)
  5. */
  6. (function(){
  7. // editor.js
  8. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  9. var baidu = window.baidu || {};
  10. window.baidu = baidu;
  11. window.UE = baidu.editor = window.UE || {};
  12. UE.plugins = {};
  13. UE.commands = {};
  14. UE.instants = {};
  15. UE.I18N = {};
  16. UE._customizeUI = {};
  17. UE.version = "1.4.3";
  18. String.prototype.replaceAll = function(s1,s2){
  19. return this.replace(new RegExp(s1,"gm"),s2);
  20. };
  21. var dom = UE.dom = {};
  22. // core/browser.js
  23. /**
  24. * 浏览器判断模块
  25. * @file
  26. * @module UE.browser
  27. * @since 1.2.6.1
  28. */
  29. /**
  30. * 提供浏览器检测的模块
  31. * @unfile
  32. * @module UE.browser
  33. */
  34. var browser = UE.browser = function(){
  35. var agent = navigator.userAgent.toLowerCase(),
  36. opera = window.opera,
  37. browser = {
  38. /**
  39. * @property {boolean} ie 检测当前浏览器是否为IE
  40. * @example
  41. * ```javascript
  42. * if ( UE.browser.ie ) {
  43. * console.log( '当前浏览器是IE' );
  44. * }
  45. * ```
  46. */
  47. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  48. /**
  49. * @property {boolean} opera 检测当前浏览器是否为Opera
  50. * @example
  51. * ```javascript
  52. * if ( UE.browser.opera ) {
  53. * console.log( '当前浏览器是Opera' );
  54. * }
  55. * ```
  56. */
  57. opera : ( !!opera && opera.version ),
  58. /**
  59. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  60. * @example
  61. * ```javascript
  62. * if ( UE.browser.webkit ) {
  63. * console.log( '当前浏览器是webkit内核浏览器' );
  64. * }
  65. * ```
  66. */
  67. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  68. /**
  69. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  70. * @example
  71. * ```javascript
  72. * if ( UE.browser.mac ) {
  73. * console.log( '当前浏览器运行在mac平台下' );
  74. * }
  75. * ```
  76. */
  77. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  78. /**
  79. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  80. * @example
  81. * ```javascript
  82. * if ( UE.browser.quirks ) {
  83. * console.log( '当前浏览器运行处于“怪异模式”' );
  84. * }
  85. * ```
  86. */
  87. quirks : ( document.compatMode == 'BackCompat' )
  88. };
  89. /**
  90. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  91. * @example
  92. * ```javascript
  93. * if ( UE.browser.gecko ) {
  94. * console.log( '当前浏览器内核是gecko内核' );
  95. * }
  96. * ```
  97. */
  98. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  99. var version = 0;
  100. // Internet Explorer 6.0+
  101. if ( browser.ie ){
  102. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  103. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  104. if(v1 && v2 && v1[1] && v2[1]){
  105. version = Math.max(v1[1]*1,v2[1]*1);
  106. }else if(v1 && v1[1]){
  107. version = v1[1]*1;
  108. }else if(v2 && v2[1]){
  109. version = v2[1]*1;
  110. }else{
  111. version = 0;
  112. }
  113. browser.ie11Compat = document.documentMode == 11;
  114. /**
  115. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  116. * @warning 如果浏览器不是IE, 则该值为undefined
  117. * @example
  118. * ```javascript
  119. * if ( UE.browser.ie9Compat ) {
  120. * console.log( '当前浏览器运行在IE9兼容模式下' );
  121. * }
  122. * ```
  123. */
  124. browser.ie9Compat = document.documentMode == 9;
  125. /**
  126. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  127. * @warning 如果浏览器不是IE, 则该值为undefined
  128. * @example
  129. * ```javascript
  130. * if ( UE.browser.ie8 ) {
  131. * console.log( '当前浏览器是IE8浏览器' );
  132. * }
  133. * ```
  134. */
  135. browser.ie8 = !!document.documentMode;
  136. /**
  137. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  138. * @warning 如果浏览器不是IE, 则该值为undefined
  139. * @example
  140. * ```javascript
  141. * if ( UE.browser.ie8Compat ) {
  142. * console.log( '当前浏览器运行在IE8兼容模式下' );
  143. * }
  144. * ```
  145. */
  146. browser.ie8Compat = document.documentMode == 8;
  147. /**
  148. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  149. * @warning 如果浏览器不是IE, 则该值为undefined
  150. * @example
  151. * ```javascript
  152. * if ( UE.browser.ie7Compat ) {
  153. * console.log( '当前浏览器运行在IE7兼容模式下' );
  154. * }
  155. * ```
  156. */
  157. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  158. || document.documentMode == 7 );
  159. /**
  160. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  161. * @warning 如果浏览器不是IE, 则该值为undefined
  162. * @example
  163. * ```javascript
  164. * if ( UE.browser.ie6Compat ) {
  165. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  166. * }
  167. * ```
  168. */
  169. browser.ie6Compat = ( version < 7 || browser.quirks );
  170. browser.ie9above = version > 8;
  171. browser.ie9below = version < 9;
  172. browser.ie11above = version > 10;
  173. browser.ie11below = version < 11;
  174. }
  175. // Gecko.
  176. if ( browser.gecko ){
  177. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  178. if ( geckoRelease )
  179. {
  180. geckoRelease = geckoRelease[1].split( '.' );
  181. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  182. }
  183. }
  184. /**
  185. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  186. * @warning 如果浏览器不是chrome, 则该值为undefined
  187. * @example
  188. * ```javascript
  189. * if ( UE.browser.chrome ) {
  190. * console.log( '当前浏览器是Chrome' );
  191. * }
  192. * ```
  193. */
  194. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  195. browser.chrome = + RegExp['\x241'];
  196. }
  197. /**
  198. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  199. * @warning 如果浏览器不是safari, 则该值为undefined
  200. * @example
  201. * ```javascript
  202. * if ( UE.browser.safari ) {
  203. * console.log( '当前浏览器是Safari' );
  204. * }
  205. * ```
  206. */
  207. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  208. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  209. }
  210. // Opera 9.50+
  211. if ( browser.opera )
  212. version = parseFloat( opera.version() );
  213. // WebKit 522+ (Safari 3+)
  214. if ( browser.webkit )
  215. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  216. /**
  217. * @property { Number } version 检测当前浏览器版本号
  218. * @remind
  219. * <ul>
  220. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  221. * <li>gecko系列会返回10900,158900等</li>
  222. * <li>webkit系列会返回其build号 (如 522等)</li>
  223. * </ul>
  224. * @example
  225. * ```javascript
  226. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  227. * ```
  228. */
  229. browser.version = version;
  230. /**
  231. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  232. * @example
  233. * ```javascript
  234. * if ( UE.browser.isCompatible ) {
  235. * console.log( '浏览器与UEditor能够良好兼容' );
  236. * }
  237. * ```
  238. */
  239. browser.isCompatible =
  240. !browser.mobile && (
  241. ( browser.ie && version >= 6 ) ||
  242. ( browser.gecko && version >= 10801 ) ||
  243. ( browser.opera && version >= 9.5 ) ||
  244. ( browser.air && version >= 1 ) ||
  245. ( browser.webkit && version >= 522 ) ||
  246. false );
  247. return browser;
  248. }();
  249. //快捷方式
  250. var ie = browser.ie,
  251. webkit = browser.webkit,
  252. gecko = browser.gecko,
  253. opera = browser.opera;
  254. // core/utils.js
  255. /**
  256. * 工具函数包
  257. * @file
  258. * @module UE.utils
  259. * @since 1.2.6.1
  260. */
  261. /**
  262. * UEditor封装使用的静态工具函数
  263. * @module UE.utils
  264. * @unfile
  265. */
  266. var utils = UE.utils = {
  267. /**
  268. * 用给定的迭代器遍历对象
  269. * @method each
  270. * @param { Object } obj 需要遍历的对象
  271. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  272. * @example
  273. * ```javascript
  274. * var demoObj = {
  275. * key1: 1,
  276. * key2: 2
  277. * };
  278. *
  279. * //output: key1: 1, key2: 2
  280. * UE.utils.each( demoObj, funciton ( value, key ) {
  281. *
  282. * console.log( key + ":" + value );
  283. *
  284. * } );
  285. * ```
  286. */
  287. /**
  288. * 用给定的迭代器遍历数组或类数组对象
  289. * @method each
  290. * @param { Array } array 需要遍历的数组或者类数组
  291. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  292. * @example
  293. * ```javascript
  294. * var divs = document.getElmentByTagNames( "div" );
  295. *
  296. * //output: 0: DIV, 1: DIV ...
  297. * UE.utils.each( divs, funciton ( value, key ) {
  298. *
  299. * console.log( key + ":" + value.tagName );
  300. *
  301. * } );
  302. * ```
  303. */
  304. each : function(obj, iterator, context) {
  305. if (obj == null) return;
  306. if (obj.length === +obj.length) {
  307. for (var i = 0, l = obj.length; i < l; i++) {
  308. if(iterator.call(context, obj[i], i, obj) === false)
  309. return false;
  310. }
  311. } else {
  312. for (var key in obj) {
  313. if (obj.hasOwnProperty(key)) {
  314. if(iterator.call(context, obj[key], key, obj) === false)
  315. return false;
  316. }
  317. }
  318. }
  319. },
  320. /**
  321. * 以给定对象作为原型创建一个新对象
  322. * @method makeInstance
  323. * @param { Object } protoObject 该对象将作为新创建对象的原型
  324. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  325. * @example
  326. * ```javascript
  327. *
  328. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  329. *
  330. * var newObject = UE.utils.makeInstance( protoObject );
  331. * //output: Hello UEditor!
  332. * newObject.sayHello();
  333. * ```
  334. */
  335. makeInstance:function (obj) {
  336. var noop = new Function();
  337. noop.prototype = obj;
  338. obj = new noop;
  339. noop.prototype = null;
  340. return obj;
  341. },
  342. /**
  343. * 将source对象中的属性扩展到target对象上
  344. * @method extend
  345. * @remind 该方法将强制把source对象上的属性复制到target对象上
  346. * @see UE.utils.extend(Object,Object,Boolean)
  347. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  348. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  349. * @return { Object } 返回target对象
  350. * @example
  351. * ```javascript
  352. *
  353. * var target = { name: 'target', sex: 1 },
  354. * source = { name: 'source', age: 17 };
  355. *
  356. * UE.utils.extend( target, source );
  357. *
  358. * //output: { name: 'source', sex: 1, age: 17 }
  359. * console.log( target );
  360. *
  361. * ```
  362. */
  363. /**
  364. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  365. * 源对象属性名相同的属性值。
  366. * @method extend
  367. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  368. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  369. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  370. * @return { Object } 返回target对象
  371. * @example
  372. * ```javascript
  373. *
  374. * var target = { name: 'target', sex: 1 },
  375. * source = { name: 'source', age: 17 };
  376. *
  377. * UE.utils.extend( target, source, true );
  378. *
  379. * //output: { name: 'target', sex: 1, age: 17 }
  380. * console.log( target );
  381. *
  382. * ```
  383. */
  384. extend:function (t, s, b) {
  385. if (s) {
  386. for (var k in s) {
  387. if (!b || !t.hasOwnProperty(k)) {
  388. t[k] = s[k];
  389. }
  390. }
  391. }
  392. return t;
  393. },
  394. /**
  395. * 将给定的多个对象的属性复制到目标对象target上
  396. * @method extend2
  397. * @remind 该方法将强制把源对象上的属性复制到target对象上
  398. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  399. * 将会覆盖掉之前的值。
  400. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  401. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  402. * @return { Object } 返回target对象
  403. * @example
  404. * ```javascript
  405. *
  406. * var target = {},
  407. * source1 = { name: 'source', age: 17 },
  408. * source2 = { title: 'dev' };
  409. *
  410. * UE.utils.extend2( target, source1, source2 );
  411. *
  412. * //output: { name: 'source', age: 17, title: 'dev' }
  413. * console.log( target );
  414. *
  415. * ```
  416. */
  417. extend2:function (t) {
  418. var a = arguments;
  419. for (var i = 1; i < a.length; i++) {
  420. var x = a[i];
  421. for (var k in x) {
  422. if (!t.hasOwnProperty(k)) {
  423. t[k] = x[k];
  424. }
  425. }
  426. }
  427. return t;
  428. },
  429. /**
  430. * 模拟继承机制, 使得subClass继承自superClass
  431. * @method inherits
  432. * @param { Object } subClass 子类对象
  433. * @param { Object } superClass 超类对象
  434. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  435. * @return { Object } 继承superClass后的子类对象
  436. * @example
  437. * ```javascript
  438. * function SuperClass(){
  439. * this.name = "小李";
  440. * }
  441. *
  442. * SuperClass.prototype = {
  443. * hello:function(str){
  444. * console.log(this.name + str);
  445. * }
  446. * }
  447. *
  448. * function SubClass(){
  449. * this.name = "小张";
  450. * }
  451. *
  452. * UE.utils.inherits(SubClass,SuperClass);
  453. *
  454. * var sub = new SubClass();
  455. * //output: '小张早上好!
  456. * sub.hello("早上好!");
  457. * ```
  458. */
  459. inherits:function (subClass, superClass) {
  460. var oldP = subClass.prototype,
  461. newP = utils.makeInstance(superClass.prototype);
  462. utils.extend(newP, oldP, true);
  463. subClass.prototype = newP;
  464. return (newP.constructor = subClass);
  465. },
  466. /**
  467. * 用指定的context对象作为函数fn的上下文
  468. * @method bind
  469. * @param { Function } fn 需要绑定上下文的函数对象
  470. * @param { Object } content 函数fn新的上下文对象
  471. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  472. * @example
  473. * ```javascript
  474. *
  475. * var name = 'window',
  476. * newTest = null;
  477. *
  478. * function test () {
  479. * console.log( this.name );
  480. * }
  481. *
  482. * newTest = UE.utils.bind( test, { name: 'object' } );
  483. *
  484. * //output: object
  485. * newTest();
  486. *
  487. * //output: window
  488. * test();
  489. *
  490. * ```
  491. */
  492. bind:function (fn, context) {
  493. return function () {
  494. return fn.apply(context, arguments);
  495. };
  496. },
  497. /**
  498. * 创建延迟指定时间后执行的函数fn
  499. * @method defer
  500. * @param { Function } fn 需要延迟执行的函数对象
  501. * @param { int } delay 延迟的时间, 单位是毫秒
  502. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  503. * 而不能保证刚好到达延迟时间时执行。
  504. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  505. * @example
  506. * ```javascript
  507. * var start = 0;
  508. *
  509. * function test(){
  510. * console.log( new Date() - start );
  511. * }
  512. *
  513. * var testDefer = UE.utils.defer( test, 1000 );
  514. * //
  515. * start = new Date();
  516. * //output: (大约在1000毫秒之后输出) 1000
  517. * testDefer();
  518. * ```
  519. */
  520. /**
  521. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  522. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  523. * @method defer
  524. * @param { Function } fn 需要延迟执行的函数对象
  525. * @param { int } delay 延迟的时间, 单位是毫秒
  526. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  527. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  528. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  529. * 而不能保证刚好到达延迟时间时执行。
  530. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  531. * @example
  532. * ```javascript
  533. *
  534. * function test(){
  535. * console.log(1);
  536. * }
  537. *
  538. * var testDefer = UE.utils.defer( test, 1000, true );
  539. *
  540. * //output: (两次调用仅有一次输出) 1
  541. * testDefer();
  542. * testDefer();
  543. * ```
  544. */
  545. defer:function (fn, delay, exclusion) {
  546. var timerID;
  547. return function () {
  548. if (exclusion) {
  549. clearTimeout(timerID);
  550. }
  551. timerID = setTimeout(fn, delay);
  552. };
  553. },
  554. /**
  555. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  556. * @method indexOf
  557. * @remind 该方法的匹配过程使用的是恒等“===”
  558. * @param { Array } array 需要查找的数组对象
  559. * @param { * } item 需要在目标数组中查找的值
  560. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  561. * @example
  562. * ```javascript
  563. * var item = 1,
  564. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  565. *
  566. * //output: 4
  567. * console.log( UE.utils.indexOf( arr, item ) );
  568. * ```
  569. */
  570. /**
  571. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  572. * @method indexOf
  573. * @remind 该方法的匹配过程使用的是恒等“===”
  574. * @param { Array } array 需要查找的数组对象
  575. * @param { * } item 需要在目标数组中查找的值
  576. * @param { int } start 搜索的起始位置
  577. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  578. * @example
  579. * ```javascript
  580. * var item = 1,
  581. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  582. *
  583. * //output: 9
  584. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  585. * ```
  586. */
  587. indexOf:function (array, item, start) {
  588. var index = -1;
  589. start = this.isNumber(start) ? start : 0;
  590. this.each(array, function (v, i) {
  591. if (i >= start && v === item) {
  592. index = i;
  593. return false;
  594. }
  595. });
  596. return index;
  597. },
  598. /**
  599. * 移除数组array中所有的元素item
  600. * @method removeItem
  601. * @param { Array } array 要移除元素的目标数组
  602. * @param { * } item 将要被移除的元素
  603. * @remind 该方法的匹配过程使用的是恒等“===”
  604. * @example
  605. * ```javascript
  606. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  607. *
  608. * UE.utils.removeItem( arr, 4 );
  609. * //output: [ 5, 7, 1, 3, 6 ]
  610. * console.log( arr );
  611. *
  612. * ```
  613. */
  614. removeItem:function (array, item) {
  615. for (var i = 0, l = array.length; i < l; i++) {
  616. if (array[i] === item) {
  617. array.splice(i, 1);
  618. i--;
  619. }
  620. }
  621. },
  622. /**
  623. * 删除字符串str的首尾空格
  624. * @method trim
  625. * @param { String } str 需要删除首尾空格的字符串
  626. * @return { String } 删除了首尾的空格后的字符串
  627. * @example
  628. * ```javascript
  629. *
  630. * var str = " UEdtior ";
  631. *
  632. * //output: 9
  633. * console.log( str.length );
  634. *
  635. * //output: 7
  636. * console.log( UE.utils.trim( " UEdtior " ).length );
  637. *
  638. * //output: 9
  639. * console.log( str.length );
  640. *
  641. * ```
  642. */
  643. trim:function (str) {
  644. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  645. },
  646. /**
  647. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  648. * @method listToMap
  649. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  650. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  651. * @return { Object } 转化之后的hash对象
  652. * @example
  653. * ```javascript
  654. *
  655. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  656. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  657. *
  658. * ```
  659. */
  660. /**
  661. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  662. * @method listToMap
  663. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  664. * @param { Array } arr 字符串数组
  665. * @return { Object } 转化之后的hash对象
  666. * @example
  667. * ```javascript
  668. *
  669. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  670. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  671. *
  672. * ```
  673. */
  674. listToMap:function (list) {
  675. if (!list)return {};
  676. list = utils.isArray(list) ? list : list.split(',');
  677. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  678. obj[ci.toUpperCase()] = obj[ci] = 1;
  679. }
  680. return obj;
  681. },
  682. /**
  683. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  684. * @method unhtml
  685. * @param { String } str 需要转义的字符串
  686. * @return { String } 转义后的字符串
  687. * @example
  688. * ```javascript
  689. * var html = '<body>&</body>';
  690. *
  691. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  692. * console.log( UE.utils.unhtml( html ) );
  693. *
  694. * ```
  695. */
  696. unhtml:function (str, reg) {
  697. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  698. if (b) {
  699. return a;
  700. } else {
  701. return {
  702. '<':'&lt;',
  703. '&':'&amp;',
  704. '"':'&quot;',
  705. '>':'&gt;',
  706. "'":'&#39;'
  707. }[a]
  708. }
  709. }) : '';
  710. },
  711. /**
  712. * 将str中的转义字符还原成html字符
  713. * @see UE.utils.unhtml(String);
  714. * @method html
  715. * @param { String } str 需要逆转义的字符串
  716. * @return { String } 逆转义后的字符串
  717. * @example
  718. * ```javascript
  719. *
  720. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  721. *
  722. * //output: <body>&</body>
  723. * console.log( UE.utils.html( str ) );
  724. *
  725. * ```
  726. */
  727. html:function (str) {
  728. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  729. return {
  730. '&lt;':'<',
  731. '&amp;':'&',
  732. '&quot;':'"',
  733. '&gt;':'>',
  734. '&#39;':"'",
  735. '&nbsp;':' '
  736. }[m]
  737. }) : '';
  738. },
  739. /**
  740. * 将css样式转换为驼峰的形式
  741. * @method cssStyleToDomStyle
  742. * @param { String } cssName 需要转换的css样式名
  743. * @return { String } 转换成驼峰形式后的css样式名
  744. * @example
  745. * ```javascript
  746. *
  747. * var str = 'border-top';
  748. *
  749. * //output: borderTop
  750. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  751. *
  752. * ```
  753. */
  754. cssStyleToDomStyle:function () {
  755. var test = document.createElement('div').style,
  756. cache = {
  757. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  758. };
  759. return function (cssName) {
  760. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  761. return match.charAt(1).toUpperCase();
  762. }));
  763. };
  764. }(),
  765. /**
  766. * 动态加载文件到doc中
  767. * @method loadFile
  768. * @param { DomDocument } document 需要加载资源文件的文档对象
  769. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  770. * @example
  771. * ```javascript
  772. *
  773. * UE.utils.loadFile( document, {
  774. * src:"test.js",
  775. * tag:"script",
  776. * type:"text/javascript",
  777. * defer:"defer"
  778. * } );
  779. *
  780. * ```
  781. */
  782. /**
  783. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  784. * @method loadFile
  785. * @param { DomDocument } document 需要加载资源文件的文档对象
  786. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  787. * @param { Function } fn 资源文件加载成功之后执行的回调
  788. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  789. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  790. * @example
  791. * ```javascript
  792. *
  793. * UE.utils.loadFile( document, {
  794. * src:"test.js",
  795. * tag:"script",
  796. * type:"text/javascript",
  797. * defer:"defer"
  798. * }, function () {
  799. * console.log('加载成功');
  800. * } );
  801. *
  802. * ```
  803. */
  804. loadFile:function () {
  805. var tmpList = [];
  806. function getItem(doc, obj) {
  807. try {
  808. for (var i = 0, ci; ci = tmpList[i++];) {
  809. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  810. return ci;
  811. }
  812. }
  813. } catch (e) {
  814. return null;
  815. }
  816. }
  817. return function (doc, obj, fn) {
  818. var item = getItem(doc, obj);
  819. if (item) {
  820. if (item.ready) {
  821. fn && fn();
  822. } else {
  823. item.funs.push(fn)
  824. }
  825. return;
  826. }
  827. tmpList.push({
  828. doc:doc,
  829. url:obj.src || obj.href,
  830. funs:[fn]
  831. });
  832. if (!doc.body) {
  833. var html = [];
  834. for (var p in obj) {
  835. if (p == 'tag')continue;
  836. html.push(p + '="' + obj[p] + '"')
  837. }
  838. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  839. return;
  840. }
  841. if (obj.id && doc.getElementById(obj.id)) {
  842. return;
  843. }
  844. var element = doc.createElement(obj.tag);
  845. delete obj.tag;
  846. for (var p in obj) {
  847. element.setAttribute(p, obj[p]);
  848. }
  849. element.onload = element.onreadystatechange = function () {
  850. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  851. item = getItem(doc, obj);
  852. if (item.funs.length > 0) {
  853. item.ready = 1;
  854. for (var fi; fi = item.funs.pop();) {
  855. fi();
  856. }
  857. }
  858. element.onload = element.onreadystatechange = null;
  859. }
  860. };
  861. element.onerror = function () {
  862. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  863. };
  864. doc.getElementsByTagName("head")[0].appendChild(element);
  865. }
  866. }(),
  867. /**
  868. * 判断obj对象是否为空
  869. * @method isEmptyObject
  870. * @param { * } obj 需要判断的对象
  871. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  872. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  873. * @return { Boolean } 对象是否为空
  874. * @example
  875. * ```javascript
  876. *
  877. * //output: true
  878. * console.log( UE.utils.isEmptyObject( {} ) );
  879. *
  880. * //output: true
  881. * console.log( UE.utils.isEmptyObject( [] ) );
  882. *
  883. * //output: true
  884. * console.log( UE.utils.isEmptyObject( "" ) );
  885. *
  886. * //output: false
  887. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  888. *
  889. * //output: false
  890. * console.log( UE.utils.isEmptyObject( [1] ) );
  891. *
  892. * //output: false
  893. * console.log( UE.utils.isEmptyObject( "1" ) );
  894. *
  895. * ```
  896. */
  897. isEmptyObject:function (obj) {
  898. if (obj == null) return true;
  899. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  900. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  901. return true;
  902. },
  903. /**
  904. * 把rgb格式的颜色值转换成16进制格式
  905. * @method fixColor
  906. * @param { String } rgb格式的颜色值
  907. * @param { String }
  908. * @example
  909. * rgb(255,255,255) => "#ffffff"
  910. */
  911. fixColor:function (name, value) {
  912. if (/color/i.test(name) && /rgba?/.test(value)) {
  913. var array = value.split(",");
  914. if (array.length > 3)
  915. return "";
  916. value = "#";
  917. for (var i = 0, color; color = array[i++];) {
  918. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  919. value += color.length == 1 ? "0" + color : color;
  920. }
  921. value = value.toUpperCase();
  922. }
  923. return value;
  924. },
  925. /**
  926. * 只针对border,padding,margin做了处理,因为性能问题
  927. * @public
  928. * @function
  929. * @param {String} val style字符串
  930. */
  931. optCss:function (val) {
  932. var padding, margin, border;
  933. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  934. if (val.split(' ').length == 1) {
  935. switch (key) {
  936. case 'padding':
  937. !padding && (padding = {});
  938. padding[name] = val;
  939. return '';
  940. case 'margin':
  941. !margin && (margin = {});
  942. margin[name] = val;
  943. return '';
  944. case 'border':
  945. return val == 'initial' ? '' : str;
  946. }
  947. }
  948. return str;
  949. });
  950. function opt(obj, name) {
  951. if (!obj) {
  952. return '';
  953. }
  954. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  955. if (!t || !l || !b || !r) {
  956. for (var p in obj) {
  957. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  958. }
  959. } else {
  960. val += ';' + name + ':' +
  961. (t == b && b == l && l == r ? t :
  962. t == b && l == r ? (t + ' ' + l) :
  963. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  964. }
  965. return val;
  966. }
  967. val += opt(padding, 'padding') + opt(margin, 'margin');
  968. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  969. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  970. return b ? b + ";;" : ';'
  971. });
  972. },
  973. /**
  974. * 克隆对象
  975. * @method clone
  976. * @param { Object } source 源对象
  977. * @return { Object } source的一个副本
  978. */
  979. /**
  980. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  981. * @method clone
  982. * @param { Object } source 源对象
  983. * @param { Object } target 目标对象
  984. * @return { Object } 附加了source对象所有属性的target对象
  985. */
  986. clone:function (source, target) {
  987. var tmp;
  988. target = target || {};
  989. for (var i in source) {
  990. if (source.hasOwnProperty(i)) {
  991. tmp = source[i];
  992. if (typeof tmp == 'object') {
  993. target[i] = utils.isArray(tmp) ? [] : {};
  994. utils.clone(source[i], target[i])
  995. } else {
  996. target[i] = tmp;
  997. }
  998. }
  999. }
  1000. return target;
  1001. },
  1002. /**
  1003. * 把cm/pt为单位的值转换为px为单位的值
  1004. * @method transUnitToPx
  1005. * @param { String } 待转换的带单位的字符串
  1006. * @return { String } 转换为px为计量单位的值的字符串
  1007. * @example
  1008. * ```javascript
  1009. *
  1010. * //output: 500px
  1011. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1012. *
  1013. * //output: 27px
  1014. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1015. *
  1016. * ```
  1017. */
  1018. transUnitToPx:function (val) {
  1019. if (!/(pt|cm)/.test(val)) {
  1020. return val
  1021. }
  1022. var unit;
  1023. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1024. val = v;
  1025. unit = u;
  1026. });
  1027. switch (unit) {
  1028. case 'cm':
  1029. val = parseFloat(val) * 25;
  1030. break;
  1031. case 'pt':
  1032. val = Math.round(parseFloat(val) * 96 / 72);
  1033. }
  1034. return val + (val ? 'px' : '');
  1035. },
  1036. /**
  1037. * 在dom树ready之后执行给定的回调函数
  1038. * @method domReady
  1039. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1040. * @param { Function } fn dom树ready之后的回调函数
  1041. * @example
  1042. * ```javascript
  1043. *
  1044. * UE.utils.domReady( function () {
  1045. *
  1046. * console.log('123');
  1047. *
  1048. * } );
  1049. *
  1050. * ```
  1051. */
  1052. domReady:function () {
  1053. var fnArr = [];
  1054. function doReady(doc) {
  1055. //确保onready只执行一次
  1056. doc.isReady = true;
  1057. for (var ci; ci = fnArr.pop(); ci()) {
  1058. }
  1059. }
  1060. return function (onready, win) {
  1061. win = win || window;
  1062. var doc = win.document;
  1063. onready && fnArr.push(onready);
  1064. if (doc.readyState === "complete") {
  1065. doReady(doc);
  1066. } else {
  1067. doc.isReady && doReady(doc);
  1068. if (browser.ie && browser.version != 11) {
  1069. (function () {
  1070. if (doc.isReady) return;
  1071. try {
  1072. doc.documentElement.doScroll("left");
  1073. } catch (error) {
  1074. setTimeout(arguments.callee, 0);
  1075. return;
  1076. }
  1077. doReady(doc);
  1078. })();
  1079. win.attachEvent('onload', function () {
  1080. doReady(doc)
  1081. });
  1082. } else {
  1083. doc.addEventListener("DOMContentLoaded", function () {
  1084. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1085. doReady(doc);
  1086. }, false);
  1087. win.addEventListener('load', function () {
  1088. doReady(doc)
  1089. }, false);
  1090. }
  1091. }
  1092. }
  1093. }(),
  1094. /**
  1095. * 动态添加css样式
  1096. * @method cssRule
  1097. * @param { String } 节点名称
  1098. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1099. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1100. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1101. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1102. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1103. */
  1104. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1105. var indexList, index;
  1106. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1107. //获取样式
  1108. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1109. indexList = doc.indexList || (doc.indexList = {});
  1110. index = indexList[key];
  1111. if(index !== undefined){
  1112. return doc.styleSheets[index].cssText
  1113. }
  1114. return undefined;
  1115. }
  1116. doc = doc || document;
  1117. indexList = doc.indexList || (doc.indexList = {});
  1118. index = indexList[key];
  1119. //清除样式
  1120. if(style === ''){
  1121. if(index!== undefined){
  1122. doc.styleSheets[index].cssText = '';
  1123. delete indexList[key];
  1124. return true
  1125. }
  1126. return false;
  1127. }
  1128. //添加样式
  1129. if(index!== undefined){
  1130. sheetStyle = doc.styleSheets[index];
  1131. }else{
  1132. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1133. indexList[key] = index;
  1134. }
  1135. sheetStyle.cssText = style;
  1136. }: function (key, style, doc) {
  1137. var head, node;
  1138. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1139. //获取样式
  1140. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1141. node = doc.getElementById(key);
  1142. return node ? node.innerHTML : undefined;
  1143. }
  1144. doc = doc || document;
  1145. node = doc.getElementById(key);
  1146. //清除样式
  1147. if(style === ''){
  1148. if(node){
  1149. node.parentNode.removeChild(node);
  1150. return true
  1151. }
  1152. return false;
  1153. }
  1154. //添加样式
  1155. if(node){
  1156. node.innerHTML = style;
  1157. }else{
  1158. node = doc.createElement('style');
  1159. node.id = key;
  1160. node.innerHTML = style;
  1161. doc.getElementsByTagName('head')[0].appendChild(node);
  1162. }
  1163. },
  1164. sort:function(array,compareFn){
  1165. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1166. for(var i= 0,len = array.length; i<len; i++){
  1167. for(var j = i,length = array.length; j<length; j++){
  1168. if(compareFn(array[i], array[j]) > 0){
  1169. var t = array[i];
  1170. array[i] = array[j];
  1171. array[j] = t;
  1172. }
  1173. }
  1174. }
  1175. return array;
  1176. },
  1177. serializeParam:function (json) {
  1178. var strArr = [];
  1179. for (var i in json) {
  1180. //忽略默认的几个参数
  1181. if(i=="method" || i=="timeout" || i=="async") continue;
  1182. //传递过来的对象和函数不在提交之列
  1183. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1184. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1185. } else if (utils.isArray(json[i])) {
  1186. //支持传数组内容
  1187. for(var j = 0; j < json[i].length; j++) {
  1188. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1189. }
  1190. }
  1191. }
  1192. return strArr.join("&");
  1193. },
  1194. formatUrl:function (url) {
  1195. var u = url.replace(/&&/g, '&');
  1196. u = u.replace(/\?&/g, '?');
  1197. u = u.replace(/&$/g, '');
  1198. u = u.replace(/&#/g, '#');
  1199. u = u.replace(/&+/g, '&');
  1200. return u;
  1201. },
  1202. isCrossDomainUrl:function (url) {
  1203. var a = document.createElement('a');
  1204. a.href = url;
  1205. if (browser.ie) {
  1206. a.href = a.href;
  1207. }
  1208. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1209. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1210. },
  1211. clearEmptyAttrs : function(obj){
  1212. for(var p in obj){
  1213. if(obj[p] === ''){
  1214. delete obj[p]
  1215. }
  1216. }
  1217. return obj;
  1218. },
  1219. str2json : function(s){
  1220. if (!utils.isString(s)) return null;
  1221. if (window.JSON) {
  1222. return JSON.parse(s);
  1223. } else {
  1224. return (new Function("return " + utils.trim(s || '')))();
  1225. }
  1226. },
  1227. json2str : (function(){
  1228. if (window.JSON) {
  1229. return JSON.stringify;
  1230. } else {
  1231. var escapeMap = {
  1232. "\b": '\\b',
  1233. "\t": '\\t',
  1234. "\n": '\\n',
  1235. "\f": '\\f',
  1236. "\r": '\\r',
  1237. '"' : '\\"',
  1238. "\\": '\\\\'
  1239. };
  1240. function encodeString(source) {
  1241. if (/["\\\x00-\x1f]/.test(source)) {
  1242. source = source.replace(
  1243. /["\\\x00-\x1f]/g,
  1244. function (match) {
  1245. var c = escapeMap[match];
  1246. if (c) {
  1247. return c;
  1248. }
  1249. c = match.charCodeAt();
  1250. return "\\u00"
  1251. + Math.floor(c / 16).toString(16)
  1252. + (c % 16).toString(16);
  1253. });
  1254. }
  1255. return '"' + source + '"';
  1256. }
  1257. function encodeArray(source) {
  1258. var result = ["["],
  1259. l = source.length,
  1260. preComma, i, item;
  1261. for (i = 0; i < l; i++) {
  1262. item = source[i];
  1263. switch (typeof item) {
  1264. case "undefined":
  1265. case "function":
  1266. case "unknown":
  1267. break;
  1268. default:
  1269. if(preComma) {
  1270. result.push(',');
  1271. }
  1272. result.push(utils.json2str(item));
  1273. preComma = 1;
  1274. }
  1275. }
  1276. result.push("]");
  1277. return result.join("");
  1278. }
  1279. function pad(source) {
  1280. return source < 10 ? '0' + source : source;
  1281. }
  1282. function encodeDate(source){
  1283. return '"' + source.getFullYear() + "-"
  1284. + pad(source.getMonth() + 1) + "-"
  1285. + pad(source.getDate()) + "T"
  1286. + pad(source.getHours()) + ":"
  1287. + pad(source.getMinutes()) + ":"
  1288. + pad(source.getSeconds()) + '"';
  1289. }
  1290. return function (value) {
  1291. switch (typeof value) {
  1292. case 'undefined':
  1293. return 'undefined';
  1294. case 'number':
  1295. return isFinite(value) ? String(value) : "null";
  1296. case 'string':
  1297. return encodeString(value);
  1298. case 'boolean':
  1299. return String(value);
  1300. default:
  1301. if (value === null) {
  1302. return 'null';
  1303. } else if (utils.isArray(value)) {
  1304. return encodeArray(value);
  1305. } else if (utils.isDate(value)) {
  1306. return encodeDate(value);
  1307. } else {
  1308. var result = ['{'],
  1309. encode = utils.json2str,
  1310. preComma,
  1311. item;
  1312. for (var key in value) {
  1313. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1314. item = value[key];
  1315. switch (typeof item) {
  1316. case 'undefined':
  1317. case 'unknown':
  1318. case 'function':
  1319. break;
  1320. default:
  1321. if (preComma) {
  1322. result.push(',');
  1323. }
  1324. preComma = 1;
  1325. result.push(encode(key) + ':' + encode(item));
  1326. }
  1327. }
  1328. }
  1329. result.push('}');
  1330. return result.join('');
  1331. }
  1332. }
  1333. };
  1334. }
  1335. })()
  1336. };
  1337. /**
  1338. * 判断给定的对象是否是字符串
  1339. * @method isString
  1340. * @param { * } object 需要判断的对象
  1341. * @return { Boolean } 给定的对象是否是字符串
  1342. */
  1343. /**
  1344. * 判断给定的对象是否是数组
  1345. * @method isArray
  1346. * @param { * } object 需要判断的对象
  1347. * @return { Boolean } 给定的对象是否是数组
  1348. */
  1349. /**
  1350. * 判断给定的对象是否是一个Function
  1351. * @method isFunction
  1352. * @param { * } object 需要判断的对象
  1353. * @return { Boolean } 给定的对象是否是Function
  1354. */
  1355. /**
  1356. * 判断给定的对象是否是Number
  1357. * @method isNumber
  1358. * @param { * } object 需要判断的对象
  1359. * @return { Boolean } 给定的对象是否是Number
  1360. */
  1361. /**
  1362. * 判断给定的对象是否是一个正则表达式
  1363. * @method isRegExp
  1364. * @param { * } object 需要判断的对象
  1365. * @return { Boolean } 给定的对象是否是正则表达式
  1366. */
  1367. /**
  1368. * 判断给定的对象是否是一个普通对象
  1369. * @method isObject
  1370. * @param { * } object 需要判断的对象
  1371. * @return { Boolean } 给定的对象是否是普通对象
  1372. */
  1373. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1374. UE.utils['is' + v] = function (obj) {
  1375. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1376. }
  1377. });
  1378. // core/EventBase.js
  1379. /**
  1380. * UE采用的事件基类
  1381. * @file
  1382. * @module UE
  1383. * @class EventBase
  1384. * @since 1.2.6.1
  1385. */
  1386. /**
  1387. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1388. * @unfile
  1389. * @module UE
  1390. */
  1391. /**
  1392. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1393. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1394. * @unfile
  1395. * @module UE
  1396. * @class EventBase
  1397. */
  1398. /**
  1399. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1400. * @constructor
  1401. * @example
  1402. * ```javascript
  1403. * UE.EventBase.call(editor);
  1404. * ```
  1405. */
  1406. var EventBase = UE.EventBase = function () {};
  1407. EventBase.prototype = {
  1408. /**
  1409. * 注册事件监听器
  1410. * @method addListener
  1411. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1412. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1413. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1414. * @example
  1415. * ```javascript
  1416. * editor.addListener('selectionchange',function(){
  1417. * console.log("选区已经变化!");
  1418. * })
  1419. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1420. * if(type == 'beforegetcontent'){
  1421. * //do something
  1422. * }else{
  1423. * //do something
  1424. * }
  1425. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1426. * })
  1427. * ```
  1428. * @see UE.EventBase:fireEvent(String)
  1429. */
  1430. addListener:function (types, listener) {
  1431. types = utils.trim(types).split(/\s+/);
  1432. for (var i = 0, ti; ti = types[i++];) {
  1433. getListener(this, ti, true).push(listener);
  1434. }
  1435. },
  1436. on : function(types, listener){
  1437. return this.addListener(types,listener);
  1438. },
  1439. off : function(types, listener){
  1440. return this.removeListener(types, listener)
  1441. },
  1442. trigger:function(){
  1443. return this.fireEvent.apply(this,arguments);
  1444. },
  1445. /**
  1446. * 移除事件监听器
  1447. * @method removeListener
  1448. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1449. * @param { Function } fn 移除监听事件的函数引用
  1450. * @example
  1451. * ```javascript
  1452. * //changeCallback为方法体
  1453. * editor.removeListener("selectionchange",changeCallback);
  1454. * ```
  1455. */
  1456. removeListener:function (types, listener) {
  1457. types = utils.trim(types).split(/\s+/);
  1458. for (var i = 0, ti; ti = types[i++];) {
  1459. utils.removeItem(getListener(this, ti) || [], listener);
  1460. }
  1461. },
  1462. /**
  1463. * 触发事件
  1464. * @method fireEvent
  1465. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1466. * @remind 该方法会触发addListener
  1467. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1468. * @example
  1469. * ```javascript
  1470. * editor.fireEvent("selectionchange");
  1471. * ```
  1472. */
  1473. /**
  1474. * 触发事件
  1475. * @method fireEvent
  1476. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1477. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1478. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1479. * @example
  1480. * ```javascript
  1481. *
  1482. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1483. *
  1484. * console.log( arg1 + " " + arg2 );
  1485. *
  1486. * } );
  1487. *
  1488. * //触发selectionchange事件, 会执行上面的事件监听器
  1489. * //output: Hello World
  1490. * editor.fireEvent("selectionchange", "Hello", "World");
  1491. * ```
  1492. */
  1493. fireEvent:function () {
  1494. var types = arguments[0];
  1495. types = utils.trim(types).split(' ');
  1496. for (var i = 0, ti; ti = types[i++];) {
  1497. var listeners = getListener(this, ti),
  1498. r, t, k;
  1499. if (listeners) {
  1500. k = listeners.length;
  1501. while (k--) {
  1502. if(!listeners[k])continue;
  1503. t = listeners[k].apply(this, arguments);
  1504. if(t === true){
  1505. return t;
  1506. }
  1507. if (t !== undefined) {
  1508. r = t;
  1509. }
  1510. }
  1511. }
  1512. if (t = this['on' + ti.toLowerCase()]) {
  1513. r = t.apply(this, arguments);
  1514. }
  1515. }
  1516. return r;
  1517. }
  1518. };
  1519. /**
  1520. * 获得对象所拥有监听类型的所有监听器
  1521. * @unfile
  1522. * @module UE
  1523. * @since 1.2.6.1
  1524. * @method getListener
  1525. * @public
  1526. * @param { Object } obj 查询监听器的对象
  1527. * @param { String } type 事件类型
  1528. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1529. * @return { Array } 监听器数组
  1530. */
  1531. function getListener(obj, type, force) {
  1532. var allListeners;
  1533. type = type.toLowerCase();
  1534. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1535. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1536. }
  1537. // core/dtd.js
  1538. ///import editor.js
  1539. ///import core/dom/dom.js
  1540. ///import core/utils.js
  1541. /**
  1542. * dtd html语义化的体现类
  1543. * @constructor
  1544. * @namespace dtd
  1545. */
  1546. var dtd = dom.dtd = (function() {
  1547. function _( s ) {
  1548. for (var k in s) {
  1549. s[k.toUpperCase()] = s[k];
  1550. }
  1551. return s;
  1552. }
  1553. var X = utils.extend2;
  1554. var A = _({isindex:1,fieldset:1}),
  1555. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1556. C = X( _({a:1}), B ),
  1557. D = X( {iframe:1}, C ),
  1558. E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),
  1559. F = _({ins:1,del:1,script:1,style:1}),
  1560. G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ),
  1561. H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ),
  1562. I = X( _({p:1}), H ),
  1563. J = X( _({iframe:1}), H, B ),
  1564. K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),
  1565. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1566. M = _({tr:1}),
  1567. N = _({'#':1}),
  1568. O = X( _({param:1}), K ),
  1569. P = X( _({form:1}), A, D, E, I ),
  1570. Q = _({li:1,ol:1,ul:1}),
  1571. R = _({style:1,script:1}),
  1572. S = _({base:1,link:1,meta:1,title:1}),
  1573. T = X( S, R ),
  1574. U = _({head:1,body:1}),
  1575. V = _({html:1});
  1576. var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),
  1577. empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});
  1578. return _({
  1579. // $ 表示自定的属性
  1580. // body外的元素列表.
  1581. $nonBodyContent: X( V, U, S ),
  1582. //块结构元素列表
  1583. $block : block,
  1584. //内联元素列表
  1585. $inline : L,
  1586. $inlineWithA : X(_({a:1}),L),
  1587. $body : X( _({script:1,style:1}), block ),
  1588. $cdata : _({script:1,style:1}),
  1589. //自闭和元素
  1590. $empty : empty,
  1591. //不是自闭合,但不能让range选中里边
  1592. $nonChild : _({iframe:1,textarea:1}),
  1593. //列表元素列表
  1594. $listItem : _({dd:1,dt:1,li:1}),
  1595. //列表根元素列表
  1596. $list: _({ul:1,ol:1,dl:1}),
  1597. //不能认为是空的元素
  1598. $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),
  1599. //如果没有子节点就可以删除的元素列表,像span,a
  1600. $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}),
  1601. $removeEmptyBlock : _({'p':1,'div':1}),
  1602. //在table元素里的元素列表
  1603. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1604. //不转换的标签
  1605. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1606. html: U,
  1607. head: T,
  1608. style: N,
  1609. script: N,
  1610. body: P,
  1611. base: {},
  1612. link: {},
  1613. meta: {},
  1614. title: N,
  1615. col : {},
  1616. tr : _({td:1,th:1}),
  1617. img : {},
  1618. embed: {},
  1619. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1620. noscript : P,
  1621. td : P,
  1622. br : {},
  1623. th : P,
  1624. center : P,
  1625. kbd : L,
  1626. button : X( I, E ),
  1627. basefont : {},
  1628. h5 : L,
  1629. h4 : L,
  1630. samp : L,
  1631. h6 : L,
  1632. ol : Q,
  1633. h1 : L,
  1634. h3 : L,
  1635. option : N,
  1636. h2 : L,
  1637. form : X( A, D, E, I ),
  1638. select : _({optgroup:1,option:1}),
  1639. font : L,
  1640. ins : L,
  1641. menu : Q,
  1642. abbr : L,
  1643. label : L,
  1644. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1645. code : L,
  1646. tfoot : M,
  1647. cite : L,
  1648. li : P,
  1649. input : {},
  1650. iframe : P,
  1651. strong : L,
  1652. textarea : N,
  1653. noframes : P,
  1654. big : L,
  1655. small : L,
  1656. //trace:
  1657. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1658. hr : L,
  1659. dt : L,
  1660. sub : L,
  1661. optgroup : _({option:1}),
  1662. param : {},
  1663. bdo : L,
  1664. 'var' : L,
  1665. div : P,
  1666. object : O,
  1667. sup : L,
  1668. dd : P,
  1669. strike : L,
  1670. area : {},
  1671. dir : Q,
  1672. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1673. applet : O,
  1674. dl : _({dt:1,dd:1}),
  1675. del : L,
  1676. isindex : {},
  1677. fieldset : X( _({legend:1}), K ),
  1678. thead : M,
  1679. ul : Q,
  1680. acronym : L,
  1681. b : L,
  1682. a : X( _({a:1}), J ),
  1683. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1684. caption : L,
  1685. i : L,
  1686. u : L,
  1687. tbody : M,
  1688. s : L,
  1689. address : X( D, I ),
  1690. tt : L,
  1691. legend : L,
  1692. q : L,
  1693. pre : X( G, C ),
  1694. p : X(_({'a':1}),L),
  1695. em :L,
  1696. dfn : L
  1697. });
  1698. })();
  1699. // core/domUtils.js
  1700. /**
  1701. * Dom操作工具包
  1702. * @file
  1703. * @module UE.dom.domUtils
  1704. * @since 1.2.6.1
  1705. */
  1706. /**
  1707. * Dom操作工具包
  1708. * @unfile
  1709. * @module UE.dom.domUtils
  1710. */
  1711. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1712. var tmpNode = startFromChild && node[start],
  1713. parent;
  1714. !tmpNode && (tmpNode = node[ltr]);
  1715. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1716. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1717. return null;
  1718. }
  1719. tmpNode = parent[ltr];
  1720. }
  1721. if (tmpNode && fn && !fn(tmpNode)) {
  1722. return getDomNode(tmpNode, start, ltr, false, fn);
  1723. }
  1724. return tmpNode;
  1725. }
  1726. var attrFix = ie && browser.version < 9 ? {
  1727. tabindex:"tabIndex",
  1728. readonly:"readOnly",
  1729. "for":"htmlFor",
  1730. "class":"className",
  1731. maxlength:"maxLength",
  1732. cellspacing:"cellSpacing",
  1733. cellpadding:"cellPadding",
  1734. rowspan:"rowSpan",
  1735. colspan:"colSpan",
  1736. usemap:"useMap",
  1737. frameborder:"frameBorder"
  1738. } : {
  1739. tabindex:"tabIndex",
  1740. readonly:"readOnly"
  1741. },
  1742. styleBlock = utils.listToMap([
  1743. '-webkit-box', '-moz-box', 'block' ,
  1744. 'list-item' , 'table' , 'table-row-group' ,
  1745. 'table-header-group', 'table-footer-group' ,
  1746. 'table-row' , 'table-column-group' , 'table-column' ,
  1747. 'table-cell' , 'table-caption'
  1748. ]);
  1749. var domUtils = dom.domUtils = {
  1750. //节点常量
  1751. NODE_ELEMENT:1,
  1752. NODE_DOCUMENT:9,
  1753. NODE_TEXT:3,
  1754. NODE_COMMENT:8,
  1755. NODE_DOCUMENT_FRAGMENT:11,
  1756. //位置关系
  1757. POSITION_IDENTICAL:0,
  1758. POSITION_DISCONNECTED:1,
  1759. POSITION_FOLLOWING:2,
  1760. POSITION_PRECEDING:4,
  1761. POSITION_IS_CONTAINED:8,
  1762. POSITION_CONTAINS:16,
  1763. //ie6使用其他的会有一段空白出现
  1764. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1765. //-------------------------Node部分--------------------------------
  1766. keys:{
  1767. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1768. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1769. 37:1, 38:1, 39:1, 40:1,
  1770. 13:1 /*enter*/
  1771. },
  1772. /**
  1773. * 获取节点A相对于节点B的位置关系
  1774. * @method getPosition
  1775. * @param { Node } nodeA 需要查询位置关系的节点A
  1776. * @param { Node } nodeB 需要查询位置关系的节点B
  1777. * @return { Number } 节点A与节点B的关系
  1778. * @example
  1779. * ```javascript
  1780. * //output: 20
  1781. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1782. *
  1783. * switch ( position ) {
  1784. *
  1785. * //0
  1786. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1787. * console.log('元素相同');
  1788. * break;
  1789. * //1
  1790. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1791. * console.log('两个节点在不同的文档中');
  1792. * break;
  1793. * //2
  1794. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1795. * console.log('节点A在节点B之后');
  1796. * break;
  1797. * //4
  1798. * case UE.dom.domUtils.POSITION_PRECEDING;
  1799. * console.log('节点A在节点B之前');
  1800. * break;
  1801. * //8
  1802. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1803. * console.log('节点A被节点B包含');
  1804. * break;
  1805. * case 10:
  1806. * console.log('节点A被节点B包含且节点A在节点B之后');
  1807. * break;
  1808. * //16
  1809. * case UE.dom.domUtils.POSITION_CONTAINS:
  1810. * console.log('节点A包含节点B');
  1811. * break;
  1812. * case 20:
  1813. * console.log('节点A包含节点B且节点A在节点B之前');
  1814. * break;
  1815. *
  1816. * }
  1817. * ```
  1818. */
  1819. getPosition:function (nodeA, nodeB) {
  1820. // 如果两个节点是同一个节点
  1821. if (nodeA === nodeB) {
  1822. // domUtils.POSITION_IDENTICAL
  1823. return 0;
  1824. }
  1825. var node,
  1826. parentsA = [nodeA],
  1827. parentsB = [nodeB];
  1828. node = nodeA;
  1829. while (node = node.parentNode) {
  1830. // 如果nodeB是nodeA的祖先节点
  1831. if (node === nodeB) {
  1832. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1833. return 10;
  1834. }
  1835. parentsA.push(node);
  1836. }
  1837. node = nodeB;
  1838. while (node = node.parentNode) {
  1839. // 如果nodeA是nodeB的祖先节点
  1840. if (node === nodeA) {
  1841. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1842. return 20;
  1843. }
  1844. parentsB.push(node);
  1845. }
  1846. parentsA.reverse();
  1847. parentsB.reverse();
  1848. if (parentsA[0] !== parentsB[0]) {
  1849. // domUtils.POSITION_DISCONNECTED
  1850. return 1;
  1851. }
  1852. var i = -1;
  1853. while (i++, parentsA[i] === parentsB[i]) {
  1854. }
  1855. nodeA = parentsA[i];
  1856. nodeB = parentsB[i];
  1857. while (nodeA = nodeA.nextSibling) {
  1858. if (nodeA === nodeB) {
  1859. // domUtils.POSITION_PRECEDING
  1860. return 4
  1861. }
  1862. }
  1863. // domUtils.POSITION_FOLLOWING
  1864. return 2;
  1865. },
  1866. /**
  1867. * 检测节点node在父节点中的索引位置
  1868. * @method getNodeIndex
  1869. * @param { Node } node 需要检测的节点对象
  1870. * @return { Number } 该节点在父节点中的位置
  1871. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1872. */
  1873. /**
  1874. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1875. * @method getNodeIndex
  1876. * @param { Node } node 需要检测的节点对象
  1877. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1878. * @return { Number } 该节点在父节点中的位置
  1879. * @example
  1880. * ```javascript
  1881. *
  1882. * var node = document.createElement("div");
  1883. *
  1884. * node.appendChild( document.createTextNode( "hello" ) );
  1885. * node.appendChild( document.createTextNode( "world" ) );
  1886. * node.appendChild( node = document.createElement( "div" ) );
  1887. *
  1888. * //output: 2
  1889. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1890. *
  1891. * //output: 1
  1892. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1893. *
  1894. * ```
  1895. */
  1896. getNodeIndex:function (node, ignoreTextNode) {
  1897. var preNode = node,
  1898. i = 0;
  1899. while (preNode = preNode.previousSibling) {
  1900. if (ignoreTextNode && preNode.nodeType == 3) {
  1901. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1902. i++;
  1903. }
  1904. continue;
  1905. }
  1906. i++;
  1907. }
  1908. return i;
  1909. },
  1910. /**
  1911. * 检测节点node是否在给定的document对象上
  1912. * @method inDoc
  1913. * @param { Node } node 需要检测的节点对象
  1914. * @param { DomDocument } doc 需要检测的document对象
  1915. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1916. * @example
  1917. * ```javascript
  1918. *
  1919. * var node = document.createElement("div");
  1920. *
  1921. * //output: false
  1922. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1923. *
  1924. * document.body.appendChild( node );
  1925. *
  1926. * //output: true
  1927. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1928. *
  1929. * ```
  1930. */
  1931. inDoc:function (node, doc) {
  1932. return domUtils.getPosition(node, doc) == 10;
  1933. },
  1934. /**
  1935. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1936. * 查找的起点是给定node节点的父节点。
  1937. * @method findParent
  1938. * @param { Node } node 需要查找的节点
  1939. * @param { Function } filterFn 自定义的过滤方法。
  1940. * @warning 查找的终点是到body节点为止
  1941. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1942. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1943. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1944. * @example
  1945. * ```javascript
  1946. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1947. *
  1948. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1949. * return node.tagName === "HTML";
  1950. *
  1951. * } );
  1952. *
  1953. * //output: true
  1954. * console.log( filterNode === null );
  1955. * ```
  1956. */
  1957. /**
  1958. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1959. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1960. * @method findParent
  1961. * @param { Node } node 需要查找的节点
  1962. * @param { Function } filterFn 自定义的过滤方法。
  1963. * @param { Boolean } includeSelf 查找过程是否包含自身
  1964. * @warning 查找的终点是到body节点为止
  1965. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1966. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1967. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1968. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1969. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1970. * @example
  1971. * ```html
  1972. * <body>
  1973. *
  1974. * <div id="test">
  1975. * </div>
  1976. *
  1977. * <script type="text/javascript">
  1978. *
  1979. * //output: DIV, BODY
  1980. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1981. *
  1982. * console.log( node.tagName );
  1983. * return false;
  1984. *
  1985. * }, true );
  1986. *
  1987. * </script>
  1988. * </body>
  1989. * ```
  1990. */
  1991. findParent:function (node, filterFn, includeSelf) {
  1992. if (node && !domUtils.isBody(node)) {
  1993. node = includeSelf ? node : node.parentNode;
  1994. while (node) {
  1995. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1996. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1997. }
  1998. node = node.parentNode;
  1999. }
  2000. }
  2001. return null;
  2002. },
  2003. /**
  2004. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2005. * @method findParentByTagName
  2006. * @param { Node } node 需要查找的节点对象
  2007. * @param { Array } tagNames 需要查找的父节点的名称数组
  2008. * @warning 查找的终点是到body节点为止
  2009. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2010. * @example
  2011. * ```javascript
  2012. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2013. * //output: BODY
  2014. * console.log( node.tagName );
  2015. * ```
  2016. */
  2017. /**
  2018. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2019. * 否则, 起点是node的父节点。
  2020. * @method findParentByTagName
  2021. * @param { Node } node 需要查找的节点对象
  2022. * @param { Array } tagNames 需要查找的父节点的名称数组
  2023. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2024. * @warning 查找的终点是到body节点为止
  2025. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2026. * @example
  2027. * ```javascript
  2028. * var queryTarget = document.getElementsByTagName("div")[0];
  2029. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2030. * //output: true
  2031. * console.log( queryTarget === node );
  2032. * ```
  2033. */
  2034. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2035. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2036. return domUtils.findParent(node, function (node) {
  2037. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2038. }, includeSelf);
  2039. },
  2040. /**
  2041. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2042. * @method findParents
  2043. * @param { Node } node 需要查找的节点对象
  2044. * @return { Array } 给定节点的祖先节点数组
  2045. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2046. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2047. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2048. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2049. */
  2050. /**
  2051. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2052. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2053. * @method findParents
  2054. * @param { Node } node 需要查找的节点对象
  2055. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2056. * @return { Array } 给定节点的祖先节点数组
  2057. */
  2058. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2059. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2060. while (node = domUtils.findParent(node, filterFn)) {
  2061. parents.push(node);
  2062. }
  2063. return closerFirst ? parents : parents.reverse();
  2064. },
  2065. /**
  2066. * 在节点node后面插入新节点newNode
  2067. * @method insertAfter
  2068. * @param { Node } node 目标节点
  2069. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2070. * @return { Node } 新插入的节点
  2071. */
  2072. insertAfter:function (node, newNode) {
  2073. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2074. node.parentNode.appendChild(newNode);
  2075. },
  2076. /**
  2077. * 删除节点node及其下属的所有节点
  2078. * @method remove
  2079. * @param { Node } node 需要删除的节点对象
  2080. * @return { Node } 返回刚删除的节点对象
  2081. * @example
  2082. * ```html
  2083. * <div id="test">
  2084. * <div id="child">你好</div>
  2085. * </div>
  2086. * <script>
  2087. * UE.dom.domUtils.remove( document.body, false );
  2088. * //output: false
  2089. * console.log( document.getElementById( "child" ) !== null );
  2090. * </script>
  2091. * ```
  2092. */
  2093. /**
  2094. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2095. * @method remove
  2096. * @param { Node } node 需要删除的节点对象
  2097. * @param { Boolean } keepChildren 是否需要保留子节点
  2098. * @return { Node } 返回刚删除的节点对象
  2099. * @example
  2100. * ```html
  2101. * <div id="test">
  2102. * <div id="child">你好</div>
  2103. * </div>
  2104. * <script>
  2105. * UE.dom.domUtils.remove( document.body, true );
  2106. * //output: true
  2107. * console.log( document.getElementById( "child" ) !== null );
  2108. * </script>
  2109. * ```
  2110. */
  2111. remove:function (node, keepChildren) {
  2112. var parent = node.parentNode,
  2113. child;
  2114. if (parent) {
  2115. if (keepChildren && node.hasChildNodes()) {
  2116. while (child = node.firstChild) {
  2117. parent.insertBefore(child, node);
  2118. }
  2119. }
  2120. parent.removeChild(node);
  2121. }
  2122. return node;
  2123. },
  2124. /**
  2125. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2126. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2127. * @method getNextDomNode
  2128. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2129. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2130. * @example
  2131. * ```html
  2132. * <body>
  2133. * <div id="test">
  2134. * <span></span>
  2135. * </div>
  2136. * <i>xxx</i>
  2137. * </body>
  2138. * <script>
  2139. *
  2140. * //output: i节点
  2141. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2142. *
  2143. * </script>
  2144. * ```
  2145. * @example
  2146. * ```html
  2147. * <body>
  2148. * <div>
  2149. * <span></span>
  2150. * <i id="test">xxx</i>
  2151. * </div>
  2152. * <b>xxx</b>
  2153. * </body>
  2154. * <script>
  2155. *
  2156. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2157. * //output: b节点
  2158. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2159. *
  2160. * </script>
  2161. * ```
  2162. */
  2163. /**
  2164. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2165. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2166. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2167. * @method getNextDomNode
  2168. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2169. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2170. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2171. * @see UE.dom.domUtils.getNextDomNode(Node)
  2172. */
  2173. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2174. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2175. },
  2176. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2177. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2178. },
  2179. /**
  2180. * 检测节点node是否属是UEditor定义的bookmark节点
  2181. * @method isBookmarkNode
  2182. * @private
  2183. * @param { Node } node 需要检测的节点对象
  2184. * @return { Boolean } 是否是bookmark节点
  2185. * @example
  2186. * ```html
  2187. * <span id="_baidu_bookmark_1"></span>
  2188. * <script>
  2189. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2190. * //output: true
  2191. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2192. * </script>
  2193. * ```
  2194. */
  2195. isBookmarkNode:function (node) {
  2196. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2197. },
  2198. /**
  2199. * 获取节点node所属的window对象
  2200. * @method getWindow
  2201. * @param { Node } node 节点对象
  2202. * @return { Window } 当前节点所属的window对象
  2203. * @example
  2204. * ```javascript
  2205. * //output: true
  2206. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2207. * ```
  2208. */
  2209. getWindow:function (node) {
  2210. var doc = node.ownerDocument || node;
  2211. return doc.defaultView || doc.parentWindow;
  2212. },
  2213. /**
  2214. * 获取离nodeA与nodeB最近的公共的祖先节点
  2215. * @method getCommonAncestor
  2216. * @param { Node } nodeA 第一个节点
  2217. * @param { Node } nodeB 第二个节点
  2218. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2219. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2220. * @example
  2221. * ```javascript
  2222. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2223. * //output: true
  2224. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2225. * ```
  2226. */
  2227. getCommonAncestor:function (nodeA, nodeB) {
  2228. if (nodeA === nodeB)
  2229. return nodeA;
  2230. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2231. while (parent = parent.parentNode) {
  2232. if (parent === nodeB) {
  2233. return parent;
  2234. }
  2235. parentsA.push(parent);
  2236. }
  2237. parent = nodeB;
  2238. while (parent = parent.parentNode) {
  2239. if (parent === nodeA)
  2240. return parent;
  2241. parentsB.push(parent);
  2242. }
  2243. parentsA.reverse();
  2244. parentsB.reverse();
  2245. while (i++, parentsA[i] === parentsB[i]) {
  2246. }
  2247. return i == 0 ? null : parentsA[i - 1];
  2248. },
  2249. /**
  2250. * 清除node节点左右连续为空的兄弟inline节点
  2251. * @method clearEmptySibling
  2252. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2253. * 则这些兄弟节点将被删除
  2254. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2255. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2256. * @example
  2257. * ```html
  2258. * <body>
  2259. * <div></div>
  2260. * <span id="test"></span>
  2261. * <i></i>
  2262. * <b></b>
  2263. * <em>xxx</em>
  2264. * <span></span>
  2265. * </body>
  2266. * <script>
  2267. *
  2268. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2269. *
  2270. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2271. * console.log( document.body.innerHTML );
  2272. *
  2273. * </script>
  2274. * ```
  2275. */
  2276. /**
  2277. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2278. * 则忽略对右边兄弟节点的操作。
  2279. * @method clearEmptySibling
  2280. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2281. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2282. * 则这些兄弟节点将被删除
  2283. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2284. */
  2285. /**
  2286. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2287. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2288. * @method clearEmptySibling
  2289. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2290. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2291. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2292. * 则这些兄弟节点将被删除
  2293. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2294. */
  2295. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2296. function clear(next, dir) {
  2297. var tmpNode;
  2298. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2299. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2300. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2301. tmpNode = next[dir];
  2302. domUtils.remove(next);
  2303. next = tmpNode;
  2304. }
  2305. }
  2306. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2307. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2308. },
  2309. /**
  2310. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2311. * @method split
  2312. * @param { Node } textNode 需要拆分的文本节点对象
  2313. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2314. * @return { Node } 拆分后形成的新节点
  2315. * @example
  2316. * ```html
  2317. * <div id="test">abcdef</div>
  2318. * <script>
  2319. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2320. * //output: def
  2321. * console.log( newNode.nodeValue );
  2322. * </script>
  2323. * ```
  2324. */
  2325. split:function (node, offset) {
  2326. var doc = node.ownerDocument;
  2327. if (browser.ie && offset == node.nodeValue.length) {
  2328. var next = doc.createTextNode('');
  2329. return domUtils.insertAfter(node, next);
  2330. }
  2331. var retval = node.splitText(offset);
  2332. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2333. if (browser.ie8) {
  2334. var tmpNode = doc.createTextNode('');
  2335. domUtils.insertAfter(retval, tmpNode);
  2336. domUtils.remove(tmpNode);
  2337. }
  2338. return retval;
  2339. },
  2340. /**
  2341. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2342. * @method isWhitespace
  2343. * @param { Node } node 需要检测的节点对象
  2344. * @return { Boolean } 检测的节点是否为空
  2345. * @example
  2346. * ```html
  2347. * <div id="test">
  2348. *
  2349. * </div>
  2350. * <script>
  2351. * //output: true
  2352. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2353. * </script>
  2354. * ```
  2355. */
  2356. isWhitespace:function (node) {
  2357. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2358. },
  2359. /**
  2360. * 获取元素element相对于viewport的位置坐标
  2361. * @method getXY
  2362. * @param { Node } element 需要计算位置的节点对象
  2363. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2364. * y代表垂直偏移距离。
  2365. *
  2366. * @example
  2367. * ```javascript
  2368. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2369. * //output: test的坐标为: 12, 24
  2370. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2371. * ```
  2372. */
  2373. getXY:function (element) {
  2374. var x = 0, y = 0;
  2375. while (element.offsetParent) {
  2376. y += element.offsetTop;
  2377. x += element.offsetLeft;
  2378. element = element.offsetParent;
  2379. }
  2380. return { 'x':x, 'y':y};
  2381. },
  2382. /**
  2383. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2384. * @method on
  2385. * @param { Node } element 需要绑定事件的节点对象
  2386. * @param { String } type 绑定的事件类型
  2387. * @param { Function } handler 事件处理器
  2388. * @example
  2389. * ```javascript
  2390. * UE.dom.domUtils.on(document.body,"click",function(e){
  2391. * //e为事件对象,this为被点击元素对戏那个
  2392. * });
  2393. * ```
  2394. */
  2395. /**
  2396. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2397. * @method on
  2398. * @param { Node } element 需要绑定事件的节点对象
  2399. * @param { Array } type 绑定的事件类型数组
  2400. * @param { Function } handler 事件处理器
  2401. * @example
  2402. * ```javascript
  2403. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2404. * //evt为事件对象,this为被点击元素对象
  2405. * });
  2406. * ```
  2407. */
  2408. on:function (element, type, handler) {
  2409. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2410. k = types.length;
  2411. if (k) while (k--) {
  2412. type = types[k];
  2413. if (element.addEventListener) {
  2414. element.addEventListener(type, handler, false);
  2415. } else {
  2416. if (!handler._d) {
  2417. handler._d = {
  2418. els : []
  2419. };
  2420. }
  2421. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2422. if (!handler._d[key] || index == -1) {
  2423. if(index == -1){
  2424. handler._d.els.push(element);
  2425. }
  2426. if(!handler._d[key]){
  2427. handler._d[key] = function (evt) {
  2428. return handler.call(evt.srcElement, evt || window.event);
  2429. };
  2430. }
  2431. element.attachEvent('on' + type, handler._d[key]);
  2432. }
  2433. }
  2434. }
  2435. element = null;
  2436. },
  2437. /**
  2438. * 解除DOM事件绑定
  2439. * @method un
  2440. * @param { Node } element 需要解除事件绑定的节点对象
  2441. * @param { String } type 需要接触绑定的事件类型
  2442. * @param { Function } handler 对应的事件处理器
  2443. * @example
  2444. * ```javascript
  2445. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2446. * //evt为事件对象,this为被点击元素对象
  2447. * });
  2448. * ```
  2449. */
  2450. /**
  2451. * 解除DOM事件绑定
  2452. * @method un
  2453. * @param { Node } element 需要解除事件绑定的节点对象
  2454. * @param { Array } type 需要接触绑定的事件类型数组
  2455. * @param { Function } handler 对应的事件处理器
  2456. * @example
  2457. * ```javascript
  2458. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2459. * //evt为事件对象,this为被点击元素对象
  2460. * });
  2461. * ```
  2462. */
  2463. un:function (element, type, handler) {
  2464. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2465. k = types.length;
  2466. if (k) while (k--) {
  2467. type = types[k];
  2468. if (element.removeEventListener) {
  2469. element.removeEventListener(type, handler, false);
  2470. } else {
  2471. var key = type + handler.toString();
  2472. try{
  2473. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2474. }catch(e){}
  2475. if (handler._d && handler._d[key]) {
  2476. var index = utils.indexOf(handler._d.els,element);
  2477. if(index!=-1){
  2478. handler._d.els.splice(index,1);
  2479. }
  2480. handler._d.els.length == 0 && delete handler._d[key];
  2481. }
  2482. }
  2483. }
  2484. },
  2485. /**
  2486. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2487. * @method isSameElement
  2488. * @param { Node } nodeA 需要比较的节点
  2489. * @param { Node } nodeB 需要比较的节点
  2490. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2491. * @example
  2492. * ```html
  2493. * <span style="font-size:12px">ssss</span>
  2494. * <span style="font-size:12px">bbbbb</span>
  2495. * <span style="font-size:13px">ssss</span>
  2496. * <span style="font-size:14px">bbbbb</span>
  2497. *
  2498. * <script>
  2499. *
  2500. * var nodes = document.getElementsByTagName( "span" );
  2501. *
  2502. * //output: true
  2503. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2504. *
  2505. * //output: false
  2506. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2507. *
  2508. * </script>
  2509. * ```
  2510. */
  2511. isSameElement:function (nodeA, nodeB) {
  2512. if (nodeA.tagName != nodeB.tagName) {
  2513. return false;
  2514. }
  2515. var thisAttrs = nodeA.attributes,
  2516. otherAttrs = nodeB.attributes;
  2517. if (!ie && thisAttrs.length != otherAttrs.length) {
  2518. return false;
  2519. }
  2520. var attrA, attrB, al = 0, bl = 0;
  2521. for (var i = 0; attrA = thisAttrs[i++];) {
  2522. if (attrA.nodeName == 'style') {
  2523. if (attrA.specified) {
  2524. al++;
  2525. }
  2526. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2527. continue;
  2528. } else {
  2529. return false;
  2530. }
  2531. }
  2532. if (ie) {
  2533. if (attrA.specified) {
  2534. al++;
  2535. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2536. } else {
  2537. continue;
  2538. }
  2539. } else {
  2540. attrB = nodeB.attributes[attrA.nodeName];
  2541. }
  2542. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2543. return false;
  2544. }
  2545. }
  2546. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2547. if (ie) {
  2548. for (i = 0; attrB = otherAttrs[i++];) {
  2549. if (attrB.specified) {
  2550. bl++;
  2551. }
  2552. }
  2553. if (al != bl) {
  2554. return false;
  2555. }
  2556. }
  2557. return true;
  2558. },
  2559. /**
  2560. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2561. * @method isSameStyle
  2562. * @param { Node } nodeA 需要比较的节点
  2563. * @param { Node } nodeB 需要比较的节点
  2564. * @return { Boolean } 两个节点是否具有相同的style属性值
  2565. * @example
  2566. * ```html
  2567. * <span style="font-size:12px">ssss</span>
  2568. * <span style="font-size:12px">bbbbb</span>
  2569. * <span style="font-size:13px">ssss</span>
  2570. * <span style="font-size:14px">bbbbb</span>
  2571. *
  2572. * <script>
  2573. *
  2574. * var nodes = document.getElementsByTagName( "span" );
  2575. *
  2576. * //output: true
  2577. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2578. *
  2579. * //output: false
  2580. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2581. *
  2582. * </script>
  2583. * ```
  2584. */
  2585. isSameStyle:function (nodeA, nodeB) {
  2586. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2587. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2588. if (browser.opera) {
  2589. styleA = nodeA.style;
  2590. styleB = nodeB.style;
  2591. if (styleA.length != styleB.length)
  2592. return false;
  2593. for (var p in styleA) {
  2594. if (/^(\d+|csstext)$/i.test(p)) {
  2595. continue;
  2596. }
  2597. if (styleA[p] != styleB[p]) {
  2598. return false;
  2599. }
  2600. }
  2601. return true;
  2602. }
  2603. if (!styleA || !styleB) {
  2604. return styleA == styleB;
  2605. }
  2606. styleA = styleA.split(';');
  2607. styleB = styleB.split(';');
  2608. if (styleA.length != styleB.length) {
  2609. return false;
  2610. }
  2611. for (var i = 0, ci; ci = styleA[i++];) {
  2612. if (utils.indexOf(styleB, ci) == -1) {
  2613. return false;
  2614. }
  2615. }
  2616. return true;
  2617. },
  2618. /**
  2619. * 检查节点node是否为block元素
  2620. * @method isBlockElm
  2621. * @param { Node } node 需要检测的节点对象
  2622. * @return { Boolean } 是否是block元素节点
  2623. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2624. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2625. * @example
  2626. * ```html
  2627. * <span id="test1" style="display: block"></span>
  2628. * <span id="test2"></span>
  2629. * <div id="test3" style="display: inline"></div>
  2630. *
  2631. * <script>
  2632. *
  2633. * //output: true
  2634. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2635. *
  2636. * //output: false
  2637. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2638. *
  2639. * //output: true
  2640. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2641. *
  2642. * </script>
  2643. * ```
  2644. */
  2645. isBlockElm:function (node) {
  2646. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2647. },
  2648. /**
  2649. * 检测node节点是否为body节点
  2650. * @method isBody
  2651. * @param { Element } node 需要检测的dom元素
  2652. * @return { Boolean } 给定的元素是否是body元素
  2653. * @example
  2654. * ```javascript
  2655. * //output: true
  2656. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2657. * ```
  2658. */
  2659. isBody:function (node) {
  2660. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2661. },
  2662. /**
  2663. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2664. * 拆分形成的两个节点之间是node节点
  2665. * @method breakParent
  2666. * @param { Node } node 作为分界的节点对象
  2667. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2668. * @return { Node } 给定的node分界节点
  2669. * @example
  2670. * ```javascript
  2671. *
  2672. * var node = document.createElement("span"),
  2673. * wrapNode = document.createElement( "div" ),
  2674. * parent = document.createElement("p");
  2675. *
  2676. * parent.appendChild( node );
  2677. * wrapNode.appendChild( parent );
  2678. *
  2679. * //拆分前
  2680. * //output: <p><span></span></p>
  2681. * console.log( wrapNode.innerHTML );
  2682. *
  2683. *
  2684. * UE.dom.domUtils.breakParent( node, parent );
  2685. * //拆分后
  2686. * //output: <p></p><span></span><p></p>
  2687. * console.log( wrapNode.innerHTML );
  2688. *
  2689. * ```
  2690. */
  2691. breakParent:function (node, parent) {
  2692. var tmpNode,
  2693. parentClone = node,
  2694. clone = node,
  2695. leftNodes,
  2696. rightNodes;
  2697. do {
  2698. parentClone = parentClone.parentNode;
  2699. if (leftNodes) {
  2700. tmpNode = parentClone.cloneNode(false);
  2701. tmpNode.appendChild(leftNodes);
  2702. leftNodes = tmpNode;
  2703. tmpNode = parentClone.cloneNode(false);
  2704. tmpNode.appendChild(rightNodes);
  2705. rightNodes = tmpNode;
  2706. } else {
  2707. leftNodes = parentClone.cloneNode(false);
  2708. rightNodes = leftNodes.cloneNode(false);
  2709. }
  2710. while (tmpNode = clone.previousSibling) {
  2711. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2712. }
  2713. while (tmpNode = clone.nextSibling) {
  2714. rightNodes.appendChild(tmpNode);
  2715. }
  2716. clone = parentClone;
  2717. } while (parent !== parentClone);
  2718. tmpNode = parent.parentNode;
  2719. tmpNode.insertBefore(leftNodes, parent);
  2720. tmpNode.insertBefore(rightNodes, parent);
  2721. tmpNode.insertBefore(node, rightNodes);
  2722. domUtils.remove(parent);
  2723. return node;
  2724. },
  2725. /**
  2726. * 检查节点node是否是空inline节点
  2727. * @method isEmptyInlineElement
  2728. * @param { Node } node 需要检测的节点对象
  2729. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2730. * @example
  2731. * ```html
  2732. * <b><i></i></b> => 1
  2733. * <b><i></i><u></u></b> => 1
  2734. * <b></b> => 1
  2735. * <b>xx<i></i></b> => 0
  2736. * ```
  2737. */
  2738. isEmptyInlineElement:function (node) {
  2739. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2740. return 0;
  2741. }
  2742. node = node.firstChild;
  2743. while (node) {
  2744. //如果是创建的bookmark就跳过
  2745. if (domUtils.isBookmarkNode(node)) {
  2746. return 0;
  2747. }
  2748. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2749. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2750. ) {
  2751. return 0;
  2752. }
  2753. node = node.nextSibling;
  2754. }
  2755. return 1;
  2756. },
  2757. /**
  2758. * 删除node节点下首尾两端的空白文本子节点
  2759. * @method trimWhiteTextNode
  2760. * @param { Element } node 需要执行删除操作的元素对象
  2761. * @example
  2762. * ```javascript
  2763. * var node = document.createElement("div");
  2764. *
  2765. * node.appendChild( document.createTextNode( "" ) );
  2766. *
  2767. * node.appendChild( document.createElement("div") );
  2768. *
  2769. * node.appendChild( document.createTextNode( "" ) );
  2770. *
  2771. * //3
  2772. * console.log( node.childNodes.length );
  2773. *
  2774. * UE.dom.domUtils.trimWhiteTextNode( node );
  2775. *
  2776. * //1
  2777. * console.log( node.childNodes.length );
  2778. * ```
  2779. */
  2780. trimWhiteTextNode:function (node) {
  2781. function remove(dir) {
  2782. var child;
  2783. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2784. node.removeChild(child);
  2785. }
  2786. }
  2787. remove('firstChild');
  2788. remove('lastChild');
  2789. },
  2790. /**
  2791. * 合并node节点下相同的子节点
  2792. * @name mergeChild
  2793. * @desc
  2794. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2795. * @example
  2796. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2797. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2798. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2799. */
  2800. mergeChild:function (node, tagName, attrs) {
  2801. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2802. for (var i = 0, ci; ci = list[i++];) {
  2803. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2804. continue;
  2805. }
  2806. //span单独处理
  2807. if (ci.tagName.toLowerCase() == 'span') {
  2808. if (node === ci.parentNode) {
  2809. domUtils.trimWhiteTextNode(node);
  2810. if (node.childNodes.length == 1) {
  2811. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2812. domUtils.remove(ci, true);
  2813. continue;
  2814. }
  2815. }
  2816. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2817. if (attrs) {
  2818. var style = attrs.style;
  2819. if (style) {
  2820. style = style.split(';');
  2821. for (var j = 0, s; s = style[j++];) {
  2822. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2823. }
  2824. }
  2825. }
  2826. if (domUtils.isSameStyle(ci, node)) {
  2827. domUtils.remove(ci, true);
  2828. }
  2829. continue;
  2830. }
  2831. if (domUtils.isSameElement(node, ci)) {
  2832. domUtils.remove(ci, true);
  2833. }
  2834. }
  2835. },
  2836. /**
  2837. * 原生方法getElementsByTagName的封装
  2838. * @method getElementsByTagName
  2839. * @param { Node } node 目标节点对象
  2840. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2841. * @return { Array } 符合条件的节点集合
  2842. */
  2843. getElementsByTagName:function (node, name,filter) {
  2844. if(filter && utils.isString(filter)){
  2845. var className = filter;
  2846. filter = function(node){return domUtils.hasClass(node,className)}
  2847. }
  2848. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2849. var arr = [];
  2850. for(var n = 0,ni;ni=name[n++];){
  2851. var list = node.getElementsByTagName(ni);
  2852. for (var i = 0, ci; ci = list[i++];) {
  2853. if(!filter || filter(ci))
  2854. arr.push(ci);
  2855. }
  2856. }
  2857. return arr;
  2858. },
  2859. /**
  2860. * 将节点node提取到父节点上
  2861. * @method mergeToParent
  2862. * @param { Element } node 需要提取的元素对象
  2863. * @example
  2864. * ```html
  2865. * <div id="parent">
  2866. * <div id="sub">
  2867. * <span id="child"></span>
  2868. * </div>
  2869. * </div>
  2870. *
  2871. * <script>
  2872. *
  2873. * var child = document.getElementById( "child" );
  2874. *
  2875. * //output: sub
  2876. * console.log( child.parentNode.id );
  2877. *
  2878. * UE.dom.domUtils.mergeToParent( child );
  2879. *
  2880. * //output: parent
  2881. * console.log( child.parentNode.id );
  2882. *
  2883. * </script>
  2884. * ```
  2885. */
  2886. mergeToParent:function (node) {
  2887. var parent = node.parentNode;
  2888. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2889. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2890. domUtils.trimWhiteTextNode(parent);
  2891. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2892. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2893. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2894. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2895. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2896. parent = parent.parentNode;
  2897. continue;
  2898. } else {
  2899. parent.style.cssText += ";" + node.style.cssText;
  2900. //trace:952 a标签要保持下划线
  2901. if (parent.tagName == 'A') {
  2902. parent.style.textDecoration = 'underline';
  2903. }
  2904. }
  2905. }
  2906. if (parent.tagName != 'A') {
  2907. parent === node.parentNode && domUtils.remove(node, true);
  2908. break;
  2909. }
  2910. }
  2911. parent = parent.parentNode;
  2912. }
  2913. },
  2914. /**
  2915. * 合并节点node的左右兄弟节点
  2916. * @method mergeSibling
  2917. * @param { Element } node 需要合并的目标节点
  2918. * @example
  2919. * ```html
  2920. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2921. *
  2922. * <script>
  2923. * var demoNode = document.getElementById("test");
  2924. * UE.dom.domUtils.mergeSibling( demoNode );
  2925. * //output: xxxxoooxxxx
  2926. * console.log( demoNode.innerHTML );
  2927. * </script>
  2928. * ```
  2929. */
  2930. /**
  2931. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2932. * @method mergeSibling
  2933. * @param { Element } node 需要合并的目标节点
  2934. * @param { Boolean } ignorePre 是否忽略合并左节点
  2935. * @example
  2936. * ```html
  2937. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2938. *
  2939. * <script>
  2940. * var demoNode = document.getElementById("test");
  2941. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2942. * //output: oooxxxx
  2943. * console.log( demoNode.innerHTML );
  2944. * </script>
  2945. * ```
  2946. */
  2947. /**
  2948. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2949. * @method mergeSibling
  2950. * @param { Element } node 需要合并的目标节点
  2951. * @param { Boolean } ignorePre 是否忽略合并左节点
  2952. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2953. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2954. * @example
  2955. * ```html
  2956. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2957. *
  2958. * <script>
  2959. * var demoNode = document.getElementById("test");
  2960. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2961. * //output: xxxxooo
  2962. * console.log( demoNode.innerHTML );
  2963. * </script>
  2964. * ```
  2965. */
  2966. mergeSibling:function (node, ignorePre, ignoreNext) {
  2967. function merge(rtl, start, node) {
  2968. var next;
  2969. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2970. while (next.firstChild) {
  2971. if (start == 'firstChild') {
  2972. node.insertBefore(next.lastChild, node.firstChild);
  2973. } else {
  2974. node.appendChild(next.firstChild);
  2975. }
  2976. }
  2977. domUtils.remove(next);
  2978. }
  2979. }
  2980. !ignorePre && merge('previousSibling', 'firstChild', node);
  2981. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2982. },
  2983. /**
  2984. * 设置节点node及其子节点不会被选中
  2985. * @method unSelectable
  2986. * @param { Element } node 需要执行操作的dom元素
  2987. * @remind 执行该操作后的节点, 将不能被鼠标选中
  2988. * @example
  2989. * ```javascript
  2990. * UE.dom.domUtils.unSelectable( document.body );
  2991. * ```
  2992. */
  2993. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  2994. //for ie9
  2995. node.onselectstart = function () {
  2996. return false;
  2997. };
  2998. node.onclick = node.onkeyup = node.onkeydown = function () {
  2999. return false;
  3000. };
  3001. node.unselectable = 'on';
  3002. node.setAttribute("unselectable", "on");
  3003. for (var i = 0, ci; ci = node.all[i++];) {
  3004. switch (ci.tagName.toLowerCase()) {
  3005. case 'iframe' :
  3006. case 'textarea' :
  3007. case 'input' :
  3008. case 'select' :
  3009. break;
  3010. default :
  3011. ci.unselectable = 'on';
  3012. node.setAttribute("unselectable", "on");
  3013. }
  3014. }
  3015. } : function (node) {
  3016. node.style.MozUserSelect =
  3017. node.style.webkitUserSelect =
  3018. node.style.msUserSelect =
  3019. node.style.KhtmlUserSelect = 'none';
  3020. },
  3021. /**
  3022. * 删除节点node上的指定属性名称的属性
  3023. * @method removeAttributes
  3024. * @param { Node } node 需要删除属性的节点对象
  3025. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3026. * @example
  3027. * ```html
  3028. * <div id="wrap">
  3029. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3030. * </div>
  3031. *
  3032. * <script>
  3033. *
  3034. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3035. *
  3036. * //output: <span style="font-size:14px;">xxxxx</span>
  3037. * console.log( document.getElementById("wrap").innerHTML );
  3038. *
  3039. * </script>
  3040. * ```
  3041. */
  3042. /**
  3043. * 删除节点node上的指定属性名称的属性
  3044. * @method removeAttributes
  3045. * @param { Node } node 需要删除属性的节点对象
  3046. * @param { Array } attrNames 需要删除的属性名数组
  3047. * @example
  3048. * ```html
  3049. * <div id="wrap">
  3050. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3051. * </div>
  3052. *
  3053. * <script>
  3054. *
  3055. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3056. *
  3057. * //output: <span style="font-size:14px;">xxxxx</span>
  3058. * console.log( document.getElementById("wrap").innerHTML );
  3059. *
  3060. * </script>
  3061. * ```
  3062. */
  3063. removeAttributes:function (node, attrNames) {
  3064. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3065. for (var i = 0, ci; ci = attrNames[i++];) {
  3066. ci = attrFix[ci] || ci;
  3067. switch (ci) {
  3068. case 'className':
  3069. node[ci] = '';
  3070. break;
  3071. case 'style':
  3072. node.style.cssText = '';
  3073. var val = node.getAttributeNode('style');
  3074. !browser.ie && val && node.removeAttributeNode(val);
  3075. }
  3076. node.removeAttribute(ci);
  3077. }
  3078. },
  3079. /**
  3080. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3081. * @method createElement
  3082. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3083. * @param { String } tagName 需要创建的元素的标签名
  3084. * @param { Object } attrs 新创建的元素的属性key-value集合
  3085. * @return { Element } 新创建的元素对象
  3086. * @example
  3087. * ```javascript
  3088. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3089. * id: 'test'
  3090. * } );
  3091. *
  3092. * //output: DIV
  3093. * console.log( ele.tagName );
  3094. *
  3095. * //output: test
  3096. * console.log( ele.id );
  3097. *
  3098. * ```
  3099. */
  3100. createElement:function (doc, tag, attrs) {
  3101. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3102. },
  3103. /**
  3104. * 为节点node添加属性attrs,attrs为属性键值对
  3105. * @method setAttributes
  3106. * @param { Element } node 需要设置属性的元素对象
  3107. * @param { Object } attrs 需要设置的属性名-值对
  3108. * @return { Element } 设置属性的元素对象
  3109. * @example
  3110. * ```html
  3111. * <span id="test"></span>
  3112. *
  3113. * <script>
  3114. *
  3115. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3116. * id: 'demo'
  3117. * } );
  3118. *
  3119. * //output: demo
  3120. * console.log( testNode.id );
  3121. *
  3122. * </script>
  3123. *
  3124. */
  3125. setAttributes:function (node, attrs) {
  3126. for (var attr in attrs) {
  3127. if(attrs.hasOwnProperty(attr)){
  3128. var value = attrs[attr];
  3129. switch (attr) {
  3130. case 'class':
  3131. //ie下要这样赋值,setAttribute不起作用
  3132. node.className = value;
  3133. break;
  3134. case 'style' :
  3135. node.style.cssText = node.style.cssText + ";" + value;
  3136. break;
  3137. case 'innerHTML':
  3138. node[attr] = value;
  3139. break;
  3140. case 'value':
  3141. node.value = value;
  3142. break;
  3143. default:
  3144. node.setAttribute(attrFix[attr] || attr, value);
  3145. }
  3146. }
  3147. }
  3148. return node;
  3149. },
  3150. /**
  3151. * 获取元素element经过计算后的样式值
  3152. * @method getComputedStyle
  3153. * @param { Element } element 需要获取样式的元素对象
  3154. * @param { String } styleName 需要获取的样式名
  3155. * @return { String } 获取到的样式值
  3156. * @example
  3157. * ```html
  3158. * <style type="text/css">
  3159. * #test {
  3160. * font-size: 15px;
  3161. * }
  3162. * </style>
  3163. *
  3164. * <span id="test"></span>
  3165. *
  3166. * <script>
  3167. * //output: 15px
  3168. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3169. * </script>
  3170. * ```
  3171. */
  3172. getComputedStyle:function (element, styleName) {
  3173. //一下的属性单独处理
  3174. var pros = 'width height top left';
  3175. if(pros.indexOf(styleName) > -1){
  3176. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3177. }
  3178. //忽略文本节点
  3179. if (element.nodeType == 3) {
  3180. element = element.parentNode;
  3181. }
  3182. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3183. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3184. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3185. var span = element.ownerDocument.createElement('span');
  3186. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3187. span.innerHTML = '.';
  3188. element.appendChild(span);
  3189. var result = span.offsetHeight;
  3190. element.removeChild(span);
  3191. span = null;
  3192. return result + 'px';
  3193. }
  3194. try {
  3195. var value = domUtils.getStyle(element, styleName) ||
  3196. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3197. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3198. } catch (e) {
  3199. return "";
  3200. }
  3201. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3202. },
  3203. /**
  3204. * 删除元素element指定的className
  3205. * @method removeClasses
  3206. * @param { Element } ele 需要删除class的元素节点
  3207. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3208. * @example
  3209. * ```html
  3210. * <span id="test" class="test1 test2 test3">xxx</span>
  3211. *
  3212. * <script>
  3213. *
  3214. * var testNode = document.getElementById( "test" );
  3215. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3216. *
  3217. * //output: test3
  3218. * console.log( testNode.className );
  3219. *
  3220. * </script>
  3221. * ```
  3222. */
  3223. /**
  3224. * 删除元素element指定的className
  3225. * @method removeClasses
  3226. * @param { Element } ele 需要删除class的元素节点
  3227. * @param { Array } classNames 需要删除的className数组
  3228. * @example
  3229. * ```html
  3230. * <span id="test" class="test1 test2 test3">xxx</span>
  3231. *
  3232. * <script>
  3233. *
  3234. * var testNode = document.getElementById( "test" );
  3235. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3236. *
  3237. * //output: test3
  3238. * console.log( testNode.className );
  3239. *
  3240. * </script>
  3241. * ```
  3242. */
  3243. removeClasses:function (elm, classNames) {
  3244. classNames = utils.isArray(classNames) ? classNames :
  3245. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3246. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3247. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3248. }
  3249. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3250. if(cls){
  3251. elm.className = cls;
  3252. }else{
  3253. domUtils.removeAttributes(elm,['class']);
  3254. }
  3255. },
  3256. /**
  3257. * 给元素element添加className
  3258. * @method addClass
  3259. * @param { Node } ele 需要增加className的元素
  3260. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3261. * @remind 相同的类名不会被重复添加
  3262. * @example
  3263. * ```html
  3264. * <span id="test" class="cls1 cls2"></span>
  3265. *
  3266. * <script>
  3267. * var testNode = document.getElementById("test");
  3268. *
  3269. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3270. *
  3271. * //output: cl1 cls2 cls3 cls4
  3272. * console.log( testNode.className );
  3273. *
  3274. * <script>
  3275. * ```
  3276. */
  3277. /**
  3278. * 给元素element添加className
  3279. * @method addClass
  3280. * @param { Node } ele 需要增加className的元素
  3281. * @param { Array } classNames 需要添加的className的数组
  3282. * @remind 相同的类名不会被重复添加
  3283. * @example
  3284. * ```html
  3285. * <span id="test" class="cls1 cls2"></span>
  3286. *
  3287. * <script>
  3288. * var testNode = document.getElementById("test");
  3289. *
  3290. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3291. *
  3292. * //output: cl1 cls2 cls3 cls4
  3293. * console.log( testNode.className );
  3294. *
  3295. * <script>
  3296. * ```
  3297. */
  3298. addClass:function (elm, classNames) {
  3299. if(!elm)return;
  3300. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3301. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3302. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3303. cls += ' ' + ci;
  3304. }
  3305. }
  3306. elm.className = utils.trim(cls);
  3307. },
  3308. /**
  3309. * 判断元素element是否包含给定的样式类名className
  3310. * @method hasClass
  3311. * @param { Node } ele 需要检测的元素
  3312. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3313. * @return { Boolean } 元素是否包含所有给定的className
  3314. * @example
  3315. * ```html
  3316. * <span id="test1" class="cls1 cls2"></span>
  3317. *
  3318. * <script>
  3319. * var test1 = document.getElementById("test1");
  3320. *
  3321. * //output: false
  3322. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3323. *
  3324. * //output: true
  3325. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3326. * </script>
  3327. * ```
  3328. */
  3329. /**
  3330. * 判断元素element是否包含给定的样式类名className
  3331. * @method hasClass
  3332. * @param { Node } ele 需要检测的元素
  3333. * @param { Array } classNames 需要检测的className数组
  3334. * @return { Boolean } 元素是否包含所有给定的className
  3335. * @example
  3336. * ```html
  3337. * <span id="test1" class="cls1 cls2"></span>
  3338. *
  3339. * <script>
  3340. * var test1 = document.getElementById("test1");
  3341. *
  3342. * //output: false
  3343. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3344. *
  3345. * //output: true
  3346. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3347. * </script>
  3348. * ```
  3349. */
  3350. hasClass:function (element, className) {
  3351. if(utils.isRegExp(className)){
  3352. return className.test(element.className)
  3353. }
  3354. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3355. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3356. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3357. return false;
  3358. }
  3359. }
  3360. return i - 1 == className.length;
  3361. },
  3362. /**
  3363. * 阻止事件默认行为
  3364. * @method preventDefault
  3365. * @param { Event } evt 需要阻止默认行为的事件对象
  3366. * @example
  3367. * ```javascript
  3368. * UE.dom.domUtils.preventDefault( evt );
  3369. * ```
  3370. */
  3371. preventDefault:function (evt) {
  3372. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3373. },
  3374. /**
  3375. * 删除元素element指定的样式
  3376. * @method removeStyle
  3377. * @param { Element } element 需要删除样式的元素
  3378. * @param { String } styleName 需要删除的样式名
  3379. * @example
  3380. * ```html
  3381. * <span id="test" style="color: red; background: blue;"></span>
  3382. *
  3383. * <script>
  3384. *
  3385. * var testNode = document.getElementById("test");
  3386. *
  3387. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3388. *
  3389. * //output: background: blue;
  3390. * console.log( testNode.style.cssText );
  3391. *
  3392. * </script>
  3393. * ```
  3394. */
  3395. removeStyle:function (element, name) {
  3396. if(browser.ie ){
  3397. //针对color先单独处理一下
  3398. if(name == 'color'){
  3399. name = '(^|;)' + name;
  3400. }
  3401. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3402. }else{
  3403. if (element.style.removeProperty) {
  3404. element.style.removeProperty (name);
  3405. }else {
  3406. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3407. }
  3408. }
  3409. if (!element.style.cssText) {
  3410. domUtils.removeAttributes(element, ['style']);
  3411. }
  3412. },
  3413. /**
  3414. * 获取元素element的style属性的指定值
  3415. * @method getStyle
  3416. * @param { Element } element 需要获取属性值的元素
  3417. * @param { String } styleName 需要获取的style的名称
  3418. * @warning 该方法仅获取元素style属性中所标明的值
  3419. * @return { String } 该元素包含指定的style属性值
  3420. * @example
  3421. * ```html
  3422. * <div id="test" style="color: red;"></div>
  3423. *
  3424. * <script>
  3425. *
  3426. * var testNode = document.getElementById( "test" );
  3427. *
  3428. * //output: red
  3429. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3430. *
  3431. * //output: ""
  3432. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3433. *
  3434. * </script>
  3435. * ```
  3436. */
  3437. getStyle:function (element, name) {
  3438. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3439. return utils.fixColor(name, value);
  3440. },
  3441. /**
  3442. * 为元素element设置样式属性值
  3443. * @method setStyle
  3444. * @param { Element } element 需要设置样式的元素
  3445. * @param { String } styleName 样式名
  3446. * @param { String } styleValue 样式值
  3447. * @example
  3448. * ```html
  3449. * <div id="test"></div>
  3450. *
  3451. * <script>
  3452. *
  3453. * var testNode = document.getElementById( "test" );
  3454. *
  3455. * //output: ""
  3456. * console.log( testNode.style.color );
  3457. *
  3458. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3459. * //output: "red"
  3460. * console.log( testNode.style.color );
  3461. *
  3462. * </script>
  3463. * ```
  3464. */
  3465. setStyle:function (element, name, value) {
  3466. element.style[utils.cssStyleToDomStyle(name)] = value;
  3467. if(!utils.trim(element.style.cssText)){
  3468. this.removeAttributes(element,'style')
  3469. }
  3470. },
  3471. /**
  3472. * 为元素element设置多个样式属性值
  3473. * @method setStyles
  3474. * @param { Element } element 需要设置样式的元素
  3475. * @param { Object } styles 样式名值对
  3476. * @example
  3477. * ```html
  3478. * <div id="test"></div>
  3479. *
  3480. * <script>
  3481. *
  3482. * var testNode = document.getElementById( "test" );
  3483. *
  3484. * //output: ""
  3485. * console.log( testNode.style.color );
  3486. *
  3487. * UE.dom.domUtils.setStyles( testNode, {
  3488. * 'color': 'red'
  3489. * } );
  3490. * //output: "red"
  3491. * console.log( testNode.style.color );
  3492. *
  3493. * </script>
  3494. * ```
  3495. */
  3496. setStyles:function (element, styles) {
  3497. for (var name in styles) {
  3498. if (styles.hasOwnProperty(name)) {
  3499. domUtils.setStyle(element, name, styles[name]);
  3500. }
  3501. }
  3502. },
  3503. /**
  3504. * 删除_moz_dirty属性
  3505. * @private
  3506. * @method removeDirtyAttr
  3507. */
  3508. removeDirtyAttr:function (node) {
  3509. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3510. ci.removeAttribute('_moz_dirty');
  3511. }
  3512. node.removeAttribute('_moz_dirty');
  3513. },
  3514. /**
  3515. * 获取子节点的数量
  3516. * @method getChildCount
  3517. * @param { Element } node 需要检测的元素
  3518. * @return { Number } 给定的node元素的子节点数量
  3519. * @example
  3520. * ```html
  3521. * <div id="test">
  3522. * <span></span>
  3523. * </div>
  3524. *
  3525. * <script>
  3526. *
  3527. * //output: 3
  3528. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3529. *
  3530. * </script>
  3531. * ```
  3532. */
  3533. /**
  3534. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3535. * @method getChildCount
  3536. * @param { Element } node 需要检测的元素
  3537. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3538. * @return { Number } 符合过滤条件的node元素的子节点数量
  3539. * @example
  3540. * ```html
  3541. * <div id="test">
  3542. * <span></span>
  3543. * </div>
  3544. *
  3545. * <script>
  3546. *
  3547. * //output: 1
  3548. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3549. *
  3550. * return node.nodeType === 1;
  3551. *
  3552. * } ) );
  3553. *
  3554. * </script>
  3555. * ```
  3556. */
  3557. getChildCount:function (node, fn) {
  3558. var count = 0, first = node.firstChild;
  3559. fn = fn || function () {
  3560. return 1;
  3561. };
  3562. while (first) {
  3563. if (fn(first)) {
  3564. count++;
  3565. }
  3566. first = first.nextSibling;
  3567. }
  3568. return count;
  3569. },
  3570. /**
  3571. * 判断给定节点是否为空节点
  3572. * @method isEmptyNode
  3573. * @param { Node } node 需要检测的节点对象
  3574. * @return { Boolean } 节点是否为空
  3575. * @example
  3576. * ```javascript
  3577. * UE.dom.domUtils.isEmptyNode( document.body );
  3578. * ```
  3579. */
  3580. isEmptyNode:function (node) {
  3581. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3582. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3583. }) == 0
  3584. },
  3585. clearSelectedArr:function (nodes) {
  3586. var node;
  3587. while (node = nodes.pop()) {
  3588. domUtils.removeAttributes(node, ['class']);
  3589. }
  3590. },
  3591. /**
  3592. * 将显示区域滚动到指定节点的位置
  3593. * @method scrollToView
  3594. * @param {Node} node 节点
  3595. * @param {window} win window对象
  3596. * @param {Number} offsetTop 距离上方的偏移量
  3597. */
  3598. scrollToView:function (node, win, offsetTop) {
  3599. var getViewPaneSize = function () {
  3600. var doc = win.document,
  3601. mode = doc.compatMode == 'CSS1Compat';
  3602. return {
  3603. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3604. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3605. };
  3606. },
  3607. getScrollPosition = function (win) {
  3608. if ('pageXOffset' in win) {
  3609. return {
  3610. x:win.pageXOffset || 0,
  3611. y:win.pageYOffset || 0
  3612. };
  3613. }
  3614. else {
  3615. var doc = win.document;
  3616. return {
  3617. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3618. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3619. };
  3620. }
  3621. };
  3622. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3623. offset += (node.offsetHeight || 0);
  3624. var elementPosition = domUtils.getXY(node);
  3625. offset += elementPosition.y;
  3626. var currentScroll = getScrollPosition(win).y;
  3627. // offset += 50;
  3628. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3629. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3630. }
  3631. },
  3632. /**
  3633. * 判断给定节点是否为br
  3634. * @method isBr
  3635. * @param { Node } node 需要判断的节点对象
  3636. * @return { Boolean } 给定的节点是否是br节点
  3637. */
  3638. isBr:function (node) {
  3639. return node.nodeType == 1 && node.tagName == 'BR';
  3640. },
  3641. /**
  3642. * 判断给定的节点是否是一个“填充”节点
  3643. * @private
  3644. * @method isFillChar
  3645. * @param { Node } node 需要判断的节点
  3646. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3647. * @returns { Boolean } 节点是否是填充节点
  3648. */
  3649. isFillChar:function (node,isInStart) {
  3650. if(node.nodeType != 3)
  3651. return false;
  3652. var text = node.nodeValue;
  3653. if(isInStart){
  3654. return new RegExp('^' + domUtils.fillChar).test(text)
  3655. }
  3656. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3657. },
  3658. isStartInblock:function (range) {
  3659. var tmpRange = range.cloneRange(),
  3660. flag = 0,
  3661. start = tmpRange.startContainer,
  3662. tmp;
  3663. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3664. start = start.childNodes[tmpRange.startOffset];
  3665. var pre = start.previousSibling;
  3666. while(pre && domUtils.isFillChar(pre)){
  3667. start = pre;
  3668. pre = pre.previousSibling;
  3669. }
  3670. }
  3671. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3672. tmpRange.setStartBefore(start);
  3673. start = tmpRange.startContainer;
  3674. }
  3675. while (start && domUtils.isFillChar(start)) {
  3676. tmp = start;
  3677. start = start.previousSibling
  3678. }
  3679. if (tmp) {
  3680. tmpRange.setStartBefore(tmp);
  3681. start = tmpRange.startContainer;
  3682. }
  3683. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3684. tmpRange.setStart(start, 0).collapse(true);
  3685. }
  3686. while (!tmpRange.startOffset) {
  3687. start = tmpRange.startContainer;
  3688. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3689. flag = 1;
  3690. break;
  3691. }
  3692. var pre = tmpRange.startContainer.previousSibling,
  3693. tmpNode;
  3694. if (!pre) {
  3695. tmpRange.setStartBefore(tmpRange.startContainer);
  3696. } else {
  3697. while (pre && domUtils.isFillChar(pre)) {
  3698. tmpNode = pre;
  3699. pre = pre.previousSibling;
  3700. }
  3701. if (tmpNode) {
  3702. tmpRange.setStartBefore(tmpNode);
  3703. } else {
  3704. tmpRange.setStartBefore(tmpRange.startContainer);
  3705. }
  3706. }
  3707. }
  3708. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3709. },
  3710. /**
  3711. * 判断给定的元素是否是一个空元素
  3712. * @method isEmptyBlock
  3713. * @param { Element } node 需要判断的元素
  3714. * @return { Boolean } 是否是空元素
  3715. * @example
  3716. * ```html
  3717. * <div id="test"></div>
  3718. *
  3719. * <script>
  3720. * //output: true
  3721. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3722. * </script>
  3723. * ```
  3724. */
  3725. /**
  3726. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3727. * @method isEmptyBlock
  3728. * @param { Element } node 需要判断的元素
  3729. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3730. * @return { Boolean } 是否是空元素
  3731. */
  3732. isEmptyBlock:function (node,reg) {
  3733. if(node.nodeType != 1)
  3734. return 0;
  3735. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3736. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3737. return 0;
  3738. }
  3739. for (var n in dtd.$isNotEmpty) {
  3740. if (node.getElementsByTagName(n).length) {
  3741. return 0;
  3742. }
  3743. }
  3744. return 1;
  3745. },
  3746. /**
  3747. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3748. * @method setViewportOffset
  3749. * @param { Element } element 需要设置偏移量的元素
  3750. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3751. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3752. * offset.top的距离
  3753. * @example
  3754. * ```html
  3755. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3756. *
  3757. * <script>
  3758. *
  3759. * var testNode = document.getElementById("test");
  3760. *
  3761. * UE.dom.domUtils.setViewportOffset( testNode, {
  3762. * left: 200,
  3763. * top: 50
  3764. * } );
  3765. *
  3766. * //output: top: 300px; left: 100px; position: absolute;
  3767. * console.log( testNode.style.cssText );
  3768. *
  3769. * </script>
  3770. * ```
  3771. */
  3772. setViewportOffset:function (element, offset) {
  3773. var left = parseInt(element.style.left) | 0;
  3774. var top = parseInt(element.style.top) | 0;
  3775. var rect = element.getBoundingClientRect();
  3776. var offsetLeft = offset.left - rect.left;
  3777. var offsetTop = offset.top - rect.top;
  3778. if (offsetLeft) {
  3779. element.style.left = left + offsetLeft + 'px';
  3780. }
  3781. if (offsetTop) {
  3782. element.style.top = top + offsetTop + 'px';
  3783. }
  3784. },
  3785. /**
  3786. * 用“填充字符”填充节点
  3787. * @method fillNode
  3788. * @private
  3789. * @param { DomDocument } doc 填充的节点所在的docment对象
  3790. * @param { Node } node 需要填充的节点对象
  3791. * @example
  3792. * ```html
  3793. * <div id="test"></div>
  3794. *
  3795. * <script>
  3796. * var testNode = document.getElementById("test");
  3797. *
  3798. * //output: 0
  3799. * console.log( testNode.childNodes.length );
  3800. *
  3801. * UE.dom.domUtils.fillNode( document, testNode );
  3802. *
  3803. * //output: 1
  3804. * console.log( testNode.childNodes.length );
  3805. *
  3806. * </script>
  3807. * ```
  3808. */
  3809. fillNode:function (doc, node) {
  3810. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3811. node.innerHTML = '';
  3812. node.appendChild(tmpNode);
  3813. },
  3814. /**
  3815. * 把节点src的所有子节点追加到另一个节点tag上去
  3816. * @method moveChild
  3817. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3818. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3819. * @example
  3820. * ```html
  3821. * <div id="test1">
  3822. * <span></span>
  3823. * </div>
  3824. * <div id="test2">
  3825. * <div></div>
  3826. * </div>
  3827. *
  3828. * <script>
  3829. *
  3830. * var test1 = document.getElementById("test1"),
  3831. * test2 = document.getElementById("test2");
  3832. *
  3833. * UE.dom.domUtils.moveChild( test1, test2 );
  3834. *
  3835. * //output: ""(空字符串)
  3836. * console.log( test1.innerHTML );
  3837. *
  3838. * //output: "<div></div><span></span>"
  3839. * console.log( test2.innerHTML );
  3840. *
  3841. * </script>
  3842. * ```
  3843. */
  3844. /**
  3845. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3846. * @method moveChild
  3847. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3848. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3849. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3850. * @example
  3851. * ```html
  3852. * <div id="test1">
  3853. * <span></span>
  3854. * </div>
  3855. * <div id="test2">
  3856. * <div></div>
  3857. * </div>
  3858. *
  3859. * <script>
  3860. *
  3861. * var test1 = document.getElementById("test1"),
  3862. * test2 = document.getElementById("test2");
  3863. *
  3864. * UE.dom.domUtils.moveChild( test1, test2, true );
  3865. *
  3866. * //output: ""(空字符串)
  3867. * console.log( test1.innerHTML );
  3868. *
  3869. * //output: "<span></span><div></div>"
  3870. * console.log( test2.innerHTML );
  3871. *
  3872. * </script>
  3873. * ```
  3874. */
  3875. moveChild:function (src, tag, dir) {
  3876. while (src.firstChild) {
  3877. if (dir && tag.firstChild) {
  3878. tag.insertBefore(src.lastChild, tag.firstChild);
  3879. } else {
  3880. tag.appendChild(src.firstChild);
  3881. }
  3882. }
  3883. },
  3884. /**
  3885. * 判断节点的标签上是否不存在任何属性
  3886. * @method hasNoAttributes
  3887. * @private
  3888. * @param { Node } node 需要检测的节点对象
  3889. * @return { Boolean } 节点是否不包含任何属性
  3890. * @example
  3891. * ```html
  3892. * <div id="test"><span>xxxx</span></div>
  3893. *
  3894. * <script>
  3895. *
  3896. * //output: false
  3897. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3898. *
  3899. * //output: true
  3900. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3901. *
  3902. * </script>
  3903. * ```
  3904. */
  3905. hasNoAttributes:function (node) {
  3906. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3907. },
  3908. /**
  3909. * 检测节点是否是UEditor所使用的辅助节点
  3910. * @method isCustomeNode
  3911. * @private
  3912. * @param { Node } node 需要检测的节点
  3913. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3914. * @return { Boolean } 给定的节点是否是一个辅助节点
  3915. */
  3916. isCustomeNode:function (node) {
  3917. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3918. },
  3919. /**
  3920. * 检测节点的标签是否是给定的标签
  3921. * @method isTagNode
  3922. * @param { Node } node 需要检测的节点对象
  3923. * @param { String } tagName 标签
  3924. * @return { Boolean } 节点的标签是否是给定的标签
  3925. * @example
  3926. * ```html
  3927. * <div id="test"></div>
  3928. *
  3929. * <script>
  3930. *
  3931. * //output: true
  3932. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3933. *
  3934. * </script>
  3935. * ```
  3936. */
  3937. isTagNode:function (node, tagNames) {
  3938. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3939. },
  3940. /**
  3941. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3942. * @method filterNodeList
  3943. * @param { Array } nodeList 需要过滤的节点数组
  3944. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3945. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3946. * @example
  3947. * ```javascript
  3948. * var divNodes = document.getElementsByTagName("div");
  3949. * divNodes = [].slice.call( divNodes, 0 );
  3950. *
  3951. * //output: null
  3952. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3953. * return node.tagName.toLowerCase() !== 'div';
  3954. * } ) );
  3955. * ```
  3956. */
  3957. /**
  3958. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3959. * @method filterNodeList
  3960. * @param { Array } nodeList 需要过滤的节点数组
  3961. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3962. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3963. * @example
  3964. * ```javascript
  3965. * var divNodes = document.getElementsByTagName("div");
  3966. * divNodes = [].slice.call( divNodes, 0 );
  3967. *
  3968. * //output: null
  3969. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3970. * ```
  3971. */
  3972. /**
  3973. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3974. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3975. * @method filterNodeList
  3976. * @param { Array } nodeList 需要过滤的节点数组
  3977. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3978. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3979. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3980. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3981. * @example
  3982. * ```javascript
  3983. * var divNodes = document.getElementsByTagName("div");
  3984. * divNodes = [].slice.call( divNodes, 0 );
  3985. *
  3986. * //output: 3(假定有3个div)
  3987. * console.log( divNodes.length );
  3988. *
  3989. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3990. * return node.tagName.toLowerCase() === 'div';
  3991. * }, true );
  3992. *
  3993. * //output: 3
  3994. * console.log( nodes.length );
  3995. *
  3996. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3997. * return node.tagName.toLowerCase() === 'div';
  3998. * }, false );
  3999. *
  4000. * //output: div
  4001. * console.log( node.nodeName );
  4002. * ```
  4003. */
  4004. filterNodeList : function(nodelist,filter,forAll){
  4005. var results = [];
  4006. if(!utils .isFunction(filter)){
  4007. var str = filter;
  4008. filter = function(n){
  4009. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4010. };
  4011. }
  4012. utils.each(nodelist,function(n){
  4013. filter(n) && results.push(n)
  4014. });
  4015. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4016. },
  4017. /**
  4018. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4019. * @method isInNodeEndBoundary
  4020. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4021. * @param node 需要检测的节点对象
  4022. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4023. */
  4024. isInNodeEndBoundary : function (rng,node){
  4025. var start = rng.startContainer;
  4026. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4027. return 0;
  4028. }
  4029. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4030. return 0;
  4031. }
  4032. while(start !== node){
  4033. if(start.nextSibling){
  4034. return 0
  4035. };
  4036. start = start.parentNode;
  4037. }
  4038. return 1;
  4039. },
  4040. isBoundaryNode : function (node,dir){
  4041. var tmp;
  4042. while(!domUtils.isBody(node)){
  4043. tmp = node;
  4044. node = node.parentNode;
  4045. if(tmp !== node[dir]){
  4046. return false;
  4047. }
  4048. }
  4049. return true;
  4050. },
  4051. fillHtml : browser.ie11below ? '&nbsp;' : '<br/>'
  4052. };
  4053. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4054. // core/Range.js
  4055. /**
  4056. * Range封装
  4057. * @file
  4058. * @module UE.dom
  4059. * @class Range
  4060. * @since 1.2.6.1
  4061. */
  4062. /**
  4063. * dom操作封装
  4064. * @unfile
  4065. * @module UE.dom
  4066. */
  4067. /**
  4068. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4069. * @unfile
  4070. * @module UE.dom
  4071. * @class Range
  4072. */
  4073. (function () {
  4074. var guid = 0,
  4075. fillChar = domUtils.fillChar,
  4076. fillData;
  4077. /**
  4078. * 更新range的collapse状态
  4079. * @param {Range} range range对象
  4080. */
  4081. function updateCollapse(range) {
  4082. range.collapsed =
  4083. range.startContainer && range.endContainer &&
  4084. range.startContainer === range.endContainer &&
  4085. range.startOffset == range.endOffset;
  4086. }
  4087. function selectOneNode(rng){
  4088. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4089. }
  4090. function setEndPoint(toStart, node, offset, range) {
  4091. //如果node是自闭合标签要处理
  4092. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4093. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4094. node = node.parentNode;
  4095. }
  4096. if (toStart) {
  4097. range.startContainer = node;
  4098. range.startOffset = offset;
  4099. if (!range.endContainer) {
  4100. range.collapse(true);
  4101. }
  4102. } else {
  4103. range.endContainer = node;
  4104. range.endOffset = offset;
  4105. if (!range.startContainer) {
  4106. range.collapse(false);
  4107. }
  4108. }
  4109. updateCollapse(range);
  4110. return range;
  4111. }
  4112. function execContentsAction(range, action) {
  4113. //调整边界
  4114. //range.includeBookmark();
  4115. var start = range.startContainer,
  4116. end = range.endContainer,
  4117. startOffset = range.startOffset,
  4118. endOffset = range.endOffset,
  4119. doc = range.document,
  4120. frag = doc.createDocumentFragment(),
  4121. tmpStart, tmpEnd;
  4122. if (start.nodeType == 1) {
  4123. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4124. }
  4125. if (end.nodeType == 1) {
  4126. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4127. }
  4128. if (start === end && start.nodeType == 3) {
  4129. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4130. //is not clone
  4131. if (action) {
  4132. start.deleteData(startOffset, endOffset - startOffset);
  4133. range.collapse(true);
  4134. }
  4135. return frag;
  4136. }
  4137. var current, currentLevel, clone = frag,
  4138. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4139. for (var i = 0; startParents[i] == endParents[i];) {
  4140. i++;
  4141. }
  4142. for (var j = i, si; si = startParents[j]; j++) {
  4143. current = si.nextSibling;
  4144. if (si == start) {
  4145. if (!tmpStart) {
  4146. if (range.startContainer.nodeType == 3) {
  4147. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4148. //is not clone
  4149. if (action) {
  4150. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4151. }
  4152. } else {
  4153. clone.appendChild(!action ? start.cloneNode(true) : start);
  4154. }
  4155. }
  4156. } else {
  4157. currentLevel = si.cloneNode(false);
  4158. clone.appendChild(currentLevel);
  4159. }
  4160. while (current) {
  4161. if (current === end || current === endParents[j]) {
  4162. break;
  4163. }
  4164. si = current.nextSibling;
  4165. clone.appendChild(!action ? current.cloneNode(true) : current);
  4166. current = si;
  4167. }
  4168. clone = currentLevel;
  4169. }
  4170. clone = frag;
  4171. if (!startParents[i]) {
  4172. clone.appendChild(startParents[i - 1].cloneNode(false));
  4173. clone = clone.firstChild;
  4174. }
  4175. for (var j = i, ei; ei = endParents[j]; j++) {
  4176. current = ei.previousSibling;
  4177. if (ei == end) {
  4178. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4179. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4180. //is not clone
  4181. if (action) {
  4182. end.deleteData(0, endOffset);
  4183. }
  4184. }
  4185. } else {
  4186. currentLevel = ei.cloneNode(false);
  4187. clone.appendChild(currentLevel);
  4188. }
  4189. //如果两端同级,右边第一次已经被开始做了
  4190. if (j != i || !startParents[i]) {
  4191. while (current) {
  4192. if (current === start) {
  4193. break;
  4194. }
  4195. ei = current.previousSibling;
  4196. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4197. current = ei;
  4198. }
  4199. }
  4200. clone = currentLevel;
  4201. }
  4202. if (action) {
  4203. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4204. }
  4205. tmpStart && domUtils.remove(tmpStart);
  4206. tmpEnd && domUtils.remove(tmpEnd);
  4207. return frag;
  4208. }
  4209. /**
  4210. * 创建一个跟document绑定的空的Range实例
  4211. * @constructor
  4212. * @param { Document } document 新建的选区所属的文档对象
  4213. */
  4214. /**
  4215. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4216. */
  4217. /**
  4218. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4219. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4220. */
  4221. /**
  4222. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4223. */
  4224. /**
  4225. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4226. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4227. */
  4228. /**
  4229. * @property { Boolean } collapsed 当前Range是否闭合
  4230. * @default true
  4231. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4232. */
  4233. /**
  4234. * @property { Document } document 当前Range所属的Document对象
  4235. * @remind 不同range的的document属性可以是不同的
  4236. */
  4237. var Range = dom.Range = function (document) {
  4238. var me = this;
  4239. me.startContainer =
  4240. me.startOffset =
  4241. me.endContainer =
  4242. me.endOffset = null;
  4243. me.document = document;
  4244. me.collapsed = true;
  4245. };
  4246. /**
  4247. * 删除fillData
  4248. * @param doc
  4249. * @param excludeNode
  4250. */
  4251. function removeFillData(doc, excludeNode) {
  4252. try {
  4253. if (fillData && domUtils.inDoc(fillData, doc)) {
  4254. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4255. var tmpNode = fillData.parentNode;
  4256. domUtils.remove(fillData);
  4257. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4258. //safari的contains有bug
  4259. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4260. ) {
  4261. fillData = tmpNode.parentNode;
  4262. domUtils.remove(tmpNode);
  4263. tmpNode = fillData;
  4264. }
  4265. } else {
  4266. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4267. }
  4268. }
  4269. } catch (e) {
  4270. }
  4271. }
  4272. /**
  4273. * @param node
  4274. * @param dir
  4275. */
  4276. function mergeSibling(node, dir) {
  4277. var tmpNode;
  4278. node = node[dir];
  4279. while (node && domUtils.isFillChar(node)) {
  4280. tmpNode = node[dir];
  4281. domUtils.remove(node);
  4282. node = tmpNode;
  4283. }
  4284. }
  4285. Range.prototype = {
  4286. /**
  4287. * 克隆选区的内容到一个DocumentFragment里
  4288. * @method cloneContents
  4289. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4290. * @example
  4291. * ```html
  4292. * <body>
  4293. * <!-- 中括号表示选区 -->
  4294. * <b>x<i>x[x</i>xx]x</b>
  4295. *
  4296. * <script>
  4297. * //range是已选中的选区
  4298. * var fragment = range.cloneContents(),
  4299. * node = document.createElement("div");
  4300. *
  4301. * node.appendChild( fragment );
  4302. *
  4303. * //output: <i>x</i>xx
  4304. * console.log( node.innerHTML );
  4305. *
  4306. * </script>
  4307. * </body>
  4308. * ```
  4309. */
  4310. cloneContents:function () {
  4311. return this.collapsed ? null : execContentsAction(this, 0);
  4312. },
  4313. /**
  4314. * 删除当前选区范围中的所有内容
  4315. * @method deleteContents
  4316. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4317. * @return { UE.dom.Range } 当前操作的Range对象
  4318. * @example
  4319. * ```html
  4320. * <body>
  4321. * <!-- 中括号表示选区 -->
  4322. * <b>x<i>x[x</i>xx]x</b>
  4323. *
  4324. * <script>
  4325. * //range是已选中的选区
  4326. * range.deleteContents();
  4327. *
  4328. * //竖线表示闭合后的选区位置
  4329. * //output: <b>x<i>x</i>|x</b>
  4330. * console.log( document.body.innerHTML );
  4331. *
  4332. * //此时, range的各项属性为
  4333. * //output: B
  4334. * console.log( range.startContainer.tagName );
  4335. * //output: 2
  4336. * console.log( range.startOffset );
  4337. * //output: B
  4338. * console.log( range.endContainer.tagName );
  4339. * //output: 2
  4340. * console.log( range.endOffset );
  4341. * //output: true
  4342. * console.log( range.collapsed );
  4343. *
  4344. * </script>
  4345. * </body>
  4346. * ```
  4347. */
  4348. deleteContents:function () {
  4349. var txt;
  4350. if (!this.collapsed) {
  4351. execContentsAction(this, 1);
  4352. }
  4353. if (browser.webkit) {
  4354. txt = this.startContainer;
  4355. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4356. this.setStartBefore(txt).collapse(true);
  4357. domUtils.remove(txt);
  4358. }
  4359. }
  4360. return this;
  4361. },
  4362. /**
  4363. * 将当前选区的内容提取到一个DocumentFragment里
  4364. * @method extractContents
  4365. * @remind 执行该操作后, 选区将变成闭合状态
  4366. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4367. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4368. * @example
  4369. * ```html
  4370. * <body>
  4371. * <!-- 中括号表示选区 -->
  4372. * <b>x<i>x[x</i>xx]x</b>
  4373. *
  4374. * <script>
  4375. * //range是已选中的选区
  4376. * var fragment = range.extractContents(),
  4377. * node = document.createElement( "div" );
  4378. *
  4379. * node.appendChild( fragment );
  4380. *
  4381. * //竖线表示闭合后的选区位置
  4382. *
  4383. * //output: <b>x<i>x</i>|x</b>
  4384. * console.log( document.body.innerHTML );
  4385. * //output: <i>x</i>xx
  4386. * console.log( node.innerHTML );
  4387. *
  4388. * //此时, range的各项属性为
  4389. * //output: B
  4390. * console.log( range.startContainer.tagName );
  4391. * //output: 2
  4392. * console.log( range.startOffset );
  4393. * //output: B
  4394. * console.log( range.endContainer.tagName );
  4395. * //output: 2
  4396. * console.log( range.endOffset );
  4397. * //output: true
  4398. * console.log( range.collapsed );
  4399. *
  4400. * </script>
  4401. * </body>
  4402. */
  4403. extractContents:function () {
  4404. return this.collapsed ? null : execContentsAction(this, 2);
  4405. },
  4406. /**
  4407. * 设置Range的开始容器节点和偏移量
  4408. * @method setStart
  4409. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4410. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4411. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4412. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4413. * 中的索引
  4414. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4415. * @param { int } offset 选区的开始位置偏移量
  4416. * @return { UE.dom.Range } 当前range对象
  4417. * @example
  4418. * ```html
  4419. * <!-- 选区 -->
  4420. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4421. *
  4422. * <script>
  4423. *
  4424. * //执行操作
  4425. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4426. *
  4427. * //此时, 选区变成了
  4428. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4429. *
  4430. * </script>
  4431. * ```
  4432. * @example
  4433. * ```html
  4434. * <!-- 选区 -->
  4435. * <b>xxx<img>[xx]x</b>
  4436. *
  4437. * <script>
  4438. *
  4439. * //执行操作
  4440. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4441. *
  4442. * //此时, 选区变成了
  4443. * //<b>xxx[<img>xx]x</b>
  4444. *
  4445. * </script>
  4446. * ```
  4447. */
  4448. setStart:function (node, offset) {
  4449. return setEndPoint(true, node, offset, this);
  4450. },
  4451. /**
  4452. * 设置Range的结束容器和偏移量
  4453. * @method setEnd
  4454. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4455. * @param { int } offset 结束边界的偏移量
  4456. * @see UE.dom.Range:setStart(Node,int)
  4457. * @return { UE.dom.Range } 当前range对象
  4458. */
  4459. setEnd:function (node, offset) {
  4460. return setEndPoint(false, node, offset, this);
  4461. },
  4462. /**
  4463. * 将Range开始位置设置到node节点之后
  4464. * @method setStartAfter
  4465. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4466. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4467. * @return { UE.dom.Range } 当前range对象
  4468. * @example
  4469. * ```html
  4470. * <!-- 选区示例 -->
  4471. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4472. *
  4473. * <script>
  4474. *
  4475. * //执行操作
  4476. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4477. *
  4478. * //结果选区
  4479. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4480. *
  4481. * </script>
  4482. * ```
  4483. */
  4484. setStartAfter:function (node) {
  4485. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4486. },
  4487. /**
  4488. * 将Range开始位置设置到node节点之前
  4489. * @method setStartBefore
  4490. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4491. * @param { Node } node 新的选区开始位置在该节点之前
  4492. * @see UE.dom.Range:setStartAfter(Node)
  4493. * @return { UE.dom.Range } 当前range对象
  4494. */
  4495. setStartBefore:function (node) {
  4496. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4497. },
  4498. /**
  4499. * 将Range结束位置设置到node节点之后
  4500. * @method setEndAfter
  4501. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4502. * @param { Node } node 目标节点
  4503. * @see UE.dom.Range:setStartAfter(Node)
  4504. * @return { UE.dom.Range } 当前range对象
  4505. * @example
  4506. * ```html
  4507. * <!-- 选区示例 -->
  4508. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4509. *
  4510. * <script>
  4511. *
  4512. * //执行操作
  4513. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4514. *
  4515. * //结果选区
  4516. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4517. *
  4518. * </script>
  4519. * ```
  4520. */
  4521. setEndAfter:function (node) {
  4522. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4523. },
  4524. /**
  4525. * 将Range结束位置设置到node节点之前
  4526. * @method setEndBefore
  4527. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4528. * @param { Node } node 目标节点
  4529. * @see UE.dom.Range:setEndAfter(Node)
  4530. * @return { UE.dom.Range } 当前range对象
  4531. */
  4532. setEndBefore:function (node) {
  4533. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4534. },
  4535. /**
  4536. * 设置Range的开始位置到node节点内的第一个子节点之前
  4537. * @method setStartAtFirst
  4538. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4539. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4540. * @param { Node } node 目标节点
  4541. * @see UE.dom.Range:setStartBefore(Node)
  4542. * @return { UE.dom.Range } 当前range对象
  4543. * @example
  4544. * ```html
  4545. * <!-- 选区示例 -->
  4546. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4547. *
  4548. * <script>
  4549. *
  4550. * //执行操作
  4551. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4552. *
  4553. * //结果选区
  4554. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4555. *
  4556. * </script>
  4557. * ```
  4558. */
  4559. setStartAtFirst:function (node) {
  4560. return this.setStart(node, 0);
  4561. },
  4562. /**
  4563. * 设置Range的开始位置到node节点内的最后一个节点之后
  4564. * @method setStartAtLast
  4565. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4566. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4567. * @param { Node } node 目标节点
  4568. * @see UE.dom.Range:setStartAtFirst(Node)
  4569. * @return { UE.dom.Range } 当前range对象
  4570. */
  4571. setStartAtLast:function (node) {
  4572. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4573. },
  4574. /**
  4575. * 设置Range的结束位置到node节点内的第一个节点之前
  4576. * @method setEndAtFirst
  4577. * @param { Node } node 目标节点
  4578. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4579. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4580. * @see UE.dom.Range:setStartAtFirst(Node)
  4581. * @return { UE.dom.Range } 当前range对象
  4582. */
  4583. setEndAtFirst:function (node) {
  4584. return this.setEnd(node, 0);
  4585. },
  4586. /**
  4587. * 设置Range的结束位置到node节点内的最后一个节点之后
  4588. * @method setEndAtLast
  4589. * @param { Node } node 目标节点
  4590. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4591. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4592. * @see UE.dom.Range:setStartAtFirst(Node)
  4593. * @return { UE.dom.Range } 当前range对象
  4594. */
  4595. setEndAtLast:function (node) {
  4596. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4597. },
  4598. /**
  4599. * 选中给定节点
  4600. * @method selectNode
  4601. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4602. * 而endOffset为startOffset+1
  4603. * @param { Node } node 需要选中的节点
  4604. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4605. * @example
  4606. * ```html
  4607. * <!-- 选区示例 -->
  4608. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4609. *
  4610. * <script>
  4611. *
  4612. * //执行操作
  4613. * range.selectNode( document.getElementsByTagName("i")[0] );
  4614. *
  4615. * //结果选区
  4616. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4617. *
  4618. * </script>
  4619. * ```
  4620. */
  4621. selectNode:function (node) {
  4622. return this.setStartBefore(node).setEndAfter(node);
  4623. },
  4624. /**
  4625. * 选中给定节点内部的所有节点
  4626. * @method selectNodeContents
  4627. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4628. * 而endOffset是该节点的子节点数。
  4629. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4630. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4631. * @example
  4632. * ```html
  4633. * <!-- 选区示例 -->
  4634. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4635. *
  4636. * <script>
  4637. *
  4638. * //执行操作
  4639. * range.selectNode( document.getElementsByTagName("b")[0] );
  4640. *
  4641. * //结果选区
  4642. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4643. *
  4644. * </script>
  4645. * ```
  4646. */
  4647. selectNodeContents:function (node) {
  4648. return this.setStart(node, 0).setEndAtLast(node);
  4649. },
  4650. /**
  4651. * clone当前Range对象
  4652. * @method cloneRange
  4653. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4654. * @return { UE.dom.Range } 当前range对象的一个副本
  4655. */
  4656. cloneRange:function () {
  4657. var me = this;
  4658. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4659. },
  4660. /**
  4661. * 向当前选区的结束处闭合选区
  4662. * @method collapse
  4663. * @return { UE.dom.Range } 当前range对象
  4664. * @example
  4665. * ```html
  4666. * <!-- 选区示例 -->
  4667. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4668. *
  4669. * <script>
  4670. *
  4671. * //执行操作
  4672. * range.collapse();
  4673. *
  4674. * //结果选区
  4675. * //“|”表示选区已闭合
  4676. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4677. *
  4678. * </script>
  4679. * ```
  4680. */
  4681. /**
  4682. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4683. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4684. * @method collapse
  4685. * @param { Boolean } toStart 是否向选区开始处闭合
  4686. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4687. * @see UE.dom.Range:collapse()
  4688. * @example
  4689. * ```html
  4690. * <!-- 选区示例 -->
  4691. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4692. *
  4693. * <script>
  4694. *
  4695. * //执行操作
  4696. * range.collapse( true );
  4697. *
  4698. * //结果选区
  4699. * //“|”表示选区已闭合
  4700. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4701. *
  4702. * </script>
  4703. * ```
  4704. */
  4705. collapse:function (toStart) {
  4706. var me = this;
  4707. if (toStart) {
  4708. me.endContainer = me.startContainer;
  4709. me.endOffset = me.startOffset;
  4710. } else {
  4711. me.startContainer = me.endContainer;
  4712. me.startOffset = me.endOffset;
  4713. }
  4714. me.collapsed = true;
  4715. return me;
  4716. },
  4717. /**
  4718. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4719. * @method shrinkBoundary
  4720. * @return { UE.dom.Range } 当前range对象
  4721. * @example
  4722. * ```html
  4723. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4724. * ```
  4725. *
  4726. * @example
  4727. * ```html
  4728. * <!-- 选区示例 -->
  4729. * <b>x[xx</b><i>]xxx</i>
  4730. *
  4731. * <script>
  4732. *
  4733. * //执行收缩
  4734. * range.shrinkBoundary();
  4735. *
  4736. * //结果选区
  4737. * //<b>x[xx]</b><i>xxx</i>
  4738. * </script>
  4739. * ```
  4740. *
  4741. * @example
  4742. * ```html
  4743. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4744. * ```
  4745. */
  4746. /**
  4747. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4748. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4749. * @method shrinkBoundary
  4750. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4751. * @return { UE.dom.Range } 当前range对象
  4752. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4753. */
  4754. shrinkBoundary:function (ignoreEnd) {
  4755. var me = this, child,
  4756. collapsed = me.collapsed;
  4757. function check(node){
  4758. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4759. }
  4760. while (me.startContainer.nodeType == 1 //是element
  4761. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4762. && check(child)) {
  4763. me.setStart(child, 0);
  4764. }
  4765. if (collapsed) {
  4766. return me.collapse(true);
  4767. }
  4768. if (!ignoreEnd) {
  4769. while (me.endContainer.nodeType == 1//是element
  4770. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4771. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4772. && check(child)) {
  4773. me.setEnd(child, child.childNodes.length);
  4774. }
  4775. }
  4776. return me;
  4777. },
  4778. /**
  4779. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4780. * @method getCommonAncestor
  4781. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4782. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4783. * @example
  4784. * ```html
  4785. * //选区示例
  4786. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4787. * <script>
  4788. *
  4789. * var node = range.getCommonAncestor();
  4790. *
  4791. * //公共祖先节点是: b节点
  4792. * //输出: B
  4793. * console.log(node.tagName);
  4794. *
  4795. * </script>
  4796. * ```
  4797. */
  4798. /**
  4799. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4800. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4801. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4802. * @method getCommonAncestor
  4803. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4804. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4805. * @see UE.dom.Range:getCommonAncestor()
  4806. * @example
  4807. * ```html
  4808. * <body>
  4809. *
  4810. * <!-- 选区示例 -->
  4811. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4812. *
  4813. * <script>
  4814. *
  4815. * var node = range.getCommonAncestor( false );
  4816. *
  4817. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4818. * //output: B
  4819. * console.log( node.tagName );
  4820. *
  4821. * </script>
  4822. *
  4823. * </body>
  4824. * ```
  4825. */
  4826. /**
  4827. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4828. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4829. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4830. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4831. * @method getCommonAncestor
  4832. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4833. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4834. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4835. * @see UE.dom.Range:getCommonAncestor()
  4836. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4837. * @example
  4838. * ```html
  4839. * <body>
  4840. *
  4841. * <!-- 选区示例 -->
  4842. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4843. *
  4844. * <script>
  4845. *
  4846. * var node = range.getCommonAncestor( true, false );
  4847. *
  4848. * //output: SPAN
  4849. * console.log( node.tagName );
  4850. *
  4851. * </script>
  4852. *
  4853. * </body>
  4854. * ```
  4855. */
  4856. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4857. var me = this,
  4858. start = me.startContainer,
  4859. end = me.endContainer;
  4860. if (start === end) {
  4861. if (includeSelf && selectOneNode(this)) {
  4862. start = start.childNodes[me.startOffset];
  4863. if(start.nodeType == 1)
  4864. return start;
  4865. }
  4866. //只有在上来就相等的情况下才会出现是文本的情况
  4867. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4868. }
  4869. return domUtils.getCommonAncestor(start, end);
  4870. },
  4871. /**
  4872. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4873. * @method trimBoundary
  4874. * @remind 该操作有可能会引起文本节点被切开
  4875. * @return { UE.dom.Range } 当前range对象
  4876. * @example
  4877. * ```html
  4878. *
  4879. * //选区示例
  4880. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4881. *
  4882. * <script>
  4883. * //未调整前, 选区的开始容器和结束都是文本节点
  4884. * //执行调整
  4885. * range.trimBoundary();
  4886. *
  4887. * //调整之后, 容器节点变成了i节点
  4888. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4889. * </script>
  4890. * ```
  4891. */
  4892. /**
  4893. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4894. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4895. * @method trimBoundary
  4896. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4897. * @return { UE.dom.Range } 当前range对象
  4898. * @example
  4899. * ```html
  4900. *
  4901. * //选区示例
  4902. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4903. *
  4904. * <script>
  4905. * //未调整前, 选区的开始容器和结束都是文本节点
  4906. * //执行调整
  4907. * range.trimBoundary( true );
  4908. *
  4909. * //调整之后, 开始容器节点变成了i节点
  4910. * //但是, 结束容器没有发生变化
  4911. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4912. * </script>
  4913. * ```
  4914. */
  4915. trimBoundary:function (ignoreEnd) {
  4916. this.txtToElmBoundary();
  4917. var start = this.startContainer,
  4918. offset = this.startOffset,
  4919. collapsed = this.collapsed,
  4920. end = this.endContainer;
  4921. if (start.nodeType == 3) {
  4922. if (offset == 0) {
  4923. this.setStartBefore(start);
  4924. } else {
  4925. if (offset >= start.nodeValue.length) {
  4926. this.setStartAfter(start);
  4927. } else {
  4928. var textNode = domUtils.split(start, offset);
  4929. //跟新结束边界
  4930. if (start === end) {
  4931. this.setEnd(textNode, this.endOffset - offset);
  4932. } else if (start.parentNode === end) {
  4933. this.endOffset += 1;
  4934. }
  4935. this.setStartBefore(textNode);
  4936. }
  4937. }
  4938. if (collapsed) {
  4939. return this.collapse(true);
  4940. }
  4941. }
  4942. if (!ignoreEnd) {
  4943. offset = this.endOffset;
  4944. end = this.endContainer;
  4945. if (end.nodeType == 3) {
  4946. if (offset == 0) {
  4947. this.setEndBefore(end);
  4948. } else {
  4949. offset < end.nodeValue.length && domUtils.split(end, offset);
  4950. this.setEndAfter(end);
  4951. }
  4952. }
  4953. }
  4954. return this;
  4955. },
  4956. /**
  4957. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4958. * @method txtToElmBoundary
  4959. * @remind 该操作不会修改dom节点
  4960. * @return { UE.dom.Range } 当前range对象
  4961. */
  4962. /**
  4963. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4964. * ignoreCollapsed 的值决定是否执行该调整
  4965. * @method txtToElmBoundary
  4966. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4967. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4968. * @return { UE.dom.Range } 当前range对象
  4969. */
  4970. txtToElmBoundary:function (ignoreCollapsed) {
  4971. function adjust(r, c) {
  4972. var container = r[c + 'Container'],
  4973. offset = r[c + 'Offset'];
  4974. if (container.nodeType == 3) {
  4975. if (!offset) {
  4976. r['set' + c.replace(/(\w)/, function (a) {
  4977. return a.toUpperCase();
  4978. }) + 'Before'](container);
  4979. } else if (offset >= container.nodeValue.length) {
  4980. r['set' + c.replace(/(\w)/, function (a) {
  4981. return a.toUpperCase();
  4982. }) + 'After' ](container);
  4983. }
  4984. }
  4985. }
  4986. if (ignoreCollapsed || !this.collapsed) {
  4987. adjust(this, 'start');
  4988. adjust(this, 'end');
  4989. }
  4990. return this;
  4991. },
  4992. /**
  4993. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  4994. * @method insertNode
  4995. * @param { Node } node 需要插入的节点
  4996. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  4997. * @return { UE.dom.Range } 当前range对象
  4998. */
  4999. insertNode:function (node) {
  5000. var first = node, length = 1;
  5001. if (node.nodeType == 11) {
  5002. first = node.firstChild;
  5003. length = node.childNodes.length;
  5004. }
  5005. this.trimBoundary(true);
  5006. var start = this.startContainer,
  5007. offset = this.startOffset;
  5008. var nextNode = start.childNodes[ offset ];
  5009. if (nextNode) {
  5010. start.insertBefore(node, nextNode);
  5011. } else {
  5012. start.appendChild(node);
  5013. }
  5014. if (first.parentNode === this.endContainer) {
  5015. this.endOffset = this.endOffset + length;
  5016. }
  5017. return this.setStartBefore(first);
  5018. },
  5019. /**
  5020. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5021. * @method setCursor
  5022. * @return { UE.dom.Range } 当前range对象
  5023. * @see UE.dom.Range:collapse()
  5024. */
  5025. /**
  5026. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5027. * @method setCursor
  5028. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5029. * 反之,则向开始容器方向闭合
  5030. * @return { UE.dom.Range } 当前range对象
  5031. * @see UE.dom.Range:collapse(Boolean)
  5032. */
  5033. setCursor:function (toEnd, noFillData) {
  5034. return this.collapse(!toEnd).select(noFillData);
  5035. },
  5036. /**
  5037. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5038. * @method createBookmark
  5039. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5040. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5041. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5042. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5043. * 返回的记录的类型为ID, 反之则为引用
  5044. */
  5045. createBookmark:function (serialize, same) {
  5046. var endNode,
  5047. startNode = this.document.createElement('span');
  5048. startNode.style.cssText = 'display:none;line-height:0px;';
  5049. startNode.appendChild(this.document.createTextNode('\u200D'));
  5050. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5051. if (!this.collapsed) {
  5052. endNode = startNode.cloneNode(true);
  5053. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5054. }
  5055. this.insertNode(startNode);
  5056. if (endNode) {
  5057. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5058. }
  5059. this.setStartAfter(startNode);
  5060. return {
  5061. start:serialize ? startNode.id : startNode,
  5062. end:endNode ? serialize ? endNode.id : endNode : null,
  5063. id:serialize
  5064. }
  5065. },
  5066. /**
  5067. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5068. * @method moveToBookmark
  5069. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5070. * @return { UE.dom.Range } 当前range对象
  5071. * @see UE.dom.Range:createBookmark(Boolean)
  5072. */
  5073. moveToBookmark:function (bookmark) {
  5074. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5075. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5076. this.setStartBefore(start);
  5077. domUtils.remove(start);
  5078. if (end) {
  5079. this.setEndBefore(end);
  5080. domUtils.remove(end);
  5081. } else {
  5082. this.collapse(true);
  5083. }
  5084. return this;
  5085. },
  5086. /**
  5087. * 调整range的边界,使其"放大"到最近的父节点
  5088. * @method enlarge
  5089. * @remind 会引起选区的变化
  5090. * @return { UE.dom.Range } 当前range对象
  5091. */
  5092. /**
  5093. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5094. * 要求扩大之后的父节点是block节点
  5095. * @method enlarge
  5096. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5097. * @return { UE.dom.Range } 当前range对象
  5098. */
  5099. enlarge:function (toBlock, stopFn) {
  5100. var isBody = domUtils.isBody,
  5101. pre, node, tmp = this.document.createTextNode('');
  5102. if (toBlock) {
  5103. node = this.startContainer;
  5104. if (node.nodeType == 1) {
  5105. if (node.childNodes[this.startOffset]) {
  5106. pre = node = node.childNodes[this.startOffset]
  5107. } else {
  5108. node.appendChild(tmp);
  5109. pre = node = tmp;
  5110. }
  5111. } else {
  5112. pre = node;
  5113. }
  5114. while (1) {
  5115. if (domUtils.isBlockElm(node)) {
  5116. node = pre;
  5117. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5118. node = pre;
  5119. }
  5120. this.setStartBefore(node);
  5121. break;
  5122. }
  5123. pre = node;
  5124. node = node.parentNode;
  5125. }
  5126. node = this.endContainer;
  5127. if (node.nodeType == 1) {
  5128. if (pre = node.childNodes[this.endOffset]) {
  5129. node.insertBefore(tmp, pre);
  5130. } else {
  5131. node.appendChild(tmp);
  5132. }
  5133. pre = node = tmp;
  5134. } else {
  5135. pre = node;
  5136. }
  5137. while (1) {
  5138. if (domUtils.isBlockElm(node)) {
  5139. node = pre;
  5140. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5141. node = pre;
  5142. }
  5143. this.setEndAfter(node);
  5144. break;
  5145. }
  5146. pre = node;
  5147. node = node.parentNode;
  5148. }
  5149. if (tmp.parentNode === this.endContainer) {
  5150. this.endOffset--;
  5151. }
  5152. domUtils.remove(tmp);
  5153. }
  5154. // 扩展边界到最大
  5155. if (!this.collapsed) {
  5156. while (this.startOffset == 0) {
  5157. if (stopFn && stopFn(this.startContainer)) {
  5158. break;
  5159. }
  5160. if (isBody(this.startContainer)) {
  5161. break;
  5162. }
  5163. this.setStartBefore(this.startContainer);
  5164. }
  5165. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5166. if (stopFn && stopFn(this.endContainer)) {
  5167. break;
  5168. }
  5169. if (isBody(this.endContainer)) {
  5170. break;
  5171. }
  5172. this.setEndAfter(this.endContainer);
  5173. }
  5174. }
  5175. return this;
  5176. },
  5177. enlargeToBlockElm:function(ignoreEnd){
  5178. while(!domUtils.isBlockElm(this.startContainer)){
  5179. this.setStartBefore(this.startContainer);
  5180. }
  5181. if(!ignoreEnd){
  5182. while(!domUtils.isBlockElm(this.endContainer)){
  5183. this.setEndAfter(this.endContainer);
  5184. }
  5185. }
  5186. return this;
  5187. },
  5188. /**
  5189. * 调整Range的边界,使其"缩小"到最合适的位置
  5190. * @method adjustmentBoundary
  5191. * @return { UE.dom.Range } 当前range对象
  5192. * @see UE.dom.Range:shrinkBoundary()
  5193. */
  5194. adjustmentBoundary:function () {
  5195. if (!this.collapsed) {
  5196. while (!domUtils.isBody(this.startContainer) &&
  5197. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5198. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5199. ) {
  5200. this.setStartAfter(this.startContainer);
  5201. }
  5202. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5203. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5204. ) {
  5205. this.setEndBefore(this.endContainer);
  5206. }
  5207. }
  5208. return this;
  5209. },
  5210. /**
  5211. * 给range选区中的内容添加给定的inline标签
  5212. * @method applyInlineStyle
  5213. * @param { String } tagName 需要添加的标签名
  5214. * @example
  5215. * ```html
  5216. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5217. * ```
  5218. */
  5219. /**
  5220. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5221. * @method applyInlineStyle
  5222. * @param { String } tagName 需要添加的标签名
  5223. * @param { Object } attrs 跟随新添加的标签的属性
  5224. * @return { UE.dom.Range } 当前选区
  5225. * @example
  5226. * ```html
  5227. * <p>xxxx[xxxx]x</p>
  5228. *
  5229. * ==>
  5230. *
  5231. * <!-- 执行操作 -->
  5232. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5233. *
  5234. * ==>
  5235. *
  5236. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5237. * ```
  5238. */
  5239. applyInlineStyle:function (tagName, attrs, list) {
  5240. if (this.collapsed)return this;
  5241. this.trimBoundary().enlarge(false,
  5242. function (node) {
  5243. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5244. }).adjustmentBoundary();
  5245. var bookmark = this.createBookmark(),
  5246. end = bookmark.end,
  5247. filterFn = function (node) {
  5248. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5249. },
  5250. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5251. node,
  5252. pre,
  5253. range = this.cloneRange();
  5254. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5255. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5256. range.setStartBefore(current);
  5257. node = current;
  5258. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5259. pre = node;
  5260. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5261. return dtd[tagName][parent.tagName];
  5262. });
  5263. }
  5264. var frag = range.setEndAfter(pre).extractContents(), elm;
  5265. if (list && list.length > 0) {
  5266. var level, top;
  5267. top = level = list[0].cloneNode(false);
  5268. for (var i = 1, ci; ci = list[i++];) {
  5269. level.appendChild(ci.cloneNode(false));
  5270. level = level.firstChild;
  5271. }
  5272. elm = level;
  5273. } else {
  5274. elm = range.document.createElement(tagName);
  5275. }
  5276. if (attrs) {
  5277. domUtils.setAttributes(elm, attrs);
  5278. }
  5279. elm.appendChild(frag);
  5280. range.insertNode(list ? top : elm);
  5281. //处理下滑线在a上的情况
  5282. var aNode;
  5283. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5284. domUtils.setAttributes(aNode, attrs);
  5285. domUtils.remove(elm, true);
  5286. elm = aNode;
  5287. } else {
  5288. domUtils.mergeSibling(elm);
  5289. domUtils.clearEmptySibling(elm);
  5290. }
  5291. //去除子节点相同的
  5292. domUtils.mergeChild(elm, attrs);
  5293. current = domUtils.getNextDomNode(elm, false, filterFn);
  5294. domUtils.mergeToParent(elm);
  5295. if (node === end) {
  5296. break;
  5297. }
  5298. } else {
  5299. current = domUtils.getNextDomNode(current, true, filterFn);
  5300. }
  5301. }
  5302. return this.moveToBookmark(bookmark);
  5303. },
  5304. /**
  5305. * 移除当前选区内指定的inline标签,但保留其中的内容
  5306. * @method removeInlineStyle
  5307. * @param { String } tagName 需要移除的标签名
  5308. * @return { UE.dom.Range } 当前的range对象
  5309. * @example
  5310. * ```html
  5311. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5312. * ```
  5313. */
  5314. /**
  5315. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5316. * @method removeInlineStyle
  5317. * @param { Array } tagNameArr 需要移除的标签名的数组
  5318. * @return { UE.dom.Range } 当前的range对象
  5319. * @see UE.dom.Range:removeInlineStyle(String)
  5320. */
  5321. removeInlineStyle:function (tagNames) {
  5322. if (this.collapsed)return this;
  5323. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5324. this.shrinkBoundary().adjustmentBoundary();
  5325. var start = this.startContainer, end = this.endContainer;
  5326. while (1) {
  5327. if (start.nodeType == 1) {
  5328. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5329. break;
  5330. }
  5331. if (start.tagName.toLowerCase() == 'body') {
  5332. start = null;
  5333. break;
  5334. }
  5335. }
  5336. start = start.parentNode;
  5337. }
  5338. while (1) {
  5339. if (end.nodeType == 1) {
  5340. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5341. break;
  5342. }
  5343. if (end.tagName.toLowerCase() == 'body') {
  5344. end = null;
  5345. break;
  5346. }
  5347. }
  5348. end = end.parentNode;
  5349. }
  5350. var bookmark = this.createBookmark(),
  5351. frag,
  5352. tmpRange;
  5353. if (start) {
  5354. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5355. frag = tmpRange.extractContents();
  5356. tmpRange.insertNode(frag);
  5357. domUtils.clearEmptySibling(start, true);
  5358. start.parentNode.insertBefore(bookmark.start, start);
  5359. }
  5360. if (end) {
  5361. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5362. frag = tmpRange.extractContents();
  5363. tmpRange.insertNode(frag);
  5364. domUtils.clearEmptySibling(end, false, true);
  5365. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5366. }
  5367. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5368. return node.nodeType == 1;
  5369. }), next;
  5370. while (current && current !== bookmark.end) {
  5371. next = domUtils.getNextDomNode(current, true, function (node) {
  5372. return node.nodeType == 1;
  5373. });
  5374. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5375. domUtils.remove(current, true);
  5376. }
  5377. current = next;
  5378. }
  5379. return this.moveToBookmark(bookmark);
  5380. },
  5381. /**
  5382. * 获取当前选中的自闭合的节点
  5383. * @method getClosedNode
  5384. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5385. */
  5386. getClosedNode:function () {
  5387. var node;
  5388. if (!this.collapsed) {
  5389. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5390. if (selectOneNode(range)) {
  5391. var child = range.startContainer.childNodes[range.startOffset];
  5392. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5393. node = child;
  5394. }
  5395. }
  5396. }
  5397. return node;
  5398. },
  5399. /**
  5400. * 在页面上高亮range所表示的选区
  5401. * @method select
  5402. * @return { UE.dom.Range } 返回当前Range对象
  5403. */
  5404. //这里不区分ie9以上,trace:3824
  5405. select:browser.ie ? function (noFillData, textRange) {
  5406. var nativeRange;
  5407. if (!this.collapsed)
  5408. this.shrinkBoundary();
  5409. var node = this.getClosedNode();
  5410. if (node && !textRange) {
  5411. try {
  5412. nativeRange = this.document.body.createControlRange();
  5413. nativeRange.addElement(node);
  5414. nativeRange.select();
  5415. } catch (e) {}
  5416. return this;
  5417. }
  5418. var bookmark = this.createBookmark(),
  5419. start = bookmark.start,
  5420. end;
  5421. nativeRange = this.document.body.createTextRange();
  5422. nativeRange.moveToElementText(start);
  5423. nativeRange.moveStart('character', 1);
  5424. if (!this.collapsed) {
  5425. var nativeRangeEnd = this.document.body.createTextRange();
  5426. end = bookmark.end;
  5427. nativeRangeEnd.moveToElementText(end);
  5428. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5429. } else {
  5430. if (!noFillData && this.startContainer.nodeType != 3) {
  5431. //使用<span>|x<span>固定住光标
  5432. var tmpText = this.document.createTextNode(fillChar),
  5433. tmp = this.document.createElement('span');
  5434. tmp.appendChild(this.document.createTextNode(fillChar));
  5435. start.parentNode.insertBefore(tmp, start);
  5436. start.parentNode.insertBefore(tmpText, start);
  5437. //当点b,i,u时,不能清除i上边的b
  5438. removeFillData(this.document, tmpText);
  5439. fillData = tmpText;
  5440. mergeSibling(tmp, 'previousSibling');
  5441. mergeSibling(start, 'nextSibling');
  5442. nativeRange.moveStart('character', -1);
  5443. nativeRange.collapse(true);
  5444. }
  5445. }
  5446. this.moveToBookmark(bookmark);
  5447. tmp && domUtils.remove(tmp);
  5448. //IE在隐藏状态下不支持range操作,catch一下
  5449. try {
  5450. nativeRange.select();
  5451. } catch (e) {
  5452. }
  5453. return this;
  5454. } : function (notInsertFillData) {
  5455. function checkOffset(rng){
  5456. function check(node,offset,dir){
  5457. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5458. rng[dir + 'Offset'] = node.nodeValue.length
  5459. }
  5460. }
  5461. check(rng.startContainer,rng.startOffset,'start');
  5462. check(rng.endContainer,rng.endOffset,'end');
  5463. }
  5464. var win = domUtils.getWindow(this.document),
  5465. sel = win.getSelection(),
  5466. txtNode;
  5467. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5468. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5469. //browser.gecko ? this.document.body.focus() : win.focus();
  5470. if (sel) {
  5471. sel.removeAllRanges();
  5472. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5473. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5474. if (this.collapsed && !notInsertFillData) {
  5475. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5476. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5477. // var tmp = this.document.createTextNode('');
  5478. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5479. // }
  5480. //
  5481. //处理光标落在文本节点的情况
  5482. //处理以下的情况
  5483. //<b>|xxxx</b>
  5484. //<b>xxxx</b>|xxxx
  5485. //xxxx<b>|</b>
  5486. var start = this.startContainer,child = start;
  5487. if(start.nodeType == 1){
  5488. child = start.childNodes[this.startOffset];
  5489. }
  5490. if( !(start.nodeType == 3 && this.startOffset) &&
  5491. (child ?
  5492. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5493. :
  5494. (!start.lastChild || start.lastChild.nodeType != 3)
  5495. )
  5496. ){
  5497. txtNode = this.document.createTextNode(fillChar);
  5498. //跟着前边走
  5499. this.insertNode(txtNode);
  5500. removeFillData(this.document, txtNode);
  5501. mergeSibling(txtNode, 'previousSibling');
  5502. mergeSibling(txtNode, 'nextSibling');
  5503. fillData = txtNode;
  5504. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5505. }
  5506. }
  5507. var nativeRange = this.document.createRange();
  5508. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5509. var child = this.startContainer.childNodes[this.startOffset];
  5510. if(!child){
  5511. //往前靠拢
  5512. child = this.startContainer.lastChild;
  5513. if( child && domUtils.isBr(child)){
  5514. this.setStartBefore(child).collapse(true);
  5515. }
  5516. }else{
  5517. //向后靠拢
  5518. while(child && domUtils.isBlockElm(child)){
  5519. if(child.nodeType == 1 && child.childNodes[0]){
  5520. child = child.childNodes[0]
  5521. }else{
  5522. break;
  5523. }
  5524. }
  5525. child && this.setStartBefore(child).collapse(true)
  5526. }
  5527. }
  5528. //是createAddress最后一位算的不准,现在这里进行微调
  5529. checkOffset(this);
  5530. nativeRange.setStart(this.startContainer, this.startOffset);
  5531. nativeRange.setEnd(this.endContainer, this.endOffset);
  5532. sel.addRange(nativeRange);
  5533. }
  5534. return this;
  5535. },
  5536. /**
  5537. * 滚动到当前range开始的位置
  5538. * @method scrollToView
  5539. * @param { Window } win 当前range对象所属的window对象
  5540. * @return { UE.dom.Range } 当前Range对象
  5541. */
  5542. /**
  5543. * 滚动到距离当前range开始位置 offset 的位置处
  5544. * @method scrollToView
  5545. * @param { Window } win 当前range对象所属的window对象
  5546. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5547. * @return { UE.dom.Range } 当前Range对象
  5548. */
  5549. scrollToView:function (win, offset) {
  5550. win = win ? window : domUtils.getWindow(this.document);
  5551. var me = this,
  5552. span = me.document.createElement('span');
  5553. //trace:717
  5554. span.innerHTML = '&nbsp;';
  5555. me.cloneRange().insertNode(span);
  5556. domUtils.scrollToView(span, win, offset);
  5557. domUtils.remove(span);
  5558. return me;
  5559. },
  5560. /**
  5561. * 判断当前选区内容是否占位符
  5562. * @private
  5563. * @method inFillChar
  5564. * @return { Boolean } 如果是占位符返回true,否则返回false
  5565. */
  5566. inFillChar : function(){
  5567. var start = this.startContainer;
  5568. if(this.collapsed && start.nodeType == 3
  5569. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5570. ){
  5571. return true;
  5572. }
  5573. return false;
  5574. },
  5575. /**
  5576. * 保存
  5577. * @method createAddress
  5578. * @private
  5579. * @return { Boolean } 返回开始和结束的位置
  5580. * @example
  5581. * ```html
  5582. * <body>
  5583. * <p>
  5584. * aaaa
  5585. * <em>
  5586. * <!-- 选区开始 -->
  5587. * bbbb
  5588. * <!-- 选区结束 -->
  5589. * </em>
  5590. * </p>
  5591. *
  5592. * <script>
  5593. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5594. * console.log( range.createAddress() );
  5595. * </script>
  5596. * </body>
  5597. * ```
  5598. */
  5599. createAddress : function(ignoreEnd,ignoreTxt){
  5600. var addr = {},me = this;
  5601. function getAddress(isStart){
  5602. var node = isStart ? me.startContainer : me.endContainer;
  5603. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5604. addrs = [];
  5605. for(var i = 0,ci;ci = parents[i++];){
  5606. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5607. }
  5608. var firstIndex = 0;
  5609. if(ignoreTxt){
  5610. if(node.nodeType == 3){
  5611. var tmpNode = node.previousSibling;
  5612. while(tmpNode && tmpNode.nodeType == 3){
  5613. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5614. tmpNode = tmpNode.previousSibling;
  5615. }
  5616. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5617. }else{
  5618. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5619. if(node){
  5620. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5621. }else{
  5622. node = isStart ? me.startContainer : me.endContainer;
  5623. var first = node.firstChild;
  5624. while(first){
  5625. if(domUtils.isFillChar(first)){
  5626. first = first.nextSibling;
  5627. continue;
  5628. }
  5629. firstIndex++;
  5630. if(first.nodeType == 3){
  5631. while( first && first.nodeType == 3){
  5632. first = first.nextSibling;
  5633. }
  5634. }else{
  5635. first = first.nextSibling;
  5636. }
  5637. }
  5638. }
  5639. }
  5640. }else{
  5641. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5642. }
  5643. if(firstIndex < 0){
  5644. firstIndex = 0;
  5645. }
  5646. addrs.push(firstIndex);
  5647. return addrs;
  5648. }
  5649. addr.startAddress = getAddress(true);
  5650. if(!ignoreEnd){
  5651. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5652. }
  5653. return addr;
  5654. },
  5655. /**
  5656. * 保存
  5657. * @method createAddress
  5658. * @private
  5659. * @return { Boolean } 返回开始和结束的位置
  5660. * @example
  5661. * ```html
  5662. * <body>
  5663. * <p>
  5664. * aaaa
  5665. * <em>
  5666. * <!-- 选区开始 -->
  5667. * bbbb
  5668. * <!-- 选区结束 -->
  5669. * </em>
  5670. * </p>
  5671. *
  5672. * <script>
  5673. * var range = editor.selection.getRange();
  5674. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5675. * range.select();
  5676. * //output: 'bbbb'
  5677. * console.log(editor.selection.getText());
  5678. * </script>
  5679. * </body>
  5680. * ```
  5681. */
  5682. moveToAddress : function(addr,ignoreEnd){
  5683. var me = this;
  5684. function getNode(address,isStart){
  5685. var tmpNode = me.document.body,
  5686. parentNode,offset;
  5687. for(var i= 0,ci,l=address.length;i<l;i++){
  5688. ci = address[i];
  5689. parentNode = tmpNode;
  5690. tmpNode = tmpNode.childNodes[ci];
  5691. if(!tmpNode){
  5692. offset = ci;
  5693. break;
  5694. }
  5695. }
  5696. if(isStart){
  5697. if(tmpNode){
  5698. me.setStartBefore(tmpNode)
  5699. }else{
  5700. me.setStart(parentNode,offset)
  5701. }
  5702. }else{
  5703. if(tmpNode){
  5704. me.setEndBefore(tmpNode)
  5705. }else{
  5706. me.setEnd(parentNode,offset)
  5707. }
  5708. }
  5709. }
  5710. getNode(addr.startAddress,true);
  5711. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5712. return me;
  5713. },
  5714. /**
  5715. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5716. * @method equals
  5717. * @param { UE.dom.Range } 需要判断的Range对象
  5718. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5719. */
  5720. equals : function(rng){
  5721. for(var p in this){
  5722. if(this.hasOwnProperty(p)){
  5723. if(this[p] !== rng[p])
  5724. return false
  5725. }
  5726. }
  5727. return true;
  5728. },
  5729. /**
  5730. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5731. * 作为其参数。
  5732. * @method traversal
  5733. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5734. * @return { UE.dom.Range } 当前range对象
  5735. * @example
  5736. * ```html
  5737. *
  5738. * <body>
  5739. *
  5740. * <!-- 选区开始 -->
  5741. * <span></span>
  5742. * <a></a>
  5743. * <!-- 选区结束 -->
  5744. * </body>
  5745. *
  5746. * <script>
  5747. *
  5748. * //output: <span></span><a></a>
  5749. * console.log( range.cloneContents() );
  5750. *
  5751. * range.traversal( function ( node ) {
  5752. *
  5753. * if ( node.nodeType === 1 ) {
  5754. * node.className = "test";
  5755. * }
  5756. *
  5757. * } );
  5758. *
  5759. * //output: <span class="test"></span><a class="test"></a>
  5760. * console.log( range.cloneContents() );
  5761. *
  5762. * </script>
  5763. * ```
  5764. */
  5765. /**
  5766. * 遍历range内的节点。
  5767. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5768. * 作为其参数。
  5769. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5770. * 发doFn函数的执行
  5771. * @method traversal
  5772. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5773. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5774. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5775. * 会触发doFn。
  5776. * @return { UE.dom.Range } 当前range对象
  5777. * @see UE.dom.Range:traversal(Function)
  5778. * @example
  5779. * ```html
  5780. *
  5781. * <body>
  5782. *
  5783. * <!-- 选区开始 -->
  5784. * <span></span>
  5785. * <a></a>
  5786. * <!-- 选区结束 -->
  5787. * </body>
  5788. *
  5789. * <script>
  5790. *
  5791. * //output: <span></span><a></a>
  5792. * console.log( range.cloneContents() );
  5793. *
  5794. * range.traversal( function ( node ) {
  5795. *
  5796. * node.className = "test";
  5797. *
  5798. * }, function ( node ) {
  5799. * return node.nodeType === 1;
  5800. * } );
  5801. *
  5802. * //output: <span class="test"></span><a class="test"></a>
  5803. * console.log( range.cloneContents() );
  5804. *
  5805. * </script>
  5806. * ```
  5807. */
  5808. traversal:function(doFn,filterFn){
  5809. if (this.collapsed)
  5810. return this;
  5811. var bookmark = this.createBookmark(),
  5812. end = bookmark.end,
  5813. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5814. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5815. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5816. doFn(current);
  5817. current = tmpNode;
  5818. }
  5819. return this.moveToBookmark(bookmark);
  5820. }
  5821. };
  5822. })();
  5823. // core/Selection.js
  5824. /**
  5825. * 选集
  5826. * @file
  5827. * @module UE.dom
  5828. * @class Selection
  5829. * @since 1.2.6.1
  5830. */
  5831. /**
  5832. * 选区集合
  5833. * @unfile
  5834. * @module UE.dom
  5835. * @class Selection
  5836. */
  5837. (function () {
  5838. function getBoundaryInformation( range, start ) {
  5839. var getIndex = domUtils.getNodeIndex;
  5840. range = range.duplicate();
  5841. range.collapse( start );
  5842. var parent = range.parentElement();
  5843. //如果节点里没有子节点,直接退出
  5844. if ( !parent.hasChildNodes() ) {
  5845. return {container:parent, offset:0};
  5846. }
  5847. var siblings = parent.children,
  5848. child,
  5849. testRange = range.duplicate(),
  5850. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5851. distance;
  5852. while ( startIndex <= endIndex ) {
  5853. index = Math.floor( (startIndex + endIndex) / 2 );
  5854. child = siblings[index];
  5855. testRange.moveToElementText( child );
  5856. var position = testRange.compareEndPoints( 'StartToStart', range );
  5857. if ( position > 0 ) {
  5858. endIndex = index - 1;
  5859. } else if ( position < 0 ) {
  5860. startIndex = index + 1;
  5861. } else {
  5862. //trace:1043
  5863. return {container:parent, offset:getIndex( child )};
  5864. }
  5865. }
  5866. if ( index == -1 ) {
  5867. testRange.moveToElementText( parent );
  5868. testRange.setEndPoint( 'StartToStart', range );
  5869. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5870. siblings = parent.childNodes;
  5871. if ( !distance ) {
  5872. child = siblings[siblings.length - 1];
  5873. return {container:child, offset:child.nodeValue.length};
  5874. }
  5875. var i = siblings.length;
  5876. while ( distance > 0 ){
  5877. distance -= siblings[ --i ].nodeValue.length;
  5878. }
  5879. return {container:siblings[i], offset:-distance};
  5880. }
  5881. testRange.collapse( position > 0 );
  5882. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5883. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5884. if ( !distance ) {
  5885. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5886. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5887. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5888. }
  5889. while ( distance > 0 ) {
  5890. try {
  5891. var pre = child;
  5892. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5893. distance -= child.nodeValue.length;
  5894. } catch ( e ) {
  5895. return {container:parent, offset:getIndex( pre )};
  5896. }
  5897. }
  5898. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5899. }
  5900. /**
  5901. * 将ieRange转换为Range对象
  5902. * @param {Range} ieRange ieRange对象
  5903. * @param {Range} range Range对象
  5904. * @return {Range} range 返回转换后的Range对象
  5905. */
  5906. function transformIERangeToRange( ieRange, range ) {
  5907. if ( ieRange.item ) {
  5908. range.selectNode( ieRange.item( 0 ) );
  5909. } else {
  5910. var bi = getBoundaryInformation( ieRange, true );
  5911. range.setStart( bi.container, bi.offset );
  5912. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5913. bi = getBoundaryInformation( ieRange, false );
  5914. range.setEnd( bi.container, bi.offset );
  5915. }
  5916. }
  5917. return range;
  5918. }
  5919. /**
  5920. * 获得ieRange
  5921. * @param {Selection} sel Selection对象
  5922. * @return {ieRange} 得到ieRange
  5923. */
  5924. function _getIERange( sel ) {
  5925. var ieRange;
  5926. //ie下有可能报错
  5927. try {
  5928. ieRange = sel.getNative().createRange();
  5929. } catch ( e ) {
  5930. return null;
  5931. }
  5932. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5933. if ( ( el.ownerDocument || el ) === sel.document ) {
  5934. return ieRange;
  5935. }
  5936. return null;
  5937. }
  5938. var Selection = dom.Selection = function ( doc ) {
  5939. var me = this, iframe;
  5940. me.document = doc;
  5941. if ( browser.ie9below ) {
  5942. iframe = domUtils.getWindow( doc ).frameElement;
  5943. domUtils.on( iframe, 'beforedeactivate', function () {
  5944. me._bakIERange = me.getIERange();
  5945. } );
  5946. domUtils.on( iframe, 'activate', function () {
  5947. try {
  5948. if ( !_getIERange( me ) && me._bakIERange ) {
  5949. me._bakIERange.select();
  5950. }
  5951. } catch ( ex ) {
  5952. }
  5953. me._bakIERange = null;
  5954. } );
  5955. }
  5956. iframe = doc = null;
  5957. };
  5958. Selection.prototype = {
  5959. rangeInBody : function(rng,txtRange){
  5960. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5961. return node === this.document.body || domUtils.inDoc(node,this.document);
  5962. },
  5963. /**
  5964. * 获取原生seleciton对象
  5965. * @method getNative
  5966. * @return { Object } 获得selection对象
  5967. * @example
  5968. * ```javascript
  5969. * editor.selection.getNative();
  5970. * ```
  5971. */
  5972. getNative:function () {
  5973. var doc = this.document;
  5974. try {
  5975. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5976. } catch ( e ) {
  5977. return null;
  5978. }
  5979. },
  5980. /**
  5981. * 获得ieRange
  5982. * @method getIERange
  5983. * @return { Object } 返回ie原生的Range
  5984. * @example
  5985. * ```javascript
  5986. * editor.selection.getIERange();
  5987. * ```
  5988. */
  5989. getIERange:function () {
  5990. var ieRange = _getIERange( this );
  5991. if ( !ieRange ) {
  5992. if ( this._bakIERange ) {
  5993. return this._bakIERange;
  5994. }
  5995. }
  5996. return ieRange;
  5997. },
  5998. /**
  5999. * 缓存当前选区的range和选区的开始节点
  6000. * @method cache
  6001. */
  6002. cache:function () {
  6003. this.clear();
  6004. this._cachedRange = this.getRange();
  6005. this._cachedStartElement = this.getStart();
  6006. this._cachedStartElementPath = this.getStartElementPath();
  6007. },
  6008. /**
  6009. * 获取选区开始位置的父节点到body
  6010. * @method getStartElementPath
  6011. * @return { Array } 返回父节点集合
  6012. * @example
  6013. * ```javascript
  6014. * editor.selection.getStartElementPath();
  6015. * ```
  6016. */
  6017. getStartElementPath:function () {
  6018. if ( this._cachedStartElementPath ) {
  6019. return this._cachedStartElementPath;
  6020. }
  6021. var start = this.getStart();
  6022. if ( start ) {
  6023. return domUtils.findParents( start, true, null, true )
  6024. }
  6025. return [];
  6026. },
  6027. /**
  6028. * 清空缓存
  6029. * @method clear
  6030. */
  6031. clear:function () {
  6032. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6033. },
  6034. /**
  6035. * 编辑器是否得到了选区
  6036. * @method isFocus
  6037. */
  6038. isFocus:function () {
  6039. try {
  6040. if(browser.ie9below){
  6041. var nativeRange = _getIERange(this);
  6042. return !!(nativeRange && this.rangeInBody(nativeRange));
  6043. }else{
  6044. return !!this.getNative().rangeCount;
  6045. }
  6046. } catch ( e ) {
  6047. return false;
  6048. }
  6049. },
  6050. /**
  6051. * 获取选区对应的Range
  6052. * @method getRange
  6053. * @return { Object } 得到Range对象
  6054. * @example
  6055. * ```javascript
  6056. * editor.selection.getRange();
  6057. * ```
  6058. */
  6059. getRange:function () {
  6060. var me = this;
  6061. function optimze( range ) {
  6062. var child = me.document.body.firstChild,
  6063. collapsed = range.collapsed;
  6064. while ( child && child.firstChild ) {
  6065. range.setStart( child, 0 );
  6066. child = child.firstChild;
  6067. }
  6068. if ( !range.startContainer ) {
  6069. range.setStart( me.document.body, 0 )
  6070. }
  6071. if ( collapsed ) {
  6072. range.collapse( true );
  6073. }
  6074. }
  6075. if ( me._cachedRange != null ) {
  6076. return this._cachedRange;
  6077. }
  6078. var range = new baidu.editor.dom.Range( me.document );
  6079. if ( browser.ie9below ) {
  6080. var nativeRange = me.getIERange();
  6081. if ( nativeRange ) {
  6082. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6083. try{
  6084. transformIERangeToRange( nativeRange, range );
  6085. }catch(e){
  6086. optimze( range );
  6087. }
  6088. } else {
  6089. optimze( range );
  6090. }
  6091. } else {
  6092. var sel = me.getNative();
  6093. if ( sel && sel.rangeCount ) {
  6094. var firstRange = sel.getRangeAt( 0 );
  6095. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6096. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6097. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6098. optimze( range );
  6099. }
  6100. } else {
  6101. //trace:1734 有可能已经不在dom树上了,标识的节点
  6102. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6103. return this._bakRange;
  6104. }
  6105. optimze( range );
  6106. }
  6107. }
  6108. return this._bakRange = range;
  6109. },
  6110. /**
  6111. * 获取开始元素,用于状态反射
  6112. * @method getStart
  6113. * @return { Element } 获得开始元素
  6114. * @example
  6115. * ```javascript
  6116. * editor.selection.getStart();
  6117. * ```
  6118. */
  6119. getStart:function () {
  6120. if ( this._cachedStartElement ) {
  6121. return this._cachedStartElement;
  6122. }
  6123. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6124. tmpRange,
  6125. start, tmp, parent;
  6126. if ( browser.ie9below ) {
  6127. if ( !range ) {
  6128. //todo 给第一个值可能会有问题
  6129. return this.document.body.firstChild;
  6130. }
  6131. //control元素
  6132. if ( range.item ){
  6133. return range.item( 0 );
  6134. }
  6135. tmpRange = range.duplicate();
  6136. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6137. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6138. tmpRange.collapse( 1 );
  6139. start = tmpRange.parentElement();
  6140. parent = tmp = range.parentElement();
  6141. while ( tmp = tmp.parentNode ) {
  6142. if ( tmp == start ) {
  6143. start = parent;
  6144. break;
  6145. }
  6146. }
  6147. } else {
  6148. range.shrinkBoundary();
  6149. start = range.startContainer;
  6150. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6151. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6152. }
  6153. if ( start.nodeType == 3 ){
  6154. return start.parentNode;
  6155. }
  6156. }
  6157. return start;
  6158. },
  6159. /**
  6160. * 得到选区中的文本
  6161. * @method getText
  6162. * @return { String } 选区中包含的文本
  6163. * @example
  6164. * ```javascript
  6165. * editor.selection.getText();
  6166. * ```
  6167. */
  6168. getText:function () {
  6169. var nativeSel, nativeRange;
  6170. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6171. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6172. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6173. }
  6174. return '';
  6175. },
  6176. /**
  6177. * 清除选区
  6178. * @method clearRange
  6179. * @example
  6180. * ```javascript
  6181. * editor.selection.clearRange();
  6182. * ```
  6183. */
  6184. clearRange : function(){
  6185. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6186. }
  6187. };
  6188. })();
  6189. // core/Editor.js
  6190. /**
  6191. * 编辑器主类,包含编辑器提供的大部分公用接口
  6192. * @file
  6193. * @module UE
  6194. * @class Editor
  6195. * @since 1.2.6.1
  6196. */
  6197. /**
  6198. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6199. * @unfile
  6200. * @module UE
  6201. */
  6202. /**
  6203. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6204. * @unfile
  6205. * @module UE
  6206. * @class Editor
  6207. */
  6208. (function () {
  6209. var uid = 0, _selectionChangeTimer;
  6210. /**
  6211. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6212. * @private
  6213. * @method setValue
  6214. * @param { UE.Editor } editor 编辑器事例
  6215. */
  6216. function setValue(form, editor) {
  6217. var textarea;
  6218. if (editor.textarea) {
  6219. if (utils.isString(editor.textarea)) {
  6220. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6221. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6222. textarea = ti;
  6223. break;
  6224. }
  6225. }
  6226. } else {
  6227. textarea = editor.textarea;
  6228. }
  6229. }
  6230. if (!textarea) {
  6231. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6232. 'name': editor.options.textarea,
  6233. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6234. 'style': "display:none"
  6235. }));
  6236. //不要产生多个textarea
  6237. editor.textarea = textarea;
  6238. }
  6239. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
  6240. textarea.value = editor.hasContents() ?
  6241. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6242. ''
  6243. }
  6244. function loadPlugins(me){
  6245. //初始化插件
  6246. for (var pi in UE.plugins) {
  6247. UE.plugins[pi].call(me);
  6248. }
  6249. }
  6250. function checkCurLang(I18N){
  6251. for(var lang in I18N){
  6252. return lang
  6253. }
  6254. }
  6255. function langReadied(me){
  6256. me.langIsReady = true;
  6257. me.fireEvent("langReady");
  6258. }
  6259. /**
  6260. * 编辑器准备就绪后会触发该事件
  6261. * @module UE
  6262. * @class Editor
  6263. * @event ready
  6264. * @remind render方法执行完成之后,会触发该事件
  6265. * @remind
  6266. * @example
  6267. * ```javascript
  6268. * editor.addListener( 'ready', function( editor ) {
  6269. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6270. * } );
  6271. * ```
  6272. */
  6273. /**
  6274. * 执行destroy方法,会触发该事件
  6275. * @module UE
  6276. * @class Editor
  6277. * @event destroy
  6278. * @see UE.Editor:destroy()
  6279. */
  6280. /**
  6281. * 执行reset方法,会触发该事件
  6282. * @module UE
  6283. * @class Editor
  6284. * @event reset
  6285. * @see UE.Editor:reset()
  6286. */
  6287. /**
  6288. * 执行focus方法,会触发该事件
  6289. * @module UE
  6290. * @class Editor
  6291. * @event focus
  6292. * @see UE.Editor:focus(Boolean)
  6293. */
  6294. /**
  6295. * 语言加载完成会触发该事件
  6296. * @module UE
  6297. * @class Editor
  6298. * @event langReady
  6299. */
  6300. /**
  6301. * 运行命令之后会触发该命令
  6302. * @module UE
  6303. * @class Editor
  6304. * @event beforeExecCommand
  6305. */
  6306. /**
  6307. * 运行命令之后会触发该命令
  6308. * @module UE
  6309. * @class Editor
  6310. * @event afterExecCommand
  6311. */
  6312. /**
  6313. * 运行命令之前会触发该命令
  6314. * @module UE
  6315. * @class Editor
  6316. * @event firstBeforeExecCommand
  6317. */
  6318. /**
  6319. * 在getContent方法执行之前会触发该事件
  6320. * @module UE
  6321. * @class Editor
  6322. * @event beforeGetContent
  6323. * @see UE.Editor:getContent()
  6324. */
  6325. /**
  6326. * 在getContent方法执行之后会触发该事件
  6327. * @module UE
  6328. * @class Editor
  6329. * @event afterGetContent
  6330. * @see UE.Editor:getContent()
  6331. */
  6332. /**
  6333. * 在getAllHtml方法执行时会触发该事件
  6334. * @module UE
  6335. * @class Editor
  6336. * @event getAllHtml
  6337. * @see UE.Editor:getAllHtml()
  6338. */
  6339. /**
  6340. * 在setContent方法执行之前会触发该事件
  6341. * @module UE
  6342. * @class Editor
  6343. * @event beforeSetContent
  6344. * @see UE.Editor:setContent(String)
  6345. */
  6346. /**
  6347. * 在setContent方法执行之后会触发该事件
  6348. * @module UE
  6349. * @class Editor
  6350. * @event afterSetContent
  6351. * @see UE.Editor:setContent(String)
  6352. */
  6353. /**
  6354. * 每当编辑器内部选区发生改变时,将触发该事件
  6355. * @event selectionchange
  6356. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6357. * @example
  6358. * ```javascript
  6359. * editor.addListener( 'selectionchange', function( editor ) {
  6360. * console.log('选区发生改变');
  6361. * }
  6362. */
  6363. /**
  6364. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6365. * @module UE
  6366. * @class Editor
  6367. * @event beforeSelectionChange
  6368. * @see UE.Editor:selectionchange
  6369. */
  6370. /**
  6371. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6372. * @module UE
  6373. * @class Editor
  6374. * @event afterSelectionChange
  6375. * @see UE.Editor:selectionchange
  6376. */
  6377. /**
  6378. * 编辑器内容发生改变时会触发该事件
  6379. * @module UE
  6380. * @class Editor
  6381. * @event contentChange
  6382. */
  6383. /**
  6384. * 以默认参数构建一个编辑器实例
  6385. * @constructor
  6386. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6387. * @example
  6388. * ```javascript
  6389. * var editor = new UE.Editor();
  6390. * editor.execCommand('blod');
  6391. * ```
  6392. * @see UE.Config
  6393. */
  6394. /**
  6395. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6396. * @constructor
  6397. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6398. * @param { Object } setting 创建编辑器的参数
  6399. * @example
  6400. * ```javascript
  6401. * var editor = new UE.Editor();
  6402. * editor.execCommand('blod');
  6403. * ```
  6404. * @see UE.Config
  6405. */
  6406. var Editor = UE.Editor = function (options) {
  6407. var me = this;
  6408. me.uid = uid++;
  6409. EventBase.call(me);
  6410. me.commands = {};
  6411. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6412. me.shortcutkeys = {};
  6413. me.inputRules = [];
  6414. me.outputRules = [];
  6415. //设置默认的常用属性
  6416. me.setOpt(Editor.defaultOptions(me));
  6417. /* 尝试异步加载后台配置 */
  6418. me.loadServerConfig();
  6419. if(!utils.isEmptyObject(UE.I18N)){
  6420. //修改默认的语言类型
  6421. me.options.lang = checkCurLang(UE.I18N);
  6422. UE.plugin.load(me);
  6423. langReadied(me);
  6424. }else{
  6425. utils.loadFile(document, {
  6426. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6427. tag: "script",
  6428. type: "text/javascript",
  6429. defer: "defer"
  6430. }, function () {
  6431. UE.plugin.load(me);
  6432. langReadied(me);
  6433. });
  6434. }
  6435. UE.instants['ueditorInstant' + me.uid] = me;
  6436. };
  6437. Editor.prototype = {
  6438. registerCommand : function(name,obj){
  6439. this.commands[name] = obj;
  6440. },
  6441. /**
  6442. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6443. * @method ready
  6444. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6445. * 立即触发该回调。
  6446. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6447. * @example
  6448. * ```javascript
  6449. * editor.ready( function( editor ) {
  6450. * editor.setContent('初始化完毕');
  6451. * } );
  6452. * ```
  6453. * @see UE.Editor.event:ready
  6454. */
  6455. ready: function (fn) {
  6456. var me = this;
  6457. if (fn) {
  6458. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6459. }
  6460. },
  6461. /**
  6462. * 该方法是提供给插件里面使用,设置配置项默认值
  6463. * @method setOpt
  6464. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6465. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6466. * @param { String } key 编辑器的可接受的选项名称
  6467. * @param { * } val 该选项可接受的值
  6468. * @example
  6469. * ```javascript
  6470. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6471. * ```
  6472. */
  6473. /**
  6474. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6475. * @method setOpt
  6476. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6477. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6478. * @param { Object } options 将要设置的选项的键值对对象
  6479. * @example
  6480. * ```javascript
  6481. * editor.setOpt( {
  6482. * 'initContent': '欢迎使用编辑器'
  6483. * } );
  6484. * ```
  6485. */
  6486. setOpt: function (key, val) {
  6487. var obj = {};
  6488. if (utils.isString(key)) {
  6489. obj[key] = val
  6490. } else {
  6491. obj = key;
  6492. }
  6493. utils.extend(this.options, obj, true);
  6494. },
  6495. getOpt:function(key){
  6496. return this.options[key]
  6497. },
  6498. /**
  6499. * 销毁编辑器实例,使用textarea代替
  6500. * @method destroy
  6501. * @example
  6502. * ```javascript
  6503. * editor.destroy();
  6504. * ```
  6505. */
  6506. destroy: function () {
  6507. var me = this;
  6508. me.fireEvent('destroy');
  6509. var container = me.container.parentNode;
  6510. var textarea = me.textarea;
  6511. if (!textarea) {
  6512. textarea = document.createElement('textarea');
  6513. container.parentNode.insertBefore(textarea, container);
  6514. } else {
  6515. textarea.style.display = ''
  6516. }
  6517. textarea.style.width = me.iframe.offsetWidth + 'px';
  6518. textarea.style.height = me.iframe.offsetHeight + 'px';
  6519. textarea.value = me.getContent();
  6520. textarea.id = me.key;
  6521. container.innerHTML = '';
  6522. domUtils.remove(container);
  6523. var key = me.key;
  6524. //trace:2004
  6525. for (var p in me) {
  6526. if (me.hasOwnProperty(p)) {
  6527. delete this[p];
  6528. }
  6529. }
  6530. UE.delEditor(key);
  6531. },
  6532. /**
  6533. * 渲染编辑器的DOM到指定容器
  6534. * @method render
  6535. * @param { String } containerId 指定一个容器ID
  6536. * @remind 执行该方法,会触发ready事件
  6537. * @warning 必须且只能调用一次
  6538. */
  6539. /**
  6540. * 渲染编辑器的DOM到指定容器
  6541. * @method render
  6542. * @param { Element } containerDom 直接指定容器对象
  6543. * @remind 执行该方法,会触发ready事件
  6544. * @warning 必须且只能调用一次
  6545. */
  6546. render: function (container) {
  6547. var me = this,
  6548. options = me.options,
  6549. getStyleValue=function(attr){
  6550. return parseInt(domUtils.getComputedStyle(container,attr));
  6551. };
  6552. if (utils.isString(container)) {
  6553. container = document.getElementById(container);
  6554. }
  6555. if (container) {
  6556. if(options.initialFrameWidth){
  6557. options.minFrameWidth = options.initialFrameWidth
  6558. }else{
  6559. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6560. }
  6561. if(options.initialFrameHeight){
  6562. options.minFrameHeight = options.initialFrameHeight
  6563. }else{
  6564. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6565. }
  6566. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6567. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6568. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6569. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6570. container.style.zIndex = options.zIndex;
  6571. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6572. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6573. '<style type=\'text/css\'>' +
  6574. //设置四周的留边
  6575. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6576. //设置默认字体和字号
  6577. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6578. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6579. //设置段落间距
  6580. 'p{margin:5px 0;}</style>' +
  6581. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6582. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6583. '</head><body class=\'view\' ></body>' +
  6584. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6585. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6586. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6587. container.appendChild(domUtils.createElement(document, 'iframe', {
  6588. id: 'ueditor_' + me.uid,
  6589. width: "100%",
  6590. height: "100%",
  6591. frameborder: "0",
  6592. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6593. // scrolling :'no',
  6594. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6595. 'document.write("' + html + '");document.close();}())'
  6596. }));
  6597. container.style.overflow = 'hidden';
  6598. //解决如果是给定的百分比,会导致高度算不对的问题
  6599. setTimeout(function(){
  6600. if( /%$/.test(options.initialFrameWidth)){
  6601. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6602. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6603. // container.style.width = options.initialFrameWidth + 'px';
  6604. }
  6605. if(/%$/.test(options.initialFrameHeight)){
  6606. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6607. container.style.height = options.initialFrameHeight + 'px';
  6608. }
  6609. })
  6610. }
  6611. },
  6612. /**
  6613. * 编辑器初始化
  6614. * @method _setup
  6615. * @private
  6616. * @param { Element } doc 编辑器Iframe中的文档对象
  6617. */
  6618. _setup: function (doc) {
  6619. var me = this,
  6620. options = me.options;
  6621. if (ie) {
  6622. doc.body.disabled = true;
  6623. doc.body.contentEditable = true;
  6624. doc.body.disabled = false;
  6625. } else {
  6626. doc.body.contentEditable = true;
  6627. }
  6628. doc.body.spellcheck = false;
  6629. me.document = doc;
  6630. me.window = doc.defaultView || doc.parentWindow;
  6631. me.iframe = me.window.frameElement;
  6632. me.body = doc.body;
  6633. me.selection = new dom.Selection(doc);
  6634. //gecko初始化就能得到range,无法判断isFocus了
  6635. var geckoSel;
  6636. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6637. geckoSel.removeAllRanges();
  6638. }
  6639. this._initEvents();
  6640. //为form提交提供一个隐藏的textarea
  6641. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6642. if (form.tagName == 'FORM') {
  6643. me.form = form;
  6644. if(me.options.autoSyncData){
  6645. domUtils.on(me.window,'blur',function(){
  6646. setValue(form,me);
  6647. });
  6648. }else{
  6649. domUtils.on(form, 'submit', function () {
  6650. setValue(this, me);
  6651. });
  6652. }
  6653. break;
  6654. }
  6655. }
  6656. if (options.initialContent) {
  6657. if (options.autoClearinitialContent) {
  6658. var oldExecCommand = me.execCommand;
  6659. me.execCommand = function () {
  6660. me.fireEvent('firstBeforeExecCommand');
  6661. return oldExecCommand.apply(me, arguments);
  6662. };
  6663. this._setDefaultContent(options.initialContent);
  6664. } else
  6665. this.setContent(options.initialContent, false, true);
  6666. }
  6667. //编辑器不能为空内容
  6668. if (domUtils.isEmptyNode(me.body)) {
  6669. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6670. }
  6671. //如果要求focus, 就把光标定位到内容开始
  6672. if (options.focus) {
  6673. setTimeout(function () {
  6674. me.focus(me.options.focusInEnd);
  6675. //如果自动清除开着,就不需要做selectionchange;
  6676. !me.options.autoClearinitialContent && me._selectionChange();
  6677. }, 0);
  6678. }
  6679. if (!me.container) {
  6680. me.container = this.iframe.parentNode;
  6681. }
  6682. if (options.fullscreen && me.ui) {
  6683. me.ui.setFullScreen(true);
  6684. }
  6685. try {
  6686. me.document.execCommand('2D-position', false, false);
  6687. } catch (e) {
  6688. }
  6689. try {
  6690. me.document.execCommand('enableInlineTableEditing', false, false);
  6691. } catch (e) {
  6692. }
  6693. try {
  6694. me.document.execCommand('enableObjectResizing', false, false);
  6695. } catch (e) {
  6696. }
  6697. //挂接快捷键
  6698. me._bindshortcutKeys();
  6699. me.isReady = 1;
  6700. me.fireEvent('ready');
  6701. options.onready && options.onready.call(me);
  6702. if (!browser.ie9below) {
  6703. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6704. //chrome下会出现alt+tab切换时,导致选区位置不对
  6705. if (e.type == 'blur') {
  6706. me._bakRange = me.selection.getRange();
  6707. try {
  6708. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6709. me.selection.getNative().removeAllRanges();
  6710. } catch (e) {
  6711. me._bakNativeRange = null;
  6712. }
  6713. } else {
  6714. try {
  6715. me._bakRange && me._bakRange.select();
  6716. } catch (e) {
  6717. }
  6718. }
  6719. });
  6720. }
  6721. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6722. if (browser.gecko && browser.version <= 10902) {
  6723. //修复ff3.6初始化进来,不能点击获得焦点
  6724. me.body.contentEditable = false;
  6725. setTimeout(function () {
  6726. me.body.contentEditable = true;
  6727. }, 100);
  6728. setInterval(function () {
  6729. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6730. }, 100)
  6731. }
  6732. !options.isShow && me.setHide();
  6733. options.readonly && me.setDisabled();
  6734. },
  6735. /**
  6736. * 同步数据到编辑器所在的form
  6737. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6738. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6739. * @method sync
  6740. * @example
  6741. * ```javascript
  6742. * editor.sync();
  6743. * form.sumbit(); //form变量已经指向了form元素
  6744. * ```
  6745. */
  6746. /**
  6747. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6748. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6749. * @method sync
  6750. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6751. */
  6752. sync: function (formId) {
  6753. var me = this,
  6754. form = formId ? document.getElementById(formId) :
  6755. domUtils.findParent(me.iframe.parentNode, function (node) {
  6756. return node.tagName == 'FORM'
  6757. }, true);
  6758. form && setValue(form, me);
  6759. },
  6760. /**
  6761. * 设置编辑器高度
  6762. * @method setHeight
  6763. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6764. * @param { Number } number 设置的高度值,纯数值,不带单位
  6765. * @example
  6766. * ```javascript
  6767. * editor.setHeight(number);
  6768. * ```
  6769. */
  6770. setHeight: function (height,notSetHeight) {
  6771. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6772. this.iframe.parentNode.style.height = height + 'px';
  6773. }
  6774. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6775. this.body.style.height = height + 'px';
  6776. !notSetHeight && this.trigger('setHeight')
  6777. },
  6778. /**
  6779. * 为编辑器的编辑命令提供快捷键
  6780. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6781. * @method addshortcutkey
  6782. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6783. * @example
  6784. * ```javascript
  6785. * editor.addshortcutkey({
  6786. * "Bold" : "ctrl+66",//^B
  6787. * "Italic" : "ctrl+73", //^I
  6788. * });
  6789. * ```
  6790. */
  6791. /**
  6792. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6793. * @method addshortcutkey
  6794. * @param { String } cmd 触发快捷键时,响应的命令
  6795. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6796. * @example
  6797. * ```javascript
  6798. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6799. * ```
  6800. */
  6801. addshortcutkey: function (cmd, keys) {
  6802. var obj = {};
  6803. if (keys) {
  6804. obj[cmd] = keys
  6805. } else {
  6806. obj = cmd;
  6807. }
  6808. utils.extend(this.shortcutkeys, obj)
  6809. },
  6810. /**
  6811. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6812. * @method _bindshortcutKeys
  6813. * @private
  6814. */
  6815. _bindshortcutKeys: function () {
  6816. var me = this, shortcutkeys = this.shortcutkeys;
  6817. me.addListener('keydown', function (type, e) {
  6818. var keyCode = e.keyCode || e.which;
  6819. for (var i in shortcutkeys) {
  6820. var tmp = shortcutkeys[i].split(',');
  6821. for (var t = 0, ti; ti = tmp[t++];) {
  6822. ti = ti.split(':');
  6823. var key = ti[0], param = ti[1];
  6824. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6825. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6826. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6827. && keyCode == RegExp.$3
  6828. ) ||
  6829. keyCode == RegExp.$1
  6830. ) {
  6831. if (me.queryCommandState(i,param) != -1)
  6832. me.execCommand(i, param);
  6833. domUtils.preventDefault(e);
  6834. }
  6835. }
  6836. }
  6837. }
  6838. });
  6839. },
  6840. /**
  6841. * 获取编辑器的内容
  6842. * @method getContent
  6843. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6844. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6845. * @example
  6846. * ```javascript
  6847. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6848. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6849. * ```
  6850. */
  6851. /**
  6852. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6853. * @method getContent
  6854. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6855. * 代表当前编辑器的内容是否空,
  6856. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6857. * 经过内置过滤规则处理后的内容。
  6858. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6859. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6860. * @return { String } 编辑器的内容字符串
  6861. * @example
  6862. * ```javascript
  6863. * // editor 是一个编辑器的实例
  6864. * var content = editor.getContent( function ( editor ) {
  6865. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6866. * } );
  6867. * ```
  6868. */
  6869. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6870. var me = this;
  6871. if (cmd && utils.isFunction(cmd)) {
  6872. fn = cmd;
  6873. cmd = '';
  6874. }
  6875. if (fn ? !fn() : !this.hasContents()) {
  6876. return '';
  6877. }
  6878. me.fireEvent('beforegetcontent');
  6879. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6880. me.filterOutputRule(root);
  6881. me.fireEvent('aftergetcontent', cmd,root);
  6882. return root.toHtml(formatter);
  6883. },
  6884. /**
  6885. * 取得完整的html代码,可以直接显示成完整的html文档
  6886. * @method getAllHtml
  6887. * @return { String } 编辑器的内容html文档字符串
  6888. * @eaxmple
  6889. * ```javascript
  6890. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6891. * ```
  6892. */
  6893. getAllHtml: function () {
  6894. var me = this,
  6895. headHtml = [],
  6896. html = '';
  6897. me.fireEvent('getAllHtml', headHtml);
  6898. if (browser.ie && browser.version > 8) {
  6899. var headHtmlForIE9 = '';
  6900. utils.each(me.document.styleSheets, function (si) {
  6901. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6902. });
  6903. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6904. headHtmlForIE9 += si.outerHTML;
  6905. });
  6906. }
  6907. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6908. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6909. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6910. },
  6911. /**
  6912. * 得到编辑器的纯文本内容,但会保留段落格式
  6913. * @method getPlainTxt
  6914. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6915. * @example
  6916. * ```javascript
  6917. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6918. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6919. * ```
  6920. */
  6921. getPlainTxt: function () {
  6922. var reg = new RegExp(domUtils.fillChar, 'g'),
  6923. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6924. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6925. .replace(/<br\/?>/gi, '\n')
  6926. .replace(/<[^>/]+>/g, '')
  6927. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6928. return dtd.$block[c] ? '\n' : b ? b : '';
  6929. });
  6930. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6931. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6932. },
  6933. /**
  6934. * 获取编辑器中的纯文本内容,没有段落格式
  6935. * @method getContentTxt
  6936. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6937. * @example
  6938. * ```javascript
  6939. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6940. * console.log(editor.getPlainTxt()); //输出:"12
  6941. * ```
  6942. */
  6943. getContentTxt: function () {
  6944. var reg = new RegExp(domUtils.fillChar, 'g');
  6945. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6946. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6947. },
  6948. /**
  6949. * 设置编辑器的内容,可修改编辑器当前的html内容
  6950. * @method setContent
  6951. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6952. * @warning 该方法会触发selectionchange事件
  6953. * @param { String } html 要插入的html内容
  6954. * @example
  6955. * ```javascript
  6956. * editor.getContent('<p>test</p>');
  6957. * ```
  6958. */
  6959. /**
  6960. * 设置编辑器的内容,可修改编辑器当前的html内容
  6961. * @method setContent
  6962. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6963. * @warning 该方法会触发selectionchange事件
  6964. * @param { String } html 要插入的html内容
  6965. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6966. * @example
  6967. * ```javascript
  6968. * //假设设置前的编辑器内容是 <p>old text</p>
  6969. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6970. * ```
  6971. */
  6972. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6973. var me = this;
  6974. me.fireEvent('beforesetcontent', html);
  6975. var root = UE.htmlparser(html);
  6976. me.filterInputRule(root);
  6977. html = root.toHtml();
  6978. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6979. function isCdataDiv(node){
  6980. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6981. }
  6982. //给文本或者inline节点套p标签
  6983. if (me.options.enterTag == 'p') {
  6984. var child = this.body.firstChild, tmpNode;
  6985. if (!child || child.nodeType == 1 &&
  6986. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  6987. domUtils.isCustomeNode(child)
  6988. )
  6989. && child === this.body.lastChild) {
  6990. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  6991. } else {
  6992. var p = me.document.createElement('p');
  6993. while (child) {
  6994. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  6995. tmpNode = child.nextSibling;
  6996. p.appendChild(child);
  6997. child = tmpNode;
  6998. }
  6999. if (p.firstChild) {
  7000. if (!child) {
  7001. me.body.appendChild(p);
  7002. break;
  7003. } else {
  7004. child.parentNode.insertBefore(p, child);
  7005. p = me.document.createElement('p');
  7006. }
  7007. }
  7008. child = child.nextSibling;
  7009. }
  7010. }
  7011. }
  7012. me.fireEvent('aftersetcontent');
  7013. me.fireEvent('contentchange');
  7014. !notFireSelectionchange && me._selectionChange();
  7015. //清除保存的选区
  7016. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7017. //trace:1742 setContent后gecko能得到焦点问题
  7018. var geckoSel;
  7019. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7020. geckoSel.removeAllRanges();
  7021. }
  7022. if(me.options.autoSyncData){
  7023. me.form && setValue(me.form,me);
  7024. }
  7025. },
  7026. /**
  7027. * 让编辑器获得焦点,默认focus到编辑器头部
  7028. * @method focus
  7029. * @example
  7030. * ```javascript
  7031. * editor.focus()
  7032. * ```
  7033. */
  7034. /**
  7035. * 让编辑器获得焦点,toEnd确定focus位置
  7036. * @method focus
  7037. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7038. * @example
  7039. * ```javascript
  7040. * editor.focus(true)
  7041. * ```
  7042. */
  7043. focus: function (toEnd) {
  7044. try {
  7045. var me = this,
  7046. rng = me.selection.getRange();
  7047. if (toEnd) {
  7048. var node = me.body.lastChild;
  7049. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7050. if(domUtils.isEmptyBlock(node)){
  7051. rng.setStartAtFirst(node)
  7052. }else{
  7053. rng.setStartAtLast(node)
  7054. }
  7055. rng.collapse(true);
  7056. }
  7057. rng.setCursor(true);
  7058. } else {
  7059. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7060. var node = me.body.firstChild;
  7061. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7062. rng.setStartAtFirst(node).collapse(true);
  7063. }
  7064. }
  7065. rng.select(true);
  7066. }
  7067. this.fireEvent('focus selectionchange');
  7068. } catch (e) {
  7069. }
  7070. },
  7071. isFocus:function(){
  7072. return this.selection.isFocus();
  7073. },
  7074. blur:function(){
  7075. var sel = this.selection.getNative();
  7076. if(sel.empty && browser.ie){
  7077. var nativeRng = document.body.createTextRange();
  7078. nativeRng.moveToElementText(document.body);
  7079. nativeRng.collapse(true);
  7080. nativeRng.select();
  7081. sel.empty()
  7082. }else{
  7083. sel.removeAllRanges()
  7084. }
  7085. //this.fireEvent('blur selectionchange');
  7086. },
  7087. /**
  7088. * 初始化UE事件及部分事件代理
  7089. * @method _initEvents
  7090. * @private
  7091. */
  7092. _initEvents: function () {
  7093. var me = this,
  7094. doc = me.document,
  7095. win = me.window;
  7096. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7097. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7098. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7099. domUtils.on(me.body,'drop',function(e){
  7100. //阻止ff下默认的弹出新页面打开图片
  7101. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7102. me.fireEvent('contentchange')
  7103. });
  7104. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7105. //特殊键不触发selectionchange
  7106. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7107. return;
  7108. }
  7109. if (evt.button == 2)return;
  7110. me._selectionChange(250, evt);
  7111. });
  7112. },
  7113. /**
  7114. * 触发事件代理
  7115. * @method _proxyDomEvent
  7116. * @private
  7117. * @return { * } fireEvent的返回值
  7118. * @see UE.EventBase:fireEvent(String)
  7119. */
  7120. _proxyDomEvent: function (evt) {
  7121. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7122. return false;
  7123. }
  7124. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7125. return false;
  7126. }
  7127. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7128. },
  7129. /**
  7130. * 变化选区
  7131. * @method _selectionChange
  7132. * @private
  7133. */
  7134. _selectionChange: function (delay, evt) {
  7135. var me = this;
  7136. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7137. // if ( !me.selection.isFocus() ){
  7138. // return;
  7139. // }
  7140. var hackForMouseUp = false;
  7141. var mouseX, mouseY;
  7142. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7143. var range = this.selection.getRange();
  7144. if (!range.collapsed) {
  7145. hackForMouseUp = true;
  7146. mouseX = evt.clientX;
  7147. mouseY = evt.clientY;
  7148. }
  7149. }
  7150. clearTimeout(_selectionChangeTimer);
  7151. _selectionChangeTimer = setTimeout(function () {
  7152. if (!me.selection || !me.selection.getNative()) {
  7153. return;
  7154. }
  7155. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7156. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7157. var ieRange;
  7158. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7159. ieRange = me.document.body.createTextRange();
  7160. try {
  7161. ieRange.moveToPoint(mouseX, mouseY);
  7162. } catch (ex) {
  7163. ieRange = null;
  7164. }
  7165. }
  7166. var bakGetIERange;
  7167. if (ieRange) {
  7168. bakGetIERange = me.selection.getIERange;
  7169. me.selection.getIERange = function () {
  7170. return ieRange;
  7171. };
  7172. }
  7173. me.selection.cache();
  7174. if (bakGetIERange) {
  7175. me.selection.getIERange = bakGetIERange;
  7176. }
  7177. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7178. me.fireEvent('beforeselectionchange');
  7179. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7180. me.fireEvent('selectionchange', !!evt);
  7181. me.fireEvent('afterselectionchange');
  7182. me.selection.clear();
  7183. }
  7184. }, delay || 50);
  7185. },
  7186. /**
  7187. * 执行编辑命令
  7188. * @method _callCmdFn
  7189. * @private
  7190. * @param { String } fnName 函数名称
  7191. * @param { * } args 传给命令函数的参数
  7192. * @return { * } 返回命令函数运行的返回值
  7193. */
  7194. _callCmdFn: function (fnName, args) {
  7195. var cmdName = args[0].toLowerCase(),
  7196. cmd, cmdFn;
  7197. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7198. cmdFn = cmd && cmd[fnName];
  7199. //没有querycommandstate或者没有command的都默认返回0
  7200. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7201. return 0;
  7202. } else if (cmdFn) {
  7203. return cmdFn.apply(this, args);
  7204. }
  7205. },
  7206. /**
  7207. * 执行编辑命令cmdName,完成富文本编辑效果
  7208. * @method execCommand
  7209. * @param { String } cmdName 需要执行的命令
  7210. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7211. * @return { * } 返回命令函数运行的返回值
  7212. * @example
  7213. * ```javascript
  7214. * editor.execCommand(cmdName);
  7215. * ```
  7216. */
  7217. execCommand: function (cmdName) {
  7218. cmdName = cmdName.toLowerCase();
  7219. var me = this,
  7220. result,
  7221. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7222. if (!cmd || !cmd.execCommand) {
  7223. return null;
  7224. }
  7225. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7226. me.__hasEnterExecCommand = true;
  7227. if (me.queryCommandState.apply(me,arguments) != -1) {
  7228. me.fireEvent('saveScene');
  7229. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7230. result = this._callCmdFn('execCommand', arguments);
  7231. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7232. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7233. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7234. me.fireEvent('saveScene');
  7235. }
  7236. me.__hasEnterExecCommand = false;
  7237. } else {
  7238. result = this._callCmdFn('execCommand', arguments);
  7239. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7240. }
  7241. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7242. return result;
  7243. },
  7244. /**
  7245. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7246. * @method queryCommandState
  7247. * @param { String } cmdName 需要查询的命令名称
  7248. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7249. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7250. * @example
  7251. * ```javascript
  7252. * editor.queryCommandState(cmdName) => (-1|0|1)
  7253. * ```
  7254. * @see COMMAND.LIST
  7255. */
  7256. queryCommandState: function (cmdName) {
  7257. return this._callCmdFn('queryCommandState', arguments);
  7258. },
  7259. /**
  7260. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7261. * @method queryCommandValue
  7262. * @param { String } cmdName 需要查询的命令名称
  7263. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7264. * @remind 只有部分插件有此方法
  7265. * @return { * } 返回每个命令特定的当前状态值
  7266. * @grammar editor.queryCommandValue(cmdName) => {*}
  7267. * @see COMMAND.LIST
  7268. */
  7269. queryCommandValue: function (cmdName) {
  7270. return this._callCmdFn('queryCommandValue', arguments);
  7271. },
  7272. /**
  7273. * 检查编辑区域中是否有内容
  7274. * @method hasContents
  7275. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7276. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7277. * @return { Boolean } 检查有内容返回true,否则返回false
  7278. * @example
  7279. * ```javascript
  7280. * editor.hasContents()
  7281. * ```
  7282. */
  7283. /**
  7284. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7285. * @method hasContents
  7286. * @param { Array } tags 传入数组判断时用到的节点类型
  7287. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7288. * @example
  7289. * ```javascript
  7290. * editor.hasContents(['span']);
  7291. * ```
  7292. */
  7293. hasContents: function (tags) {
  7294. if (tags) {
  7295. for (var i = 0, ci; ci = tags[i++];) {
  7296. if (this.document.getElementsByTagName(ci).length > 0) {
  7297. return true;
  7298. }
  7299. }
  7300. }
  7301. if (!domUtils.isEmptyBlock(this.body)) {
  7302. return true
  7303. }
  7304. //随时添加,定义的特殊标签如果存在,不能认为是空
  7305. tags = ['div'];
  7306. for (i = 0; ci = tags[i++];) {
  7307. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7308. for (var n = 0, cn; cn = nodes[n++];) {
  7309. if (domUtils.isCustomeNode(cn)) {
  7310. return true;
  7311. }
  7312. }
  7313. }
  7314. return false;
  7315. },
  7316. /**
  7317. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7318. * @method reset
  7319. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7320. * @example
  7321. * ```javascript
  7322. * editor.reset()
  7323. * ```
  7324. */
  7325. reset: function () {
  7326. this.fireEvent('reset');
  7327. },
  7328. /**
  7329. * 设置当前编辑区域可以编辑
  7330. * @method setEnabled
  7331. * @example
  7332. * ```javascript
  7333. * editor.setEnabled()
  7334. * ```
  7335. */
  7336. setEnabled: function () {
  7337. var me = this, range;
  7338. if (me.body.contentEditable == 'false') {
  7339. me.body.contentEditable = true;
  7340. range = me.selection.getRange();
  7341. //有可能内容丢失了
  7342. try {
  7343. range.moveToBookmark(me.lastBk);
  7344. delete me.lastBk
  7345. } catch (e) {
  7346. range.setStartAtFirst(me.body).collapse(true)
  7347. }
  7348. range.select(true);
  7349. if (me.bkqueryCommandState) {
  7350. me.queryCommandState = me.bkqueryCommandState;
  7351. delete me.bkqueryCommandState;
  7352. }
  7353. if (me.bkqueryCommandValue) {
  7354. me.queryCommandValue = me.bkqueryCommandValue;
  7355. delete me.bkqueryCommandValue;
  7356. }
  7357. me.fireEvent('selectionchange');
  7358. }
  7359. },
  7360. enable: function () {
  7361. return this.setEnabled();
  7362. },
  7363. /** 设置当前编辑区域不可编辑
  7364. * @method setDisabled
  7365. */
  7366. /** 设置当前编辑区域不可编辑,except中的命令除外
  7367. * @method setDisabled
  7368. * @param { String } except 例外命令的字符串
  7369. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7370. * @example
  7371. * ```javascript
  7372. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7373. * ```
  7374. */
  7375. /** 设置当前编辑区域不可编辑,except中的命令除外
  7376. * @method setDisabled
  7377. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7378. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7379. * @example
  7380. * ```javascript
  7381. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7382. * ```
  7383. */
  7384. setDisabled: function (except) {
  7385. var me = this;
  7386. except = except ? utils.isArray(except) ? except : [except] : [];
  7387. if (me.body.contentEditable == 'true') {
  7388. if (!me.lastBk) {
  7389. me.lastBk = me.selection.getRange().createBookmark(true);
  7390. }
  7391. me.body.contentEditable = false;
  7392. me.bkqueryCommandState = me.queryCommandState;
  7393. me.bkqueryCommandValue = me.queryCommandValue;
  7394. me.queryCommandState = function (type) {
  7395. if (utils.indexOf(except, type) != -1) {
  7396. return me.bkqueryCommandState.apply(me, arguments);
  7397. }
  7398. return -1;
  7399. };
  7400. me.queryCommandValue = function (type) {
  7401. if (utils.indexOf(except, type) != -1) {
  7402. return me.bkqueryCommandValue.apply(me, arguments);
  7403. }
  7404. return null;
  7405. };
  7406. me.fireEvent('selectionchange');
  7407. }
  7408. },
  7409. disable: function (except) {
  7410. return this.setDisabled(except);
  7411. },
  7412. /**
  7413. * 设置默认内容
  7414. * @method _setDefaultContent
  7415. * @private
  7416. * @param { String } cont 要存入的内容
  7417. */
  7418. _setDefaultContent: function () {
  7419. function clear() {
  7420. var me = this;
  7421. if (me.document.getElementById('initContent')) {
  7422. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7423. me.removeListener('firstBeforeExecCommand focus', clear);
  7424. setTimeout(function () {
  7425. me.focus();
  7426. me._selectionChange();
  7427. }, 0)
  7428. }
  7429. }
  7430. return function (cont) {
  7431. var me = this;
  7432. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7433. me.addListener('firstBeforeExecCommand focus', clear);
  7434. }
  7435. }(),
  7436. /**
  7437. * 显示编辑器
  7438. * @method setShow
  7439. * @example
  7440. * ```javascript
  7441. * editor.setShow()
  7442. * ```
  7443. */
  7444. setShow: function () {
  7445. var me = this, range = me.selection.getRange();
  7446. if (me.container.style.display == 'none') {
  7447. //有可能内容丢失了
  7448. try {
  7449. range.moveToBookmark(me.lastBk);
  7450. delete me.lastBk
  7451. } catch (e) {
  7452. range.setStartAtFirst(me.body).collapse(true)
  7453. }
  7454. //ie下focus实效,所以做了个延迟
  7455. setTimeout(function () {
  7456. range.select(true);
  7457. }, 100);
  7458. me.container.style.display = '';
  7459. }
  7460. },
  7461. show: function () {
  7462. return this.setShow();
  7463. },
  7464. /**
  7465. * 隐藏编辑器
  7466. * @method setHide
  7467. * @example
  7468. * ```javascript
  7469. * editor.setHide()
  7470. * ```
  7471. */
  7472. setHide: function () {
  7473. var me = this;
  7474. if (!me.lastBk) {
  7475. me.lastBk = me.selection.getRange().createBookmark(true);
  7476. }
  7477. me.container.style.display = 'none'
  7478. },
  7479. hide: function () {
  7480. return this.setHide();
  7481. },
  7482. /**
  7483. * 根据指定的路径,获取对应的语言资源
  7484. * @method getLang
  7485. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7486. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7487. * @example
  7488. * ```javascript
  7489. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7490. * ```
  7491. */
  7492. getLang: function (path) {
  7493. var lang = UE.I18N[this.options.lang];
  7494. if (!lang) {
  7495. throw Error("not import language file");
  7496. }
  7497. path = (path || "").split(".");
  7498. for (var i = 0, ci; ci = path[i++];) {
  7499. lang = lang[ci];
  7500. if (!lang)break;
  7501. }
  7502. return lang;
  7503. },
  7504. /**
  7505. * 计算编辑器html内容字符串的长度
  7506. * @method getContentLength
  7507. * @return { Number } 返回计算的长度
  7508. * @example
  7509. * ```javascript
  7510. * //编辑器html内容<p><strong>132</strong></p>
  7511. * editor.getContentLength() //返回27
  7512. * ```
  7513. */
  7514. /**
  7515. * 计算编辑器当前纯文本内容的长度
  7516. * @method getContentLength
  7517. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7518. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7519. * @example
  7520. * ```javascript
  7521. * //编辑器html内容<p><strong>132</strong></p>
  7522. * editor.getContentLength() //返回3
  7523. * ```
  7524. */
  7525. getContentLength: function (ingoneHtml, tagNames) {
  7526. var count = this.getContent(false,false,true).length;
  7527. if (ingoneHtml) {
  7528. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7529. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7530. for (var i = 0, ci; ci = tagNames[i++];) {
  7531. count += this.document.getElementsByTagName(ci).length;
  7532. }
  7533. }
  7534. return count;
  7535. },
  7536. /**
  7537. * 注册输入过滤规则
  7538. * @method addInputRule
  7539. * @param { Function } rule 要添加的过滤规则
  7540. * @example
  7541. * ```javascript
  7542. * editor.addInputRule(function(root){
  7543. * $.each(root.getNodesByTagName('div'),function(i,node){
  7544. * node.tagName="p";
  7545. * });
  7546. * });
  7547. * ```
  7548. */
  7549. addInputRule: function (rule) {
  7550. this.inputRules.push(rule);
  7551. },
  7552. /**
  7553. * 执行注册的过滤规则
  7554. * @method filterInputRule
  7555. * @param { UE.uNode } root 要过滤的uNode节点
  7556. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7557. * @example
  7558. * ```javascript
  7559. * editor.filterInputRule(editor.body);
  7560. * ```
  7561. * @see UE.Editor:addInputRule
  7562. */
  7563. filterInputRule: function (root) {
  7564. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7565. ci.call(this, root)
  7566. }
  7567. },
  7568. /**
  7569. * 注册输出过滤规则
  7570. * @method addOutputRule
  7571. * @param { Function } rule 要添加的过滤规则
  7572. * @example
  7573. * ```javascript
  7574. * editor.addOutputRule(function(root){
  7575. * $.each(root.getNodesByTagName('p'),function(i,node){
  7576. * node.tagName="div";
  7577. * });
  7578. * });
  7579. * ```
  7580. */
  7581. addOutputRule: function (rule) {
  7582. this.outputRules.push(rule)
  7583. },
  7584. /**
  7585. * 根据输出过滤规则,过滤编辑器内容
  7586. * @method filterOutputRule
  7587. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7588. * @param { UE.uNode } root 要过滤的uNode节点
  7589. * @example
  7590. * ```javascript
  7591. * editor.filterOutputRule(editor.body);
  7592. * ```
  7593. * @see UE.Editor:addOutputRule
  7594. */
  7595. filterOutputRule: function (root) {
  7596. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7597. ci.call(this, root)
  7598. }
  7599. },
  7600. /**
  7601. * 根据action名称获取请求的路径
  7602. * @method getActionUrl
  7603. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7604. * @param { String } action action名称
  7605. * @example
  7606. * ```javascript
  7607. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7608. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7609. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7610. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7611. * ```
  7612. */
  7613. getActionUrl: function(action){
  7614. var actionName = this.getOpt(action) || action,
  7615. imageUrl = this.getOpt('imageUrl'),
  7616. serverUrl = this.getOpt('serverUrl');
  7617. if(!serverUrl && imageUrl) {
  7618. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7619. }
  7620. if(serverUrl) {
  7621. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&') + 'action=' + (actionName || '');
  7622. return utils.formatUrl(serverUrl);
  7623. } else {
  7624. return '';
  7625. }
  7626. }
  7627. };
  7628. utils.inherits(Editor, EventBase);
  7629. })();
  7630. // core/Editor.defaultoptions.js
  7631. //维护编辑器一下默认的不在插件中的配置项
  7632. UE.Editor.defaultOptions = function(editor){
  7633. var _url = editor.options.UEDITOR_HOME_URL;
  7634. return {
  7635. isShow: true,
  7636. initialContent: '',
  7637. initialStyle:'',
  7638. autoClearinitialContent: false,
  7639. iframeCssUrl: _url + 'themes/iframe.css',
  7640. textarea: 'editorValue',
  7641. focus: false,
  7642. focusInEnd: true,
  7643. autoClearEmptyNode: true,
  7644. fullscreen: false,
  7645. readonly: false,
  7646. zIndex: 999,
  7647. imagePopup: true,
  7648. enterTag: 'p',
  7649. customDomain: false,
  7650. lang: 'zh-cn',
  7651. langPath: _url + 'lang/',
  7652. theme: 'default',
  7653. themePath: _url + 'themes/',
  7654. allHtmlEnabled: false,
  7655. scaleEnabled: false,
  7656. tableNativeEditInFF: false,
  7657. autoSyncData : true,
  7658. fileNameFormat: '{time}{rand:6}'
  7659. }
  7660. };
  7661. // core/loadconfig.js
  7662. (function(){
  7663. UE.Editor.prototype.loadServerConfig = function(){
  7664. var me = this;
  7665. setTimeout(function(){
  7666. try{
  7667. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7668. var configUrl = me.getActionUrl('config'),
  7669. isJsonp = utils.isCrossDomainUrl(configUrl);
  7670. /* 发出ajax请求 */
  7671. me._serverConfigLoaded = false;
  7672. configUrl && UE.ajax.request(configUrl,{
  7673. 'method': 'GET',
  7674. 'dataType': isJsonp ? 'jsonp':'',
  7675. 'onsuccess':function(r){
  7676. try {
  7677. var config = isJsonp ? r:eval("("+r.responseText+")");
  7678. utils.extend(me.options, config);
  7679. me.fireEvent('serverConfigLoaded');
  7680. me._serverConfigLoaded = true;
  7681. } catch (e) {
  7682. showErrorMsg(me.getLang('loadconfigFormatError'));
  7683. }
  7684. },
  7685. 'onerror':function(){
  7686. showErrorMsg(me.getLang('loadconfigHttpError'));
  7687. }
  7688. });
  7689. } catch(e){
  7690. showErrorMsg(me.getLang('loadconfigError'));
  7691. }
  7692. });
  7693. function showErrorMsg(msg) {
  7694. console && console.error(msg);
  7695. //me.fireEvent('showMessage', {
  7696. // 'title': msg,
  7697. // 'type': 'error'
  7698. //});
  7699. }
  7700. };
  7701. UE.Editor.prototype.isServerConfigLoaded = function(){
  7702. var me = this;
  7703. return me._serverConfigLoaded || false;
  7704. };
  7705. UE.Editor.prototype.afterConfigReady = function(handler){
  7706. if (!handler || !utils.isFunction(handler)) return;
  7707. var me = this;
  7708. var readyHandler = function(){
  7709. handler.apply(me, arguments);
  7710. me.removeListener('serverConfigLoaded', readyHandler);
  7711. };
  7712. if (me.isServerConfigLoaded()) {
  7713. handler.call(me, 'serverConfigLoaded');
  7714. } else {
  7715. me.addListener('serverConfigLoaded', readyHandler);
  7716. }
  7717. };
  7718. })();
  7719. // core/ajax.js
  7720. /**
  7721. * @file
  7722. * @module UE.ajax
  7723. * @since 1.2.6.1
  7724. */
  7725. /**
  7726. * 提供对ajax请求的支持
  7727. * @module UE.ajax
  7728. */
  7729. UE.ajax = function() {
  7730. //创建一个ajaxRequest对象
  7731. var fnStr = 'XMLHttpRequest()';
  7732. try {
  7733. new ActiveXObject("Msxml2.XMLHTTP");
  7734. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7735. } catch (e) {
  7736. try {
  7737. new ActiveXObject("Microsoft.XMLHTTP");
  7738. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7739. } catch (e) {
  7740. }
  7741. }
  7742. var creatAjaxRequest = new Function('return new ' + fnStr);
  7743. /**
  7744. * 将json参数转化成适合ajax提交的参数列表
  7745. * @param json
  7746. */
  7747. function json2str(json) {
  7748. var strArr = [];
  7749. for (var i in json) {
  7750. //忽略默认的几个参数
  7751. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7752. //忽略控制
  7753. if(json[i] == undefined || json[i] == null) continue;
  7754. //传递过来的对象和函数不在提交之列
  7755. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7756. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7757. } else if (utils.isArray(json[i])) {
  7758. //支持传数组内容
  7759. for(var j = 0; j < json[i].length; j++) {
  7760. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7761. }
  7762. }
  7763. }
  7764. return strArr.join("&");
  7765. }
  7766. function doAjax(url, ajaxOptions) {
  7767. var xhr = creatAjaxRequest(),
  7768. //是否超时
  7769. timeIsOut = false,
  7770. //默认参数
  7771. defaultAjaxOptions = {
  7772. method:"POST",
  7773. timeout:5000,
  7774. async:true,
  7775. data:{},//需要传递对象的话只能覆盖
  7776. onsuccess:function() {
  7777. },
  7778. onerror:function() {
  7779. }
  7780. };
  7781. if (typeof url === "object") {
  7782. ajaxOptions = url;
  7783. url = ajaxOptions.url;
  7784. }
  7785. if (!xhr || !url) return;
  7786. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7787. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7788. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7789. if (!utils.isEmptyObject(ajaxOpts.data)){
  7790. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7791. }
  7792. //超时检测
  7793. var timerID = setTimeout(function() {
  7794. if (xhr.readyState != 4) {
  7795. timeIsOut = true;
  7796. xhr.abort();
  7797. clearTimeout(timerID);
  7798. }
  7799. }, ajaxOpts.timeout);
  7800. var method = ajaxOpts.method.toUpperCase();
  7801. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7802. xhr.open(method, str, ajaxOpts.async);
  7803. xhr.onreadystatechange = function() {
  7804. if (xhr.readyState == 4) {
  7805. if (!timeIsOut && xhr.status == 200) {
  7806. ajaxOpts.onsuccess(xhr);
  7807. } else {
  7808. ajaxOpts.onerror(xhr);
  7809. }
  7810. }
  7811. };
  7812. if (method == "POST") {
  7813. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7814. xhr.send(submitStr);
  7815. } else {
  7816. xhr.send(null);
  7817. }
  7818. }
  7819. function doJsonp(url, opts) {
  7820. var successhandler = opts.onsuccess || function(){},
  7821. scr = document.createElement('SCRIPT'),
  7822. options = opts || {},
  7823. charset = options['charset'],
  7824. callbackField = options['jsonp'] || 'callback',
  7825. callbackFnName,
  7826. timeOut = options['timeOut'] || 0,
  7827. timer,
  7828. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7829. matches;
  7830. if (utils.isFunction(successhandler)) {
  7831. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7832. window[callbackFnName] = getCallBack(0);
  7833. } else if(utils.isString(successhandler)){
  7834. callbackFnName = successhandler;
  7835. } else {
  7836. if (matches = reg.exec(url)) {
  7837. callbackFnName = matches[2];
  7838. }
  7839. }
  7840. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7841. if (url.search(reg) < 0) {
  7842. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7843. }
  7844. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7845. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7846. if (!utils.isEmptyObject(opts.data)){
  7847. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7848. }
  7849. if (queryStr) {
  7850. url = url.replace(/\?/, '?' + queryStr + '&');
  7851. }
  7852. scr.onerror = getCallBack(1);
  7853. if( timeOut ){
  7854. timer = setTimeout(getCallBack(1), timeOut);
  7855. }
  7856. createScriptTag(scr, url, charset);
  7857. function createScriptTag(scr, url, charset) {
  7858. scr.setAttribute('type', 'text/javascript');
  7859. scr.setAttribute('defer', 'defer');
  7860. charset && scr.setAttribute('charset', charset);
  7861. scr.setAttribute('src', url);
  7862. document.getElementsByTagName('head')[0].appendChild(scr);
  7863. }
  7864. function getCallBack(onTimeOut){
  7865. return function(){
  7866. try {
  7867. if(onTimeOut){
  7868. options.onerror && options.onerror();
  7869. }else{
  7870. try{
  7871. clearTimeout(timer);
  7872. successhandler.apply(window, arguments);
  7873. } catch (e){}
  7874. }
  7875. } catch (exception) {
  7876. options.onerror && options.onerror.call(window, exception);
  7877. } finally {
  7878. options.oncomplete && options.oncomplete.apply(window, arguments);
  7879. scr.parentNode && scr.parentNode.removeChild(scr);
  7880. window[callbackFnName] = null;
  7881. try {
  7882. delete window[callbackFnName];
  7883. }catch(e){}
  7884. }
  7885. }
  7886. }
  7887. }
  7888. return {
  7889. /**
  7890. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7891. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7892. * @method request
  7893. * @param { URLString } url ajax请求的url地址
  7894. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7895. * @example
  7896. * ```javascript
  7897. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7898. * UE.ajax.requeset( 'sayhello.php', {
  7899. *
  7900. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7901. * method: 'GET',
  7902. *
  7903. * //超时时间。 默认为5000, 单位是ms
  7904. * timeout: 10000,
  7905. *
  7906. * //是否是异步请求。 true为异步请求, false为同步请求
  7907. * async: true,
  7908. *
  7909. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7910. * data: {
  7911. * name: 'ueditor'
  7912. * },
  7913. *
  7914. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7915. * onsuccess: function ( xhr ) {
  7916. * console.log( xhr.responseText );
  7917. * },
  7918. *
  7919. * //请求失败或者超时后的回调。
  7920. * onerror: function ( xhr ) {
  7921. * alert( 'Ajax请求失败' );
  7922. * }
  7923. *
  7924. * } );
  7925. * ```
  7926. */
  7927. /**
  7928. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7929. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7930. * @method request
  7931. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7932. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7933. * @example
  7934. * ```javascript
  7935. *
  7936. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7937. * UE.ajax.requeset( 'sayhello.php', {
  7938. *
  7939. * //请求的地址, 该项是必须的。
  7940. * url: 'sayhello.php'
  7941. *
  7942. * } );
  7943. * ```
  7944. */
  7945. request:function(url, opts) {
  7946. if (opts && opts.dataType == 'jsonp') {
  7947. doJsonp(url, opts);
  7948. } else {
  7949. doAjax(url, opts);
  7950. }
  7951. },
  7952. getJSONP:function(url, data, fn) {
  7953. var opts = {
  7954. 'data': data,
  7955. 'oncomplete': fn
  7956. };
  7957. doJsonp(url, opts);
  7958. }
  7959. };
  7960. }();
  7961. // core/filterword.js
  7962. /**
  7963. * UE过滤word的静态方法
  7964. * @file
  7965. */
  7966. /**
  7967. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7968. * @module UE
  7969. */
  7970. /**
  7971. * 根据传入html字符串过滤word
  7972. * @module UE
  7973. * @since 1.2.6.1
  7974. * @method filterWord
  7975. * @param { String } html html字符串
  7976. * @return { String } 已过滤后的结果字符串
  7977. * @example
  7978. * ```javascript
  7979. * UE.filterWord(html);
  7980. * ```
  7981. */
  7982. var filterWord = UE.filterWord = function () {
  7983. //是否是word过来的内容
  7984. function isWordDocument( str ) {
  7985. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  7986. }
  7987. //去掉小数
  7988. function transUnit( v ) {
  7989. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  7990. return utils.transUnitToPx(m);
  7991. } );
  7992. return v;
  7993. }
  7994. function filterPasteWord( str ) {
  7995. return str.replace(/[\t\r\n]+/g,' ')
  7996. .replace( /<!--[\s\S]*?-->/ig, "" )
  7997. //转换图片
  7998. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  7999. //opera能自己解析出image所这里直接返回空
  8000. if(browser.opera){
  8001. return '';
  8002. }
  8003. try{
  8004. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8005. if(/Bitmap/i.test(str)){
  8006. return '';
  8007. }
  8008. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8009. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8010. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8011. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  8012. } catch(e){
  8013. return '';
  8014. }
  8015. })
  8016. //针对wps添加的多余标签处理
  8017. .replace(/<\/?div[^>]*>/g,'')
  8018. //去掉多余的属性
  8019. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8020. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8021. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8022. //去掉多余的属性
  8023. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8024. //保留list的标示
  8025. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8026. })
  8027. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8028. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8029. return c.replace(/[\t\r\n ]+/g,' ')
  8030. })
  8031. //处理style的问题
  8032. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8033. var n = [],
  8034. s = style.replace( /^\s+|\s+$/, '' )
  8035. .replace(/&#39;/g,'\'')
  8036. .replace( /&quot;/gi, "'" )
  8037. .replace(/[\d.]+(cm|pt)/g,function(str){
  8038. return utils.transUnitToPx(str)
  8039. })
  8040. .split( /;\s*/g );
  8041. for ( var i = 0,v; v = s[i];i++ ) {
  8042. var name, value,
  8043. parts = v.split( ":" );
  8044. if ( parts.length == 2 ) {
  8045. name = parts[0].toLowerCase();
  8046. value = parts[1].toLowerCase();
  8047. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8048. ||
  8049. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8050. ){
  8051. continue;
  8052. }
  8053. switch ( name ) {
  8054. case "mso-padding-alt":
  8055. case "mso-padding-top-alt":
  8056. case "mso-padding-right-alt":
  8057. case "mso-padding-bottom-alt":
  8058. case "mso-padding-left-alt":
  8059. case "mso-margin-alt":
  8060. case "mso-margin-top-alt":
  8061. case "mso-margin-right-alt":
  8062. case "mso-margin-bottom-alt":
  8063. case "mso-margin-left-alt":
  8064. //ie下会出现挤到一起的情况
  8065. //case "mso-table-layout-alt":
  8066. case "mso-height":
  8067. case "mso-width":
  8068. case "mso-vertical-align-alt":
  8069. //trace:1819 ff下会解析出padding在table上
  8070. if(!/<table/.test(tag))
  8071. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8072. continue;
  8073. case "horiz-align":
  8074. n[i] = "text-align:" + value;
  8075. continue;
  8076. case "vert-align":
  8077. n[i] = "vertical-align:" + value;
  8078. continue;
  8079. case "font-color":
  8080. case "mso-foreground":
  8081. n[i] = "color:" + value;
  8082. continue;
  8083. case "mso-background":
  8084. case "mso-highlight":
  8085. n[i] = "background:" + value;
  8086. continue;
  8087. case "mso-default-height":
  8088. n[i] = "min-height:" + transUnit( value );
  8089. continue;
  8090. case "mso-default-width":
  8091. n[i] = "min-width:" + transUnit( value );
  8092. continue;
  8093. case "mso-padding-between-alt":
  8094. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8095. continue;
  8096. case "text-line-through":
  8097. if ( (value == "single") || (value == "double") ) {
  8098. n[i] = "text-decoration:line-through";
  8099. }
  8100. continue;
  8101. case "mso-zero-height":
  8102. if ( value == "yes" ) {
  8103. n[i] = "display:none";
  8104. }
  8105. continue;
  8106. // case 'background':
  8107. // break;
  8108. case 'margin':
  8109. if ( !/[1-9]/.test( value ) ) {
  8110. continue;
  8111. }
  8112. }
  8113. 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 )
  8114. ||
  8115. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8116. ) {
  8117. continue;
  8118. }
  8119. n[i] = name + ":" + parts[1];
  8120. }
  8121. }
  8122. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8123. })
  8124. }
  8125. return function ( html ) {
  8126. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8127. };
  8128. }();
  8129. // core/node.js
  8130. /**
  8131. * 编辑器模拟的节点类
  8132. * @file
  8133. * @module UE
  8134. * @class uNode
  8135. * @since 1.2.6.1
  8136. */
  8137. /**
  8138. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8139. * @unfile
  8140. * @module UE
  8141. */
  8142. (function () {
  8143. /**
  8144. * 编辑器模拟的节点类
  8145. * @unfile
  8146. * @module UE
  8147. * @class uNode
  8148. */
  8149. /**
  8150. * 通过一个键值对,创建一个uNode对象
  8151. * @constructor
  8152. * @param { Object } attr 传入要创建的uNode的初始属性
  8153. * @example
  8154. * ```javascript
  8155. * var node = new uNode({
  8156. * type:'element',
  8157. * tagName:'span',
  8158. * attrs:{style:'font-size:14px;'}
  8159. * }
  8160. * ```
  8161. */
  8162. var uNode = UE.uNode = function (obj) {
  8163. this.type = obj.type;
  8164. this.data = obj.data;
  8165. this.tagName = obj.tagName;
  8166. this.parentNode = obj.parentNode;
  8167. this.attrs = obj.attrs || {};
  8168. this.children = obj.children;
  8169. };
  8170. var notTransAttrs = {
  8171. 'href':1,
  8172. 'src':1,
  8173. '_src':1,
  8174. '_href':1,
  8175. 'cdata_data':1
  8176. };
  8177. var notTransTagName = {
  8178. style:1,
  8179. script:1
  8180. };
  8181. var indentChar = ' ',
  8182. breakChar = '\n';
  8183. function insertLine(arr, current, begin) {
  8184. arr.push(breakChar);
  8185. return current + (begin ? 1 : -1);
  8186. }
  8187. function insertIndent(arr, current) {
  8188. //插入缩进
  8189. for (var i = 0; i < current; i++) {
  8190. arr.push(indentChar);
  8191. }
  8192. }
  8193. //创建uNode的静态方法
  8194. //支持标签和html
  8195. uNode.createElement = function (html) {
  8196. if (/[<>]/.test(html)) {
  8197. return UE.htmlparser(html).children[0]
  8198. } else {
  8199. return new uNode({
  8200. type:'element',
  8201. children:[],
  8202. tagName:html
  8203. })
  8204. }
  8205. };
  8206. uNode.createText = function (data,noTrans) {
  8207. return new UE.uNode({
  8208. type:'text',
  8209. 'data':noTrans ? data : utils.unhtml(data || '')
  8210. })
  8211. };
  8212. function nodeToHtml(node, arr, formatter, current) {
  8213. switch (node.type) {
  8214. case 'root':
  8215. for (var i = 0, ci; ci = node.children[i++];) {
  8216. //插入新行
  8217. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8218. insertLine(arr, current, true);
  8219. insertIndent(arr, current)
  8220. }
  8221. nodeToHtml(ci, arr, formatter, current)
  8222. }
  8223. break;
  8224. case 'text':
  8225. isText(node, arr);
  8226. break;
  8227. case 'element':
  8228. isElement(node, arr, formatter, current);
  8229. break;
  8230. case 'comment':
  8231. isComment(node, arr, formatter);
  8232. }
  8233. return arr;
  8234. }
  8235. function isText(node, arr) {
  8236. if(node.parentNode.tagName == 'pre'){
  8237. //源码模式下输入html标签,不能做转换处理,直接输出
  8238. arr.push(node.data)
  8239. }else{
  8240. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8241. }
  8242. }
  8243. function isElement(node, arr, formatter, current) {
  8244. var attrhtml = '';
  8245. if (node.attrs) {
  8246. attrhtml = [];
  8247. var attrs = node.attrs;
  8248. for (var a in attrs) {
  8249. //这里就针对
  8250. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8251. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8252. //有可能做的不够
  8253. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8254. return '&quot;'
  8255. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8256. }
  8257. attrhtml = attrhtml.join(' ');
  8258. }
  8259. arr.push('<' + node.tagName +
  8260. (attrhtml ? ' ' + attrhtml : '') +
  8261. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8262. );
  8263. //插入新行
  8264. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8265. if(node.children && node.children.length){
  8266. current = insertLine(arr, current, true);
  8267. insertIndent(arr, current)
  8268. }
  8269. }
  8270. if (node.children && node.children.length) {
  8271. for (var i = 0, ci; ci = node.children[i++];) {
  8272. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8273. insertLine(arr, current);
  8274. insertIndent(arr, current)
  8275. }
  8276. nodeToHtml(ci, arr, formatter, current)
  8277. }
  8278. }
  8279. if (!dtd.$empty[node.tagName]) {
  8280. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8281. if(node.children && node.children.length){
  8282. current = insertLine(arr, current);
  8283. insertIndent(arr, current)
  8284. }
  8285. }
  8286. arr.push('<\/' + node.tagName + '>');
  8287. }
  8288. }
  8289. function isComment(node, arr) {
  8290. arr.push('<!--' + node.data + '-->');
  8291. }
  8292. function getNodeById(root, id) {
  8293. var node;
  8294. if (root.type == 'element' && root.getAttr('id') == id) {
  8295. return root;
  8296. }
  8297. if (root.children && root.children.length) {
  8298. for (var i = 0, ci; ci = root.children[i++];) {
  8299. if (node = getNodeById(ci, id)) {
  8300. return node;
  8301. }
  8302. }
  8303. }
  8304. }
  8305. function getNodesByTagName(node, tagName, arr) {
  8306. if (node.type == 'element' && node.tagName == tagName) {
  8307. arr.push(node);
  8308. }
  8309. if (node.children && node.children.length) {
  8310. for (var i = 0, ci; ci = node.children[i++];) {
  8311. getNodesByTagName(ci, tagName, arr)
  8312. }
  8313. }
  8314. }
  8315. function nodeTraversal(root,fn){
  8316. if(root.children && root.children.length){
  8317. for(var i= 0,ci;ci=root.children[i];){
  8318. nodeTraversal(ci,fn);
  8319. //ci被替换的情况,这里就不再走 fn了
  8320. if(ci.parentNode ){
  8321. if(ci.children && ci.children.length){
  8322. fn(ci)
  8323. }
  8324. if(ci.parentNode) i++
  8325. }
  8326. }
  8327. }else{
  8328. fn(root)
  8329. }
  8330. }
  8331. uNode.prototype = {
  8332. /**
  8333. * 当前节点对象,转换成html文本
  8334. * @method toHtml
  8335. * @return { String } 返回转换后的html字符串
  8336. * @example
  8337. * ```javascript
  8338. * node.toHtml();
  8339. * ```
  8340. */
  8341. /**
  8342. * 当前节点对象,转换成html文本
  8343. * @method toHtml
  8344. * @param { Boolean } formatter 是否格式化返回值
  8345. * @return { String } 返回转换后的html字符串
  8346. * @example
  8347. * ```javascript
  8348. * node.toHtml( true );
  8349. * ```
  8350. */
  8351. toHtml:function (formatter) {
  8352. var arr = [];
  8353. nodeToHtml(this, arr, formatter, 0);
  8354. return arr.join('')
  8355. },
  8356. /**
  8357. * 获取节点的html内容
  8358. * @method innerHTML
  8359. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8360. * @return { String } 返回节点的html内容
  8361. * @example
  8362. * ```javascript
  8363. * var htmlstr = node.innerHTML();
  8364. * ```
  8365. */
  8366. /**
  8367. * 设置节点的html内容
  8368. * @method innerHTML
  8369. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8370. * @param { String } htmlstr 传入要设置的html内容
  8371. * @return { UE.uNode } 返回节点本身
  8372. * @example
  8373. * ```javascript
  8374. * node.innerHTML('<span>text</span>');
  8375. * ```
  8376. */
  8377. innerHTML:function (htmlstr) {
  8378. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8379. return this;
  8380. }
  8381. if (utils.isString(htmlstr)) {
  8382. if(this.children){
  8383. for (var i = 0, ci; ci = this.children[i++];) {
  8384. ci.parentNode = null;
  8385. }
  8386. }
  8387. this.children = [];
  8388. var tmpRoot = UE.htmlparser(htmlstr);
  8389. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8390. this.children.push(ci);
  8391. ci.parentNode = this;
  8392. }
  8393. return this;
  8394. } else {
  8395. var tmpRoot = new UE.uNode({
  8396. type:'root',
  8397. children:this.children
  8398. });
  8399. return tmpRoot.toHtml();
  8400. }
  8401. },
  8402. /**
  8403. * 获取节点的纯文本内容
  8404. * @method innerText
  8405. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8406. * @return { String } 返回节点的存文本内容
  8407. * @example
  8408. * ```javascript
  8409. * var textStr = node.innerText();
  8410. * ```
  8411. */
  8412. /**
  8413. * 设置节点的纯文本内容
  8414. * @method innerText
  8415. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8416. * @param { String } textStr 传入要设置的文本内容
  8417. * @return { UE.uNode } 返回节点本身
  8418. * @example
  8419. * ```javascript
  8420. * node.innerText('<span>text</span>');
  8421. * ```
  8422. */
  8423. innerText:function (textStr,noTrans) {
  8424. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8425. return this;
  8426. }
  8427. if (textStr) {
  8428. if(this.children){
  8429. for (var i = 0, ci; ci = this.children[i++];) {
  8430. ci.parentNode = null;
  8431. }
  8432. }
  8433. this.children = [];
  8434. this.appendChild(uNode.createText(textStr,noTrans));
  8435. return this;
  8436. } else {
  8437. return this.toHtml().replace(/<[^>]+>/g, '');
  8438. }
  8439. },
  8440. /**
  8441. * 获取当前对象的data属性
  8442. * @method getData
  8443. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8444. * @example
  8445. * ```javascript
  8446. * node.getData();
  8447. * ```
  8448. */
  8449. getData:function () {
  8450. if (this.type == 'element')
  8451. return '';
  8452. return this.data
  8453. },
  8454. /**
  8455. * 获取当前节点下的第一个子节点
  8456. * @method firstChild
  8457. * @return { UE.uNode } 返回第一个子节点
  8458. * @example
  8459. * ```javascript
  8460. * node.firstChild(); //返回第一个子节点
  8461. * ```
  8462. */
  8463. firstChild:function () {
  8464. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8465. // return this;
  8466. // }
  8467. return this.children ? this.children[0] : null;
  8468. },
  8469. /**
  8470. * 获取当前节点下的最后一个子节点
  8471. * @method lastChild
  8472. * @return { UE.uNode } 返回最后一个子节点
  8473. * @example
  8474. * ```javascript
  8475. * node.lastChild(); //返回最后一个子节点
  8476. * ```
  8477. */
  8478. lastChild:function () {
  8479. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8480. // return this;
  8481. // }
  8482. return this.children ? this.children[this.children.length - 1] : null;
  8483. },
  8484. /**
  8485. * 获取和当前节点有相同父亲节点的前一个节点
  8486. * @method previousSibling
  8487. * @return { UE.uNode } 返回前一个节点
  8488. * @example
  8489. * ```javascript
  8490. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8491. * ```
  8492. */
  8493. previousSibling : function(){
  8494. var parent = this.parentNode;
  8495. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8496. if (ci === this) {
  8497. return i == 0 ? null : parent.children[i-1];
  8498. }
  8499. }
  8500. },
  8501. /**
  8502. * 获取和当前节点有相同父亲节点的后一个节点
  8503. * @method nextSibling
  8504. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8505. * @example
  8506. * ```javascript
  8507. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8508. * ```
  8509. */
  8510. nextSibling : function(){
  8511. var parent = this.parentNode;
  8512. for (var i = 0, ci; ci = parent.children[i++];) {
  8513. if (ci === this) {
  8514. return parent.children[i];
  8515. }
  8516. }
  8517. },
  8518. /**
  8519. * 用新的节点替换当前节点
  8520. * @method replaceChild
  8521. * @param { UE.uNode } target 要替换成该节点参数
  8522. * @param { UE.uNode } source 要被替换掉的节点
  8523. * @return { UE.uNode } 返回替换之后的节点对象
  8524. * @example
  8525. * ```javascript
  8526. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8527. * ```
  8528. */
  8529. replaceChild:function (target, source) {
  8530. if (this.children) {
  8531. if(target.parentNode){
  8532. target.parentNode.removeChild(target);
  8533. }
  8534. for (var i = 0, ci; ci = this.children[i]; i++) {
  8535. if (ci === source) {
  8536. this.children.splice(i, 1, target);
  8537. source.parentNode = null;
  8538. target.parentNode = this;
  8539. return target;
  8540. }
  8541. }
  8542. }
  8543. },
  8544. /**
  8545. * 在节点的子节点列表最后位置插入一个节点
  8546. * @method appendChild
  8547. * @param { UE.uNode } node 要插入的节点
  8548. * @return { UE.uNode } 返回刚插入的子节点
  8549. * @example
  8550. * ```javascript
  8551. * node.appendChild( newNode ); //在node内插入子节点newNode
  8552. * ```
  8553. */
  8554. appendChild:function (node) {
  8555. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8556. if (!this.children) {
  8557. this.children = []
  8558. }
  8559. if(node.parentNode){
  8560. node.parentNode.removeChild(node);
  8561. }
  8562. for (var i = 0, ci; ci = this.children[i]; i++) {
  8563. if (ci === node) {
  8564. this.children.splice(i, 1);
  8565. break;
  8566. }
  8567. }
  8568. this.children.push(node);
  8569. node.parentNode = this;
  8570. return node;
  8571. }
  8572. },
  8573. /**
  8574. * 在传入节点的前面插入一个节点
  8575. * @method insertBefore
  8576. * @param { UE.uNode } target 要插入的节点
  8577. * @param { UE.uNode } source 在该参数节点前面插入
  8578. * @return { UE.uNode } 返回刚插入的子节点
  8579. * @example
  8580. * ```javascript
  8581. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8582. * ```
  8583. */
  8584. insertBefore:function (target, source) {
  8585. if (this.children) {
  8586. if(target.parentNode){
  8587. target.parentNode.removeChild(target);
  8588. }
  8589. for (var i = 0, ci; ci = this.children[i]; i++) {
  8590. if (ci === source) {
  8591. this.children.splice(i, 0, target);
  8592. target.parentNode = this;
  8593. return target;
  8594. }
  8595. }
  8596. }
  8597. },
  8598. /**
  8599. * 在传入节点的后面插入一个节点
  8600. * @method insertAfter
  8601. * @param { UE.uNode } target 要插入的节点
  8602. * @param { UE.uNode } source 在该参数节点后面插入
  8603. * @return { UE.uNode } 返回刚插入的子节点
  8604. * @example
  8605. * ```javascript
  8606. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8607. * ```
  8608. */
  8609. insertAfter:function (target, source) {
  8610. if (this.children) {
  8611. if(target.parentNode){
  8612. target.parentNode.removeChild(target);
  8613. }
  8614. for (var i = 0, ci; ci = this.children[i]; i++) {
  8615. if (ci === source) {
  8616. this.children.splice(i + 1, 0, target);
  8617. target.parentNode = this;
  8618. return target;
  8619. }
  8620. }
  8621. }
  8622. },
  8623. /**
  8624. * 从当前节点的子节点列表中,移除节点
  8625. * @method removeChild
  8626. * @param { UE.uNode } node 要移除的节点引用
  8627. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8628. * @return { * } 返回刚移除的子节点
  8629. * @example
  8630. * ```javascript
  8631. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8632. * ```
  8633. */
  8634. removeChild:function (node,keepChildren) {
  8635. if (this.children) {
  8636. for (var i = 0, ci; ci = this.children[i]; i++) {
  8637. if (ci === node) {
  8638. this.children.splice(i, 1);
  8639. ci.parentNode = null;
  8640. if(keepChildren && ci.children && ci.children.length){
  8641. for(var j= 0,cj;cj=ci.children[j];j++){
  8642. this.children.splice(i+j,0,cj);
  8643. cj.parentNode = this;
  8644. }
  8645. }
  8646. return ci;
  8647. }
  8648. }
  8649. }
  8650. },
  8651. /**
  8652. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8653. * @method getAttr
  8654. * @param { String } attrName 要获取的属性名称
  8655. * @return { * } 返回attrs对象下的属性值
  8656. * @example
  8657. * ```javascript
  8658. * node.getAttr('title');
  8659. * ```
  8660. */
  8661. getAttr:function (attrName) {
  8662. return this.attrs && this.attrs[attrName.toLowerCase()]
  8663. },
  8664. /**
  8665. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8666. * @method setAttr
  8667. * @param { String } attrName 要设置的属性名称
  8668. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8669. * @return { * } 返回attrs对象下的属性值
  8670. * @example
  8671. * ```javascript
  8672. * node.setAttr('title','标题');
  8673. * ```
  8674. */
  8675. setAttr:function (attrName, attrVal) {
  8676. if (!attrName) {
  8677. delete this.attrs;
  8678. return;
  8679. }
  8680. if(!this.attrs){
  8681. this.attrs = {};
  8682. }
  8683. if (utils.isObject(attrName)) {
  8684. for (var a in attrName) {
  8685. if (!attrName[a]) {
  8686. delete this.attrs[a]
  8687. } else {
  8688. this.attrs[a.toLowerCase()] = attrName[a];
  8689. }
  8690. }
  8691. } else {
  8692. if (!attrVal) {
  8693. delete this.attrs[attrName]
  8694. } else {
  8695. this.attrs[attrName.toLowerCase()] = attrVal;
  8696. }
  8697. }
  8698. },
  8699. /**
  8700. * 获取当前节点在父节点下的位置索引
  8701. * @method getIndex
  8702. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8703. * @example
  8704. * ```javascript
  8705. * node.getIndex();
  8706. * ```
  8707. */
  8708. getIndex:function(){
  8709. var parent = this.parentNode;
  8710. for(var i= 0,ci;ci=parent.children[i];i++){
  8711. if(ci === this){
  8712. return i;
  8713. }
  8714. }
  8715. return -1;
  8716. },
  8717. /**
  8718. * 在当前节点下,根据id查找节点
  8719. * @method getNodeById
  8720. * @param { String } id 要查找的id
  8721. * @return { UE.uNode } 返回找到的节点
  8722. * @example
  8723. * ```javascript
  8724. * node.getNodeById('textId');
  8725. * ```
  8726. */
  8727. getNodeById:function (id) {
  8728. var node;
  8729. if (this.children && this.children.length) {
  8730. for (var i = 0, ci; ci = this.children[i++];) {
  8731. if (node = getNodeById(ci, id)) {
  8732. return node;
  8733. }
  8734. }
  8735. }
  8736. },
  8737. /**
  8738. * 在当前节点下,根据元素名称查找节点列表
  8739. * @method getNodesByTagName
  8740. * @param { String } tagNames 要查找的元素名称
  8741. * @return { Array } 返回找到的节点列表
  8742. * @example
  8743. * ```javascript
  8744. * node.getNodesByTagName('span');
  8745. * ```
  8746. */
  8747. getNodesByTagName:function (tagNames) {
  8748. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8749. var arr = [], me = this;
  8750. utils.each(tagNames, function (tagName) {
  8751. if (me.children && me.children.length) {
  8752. for (var i = 0, ci; ci = me.children[i++];) {
  8753. getNodesByTagName(ci, tagName, arr)
  8754. }
  8755. }
  8756. });
  8757. return arr;
  8758. },
  8759. /**
  8760. * 根据样式名称,获取节点的样式值
  8761. * @method getStyle
  8762. * @param { String } name 要获取的样式名称
  8763. * @return { String } 返回样式值
  8764. * @example
  8765. * ```javascript
  8766. * node.getStyle('font-size');
  8767. * ```
  8768. */
  8769. getStyle:function (name) {
  8770. var cssStyle = this.getAttr('style');
  8771. if (!cssStyle) {
  8772. return ''
  8773. }
  8774. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8775. var match = cssStyle.match(reg);
  8776. if (match && match[0]) {
  8777. return match[2]
  8778. }
  8779. return '';
  8780. },
  8781. /**
  8782. * 给节点设置样式
  8783. * @method setStyle
  8784. * @param { String } name 要设置的的样式名称
  8785. * @param { String } val 要设置的的样值
  8786. * @example
  8787. * ```javascript
  8788. * node.setStyle('font-size', '12px');
  8789. * ```
  8790. */
  8791. setStyle:function (name, val) {
  8792. function exec(name, val) {
  8793. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8794. cssStyle = cssStyle.replace(reg, '$1');
  8795. if (val) {
  8796. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8797. }
  8798. }
  8799. var cssStyle = this.getAttr('style');
  8800. if (!cssStyle) {
  8801. cssStyle = '';
  8802. }
  8803. if (utils.isObject(name)) {
  8804. for (var a in name) {
  8805. exec(a, name[a])
  8806. }
  8807. } else {
  8808. exec(name, val)
  8809. }
  8810. this.setAttr('style', utils.trim(cssStyle))
  8811. },
  8812. /**
  8813. * 传入一个函数,递归遍历当前节点下的所有节点
  8814. * @method traversal
  8815. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8816. * @example
  8817. * ```javascript
  8818. * traversal(node, function(){
  8819. * console.log(node.type);
  8820. * });
  8821. * ```
  8822. */
  8823. traversal:function(fn){
  8824. if(this.children && this.children.length){
  8825. nodeTraversal(this,fn);
  8826. }
  8827. return this;
  8828. }
  8829. }
  8830. })();
  8831. // core/htmlparser.js
  8832. /**
  8833. * html字符串转换成uNode节点
  8834. * @file
  8835. * @module UE
  8836. * @since 1.2.6.1
  8837. */
  8838. /**
  8839. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8840. * @unfile
  8841. * @module UE
  8842. */
  8843. /**
  8844. * html字符串转换成uNode节点的静态方法
  8845. * @method htmlparser
  8846. * @param { String } htmlstr 要转换的html代码
  8847. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8848. * @return { uNode } 给定的html片段转换形成的uNode对象
  8849. * @example
  8850. * ```javascript
  8851. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8852. * ```
  8853. */
  8854. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8855. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8856. //先去掉了,加上的原因忘了,这里先记录
  8857. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8858. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8859. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8860. var allowEmptyTags = {
  8861. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8862. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8863. };
  8864. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8865. if(!ignoreBlank){
  8866. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8867. //br暂时单独处理
  8868. if(b && allowEmptyTags[b.toLowerCase()]){
  8869. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8870. }
  8871. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8872. });
  8873. }
  8874. var notTransAttrs = {
  8875. 'href':1,
  8876. 'src':1
  8877. };
  8878. var uNode = UE.uNode,
  8879. needParentNode = {
  8880. 'td':'tr',
  8881. 'tr':['tbody','thead','tfoot'],
  8882. 'tbody':'table',
  8883. 'th':'tr',
  8884. 'thead':'table',
  8885. 'tfoot':'table',
  8886. 'caption':'table',
  8887. 'li':['ul', 'ol'],
  8888. 'dt':'dl',
  8889. 'dd':'dl',
  8890. 'option':'select'
  8891. },
  8892. needChild = {
  8893. 'ol':'li',
  8894. 'ul':'li'
  8895. };
  8896. function text(parent, data) {
  8897. if(needChild[parent.tagName]){
  8898. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8899. parent.appendChild(tmpNode);
  8900. tmpNode.appendChild(uNode.createText(data));
  8901. parent = tmpNode;
  8902. }else{
  8903. parent.appendChild(uNode.createText(data));
  8904. }
  8905. }
  8906. function element(parent, tagName, htmlattr) {
  8907. var needParentTag;
  8908. if (needParentTag = needParentNode[tagName]) {
  8909. var tmpParent = parent,hasParent;
  8910. while(tmpParent.type != 'root'){
  8911. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8912. parent = tmpParent;
  8913. hasParent = true;
  8914. break;
  8915. }
  8916. tmpParent = tmpParent.parentNode;
  8917. }
  8918. if(!hasParent){
  8919. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8920. }
  8921. }
  8922. //按dtd处理嵌套
  8923. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8924. // parent = parent.parentNode;
  8925. var elm = new uNode({
  8926. parentNode:parent,
  8927. type:'element',
  8928. tagName:tagName.toLowerCase(),
  8929. //是自闭合的处理一下
  8930. children:dtd.$empty[tagName] ? null : []
  8931. });
  8932. //如果属性存在,处理属性
  8933. if (htmlattr) {
  8934. var attrs = {}, match;
  8935. while (match = re_attr.exec(htmlattr)) {
  8936. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8937. }
  8938. elm.attrs = attrs;
  8939. }
  8940. //trace:3970
  8941. // //如果parent下不能放elm
  8942. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8943. // parent = parent.parentNode;
  8944. // elm.parentNode = parent;
  8945. // }
  8946. parent.children.push(elm);
  8947. //如果是自闭合节点返回父亲节点
  8948. return dtd.$empty[tagName] ? parent : elm
  8949. }
  8950. function comment(parent, data) {
  8951. parent.children.push(new uNode({
  8952. type:'comment',
  8953. data:data,
  8954. parentNode:parent
  8955. }));
  8956. }
  8957. var match, currentIndex = 0, nextIndex = 0;
  8958. //设置根节点
  8959. var root = new uNode({
  8960. type:'root',
  8961. children:[]
  8962. });
  8963. var currentParent = root;
  8964. while (match = re_tag.exec(htmlstr)) {
  8965. currentIndex = match.index;
  8966. try{
  8967. if (currentIndex > nextIndex) {
  8968. //text node
  8969. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8970. }
  8971. if (match[3]) {
  8972. if(dtd.$cdata[currentParent.tagName]){
  8973. text(currentParent, match[0]);
  8974. }else{
  8975. //start tag
  8976. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8977. }
  8978. } else if (match[1]) {
  8979. if(currentParent.type != 'root'){
  8980. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8981. text(currentParent, match[0]);
  8982. }else{
  8983. var tmpParent = currentParent;
  8984. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8985. currentParent = currentParent.parentNode;
  8986. if(currentParent.type == 'root'){
  8987. currentParent = tmpParent;
  8988. throw 'break'
  8989. }
  8990. }
  8991. //end tag
  8992. currentParent = currentParent.parentNode;
  8993. }
  8994. }
  8995. } else if (match[2]) {
  8996. //comment
  8997. comment(currentParent, match[2])
  8998. }
  8999. }catch(e){}
  9000. nextIndex = re_tag.lastIndex;
  9001. }
  9002. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9003. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9004. if (nextIndex < htmlstr.length) {
  9005. text(currentParent, htmlstr.slice(nextIndex));
  9006. }
  9007. return root;
  9008. };
  9009. // core/filternode.js
  9010. /**
  9011. * UE过滤节点的静态方法
  9012. * @file
  9013. */
  9014. /**
  9015. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9016. * @module UE
  9017. */
  9018. /**
  9019. * 根据传入节点和过滤规则过滤相应节点
  9020. * @module UE
  9021. * @since 1.2.6.1
  9022. * @method filterNode
  9023. * @param { Object } root 指定root节点
  9024. * @param { Object } rules 过滤规则json对象
  9025. * @example
  9026. * ```javascript
  9027. * UE.filterNode(root,editor.options.filterRules);
  9028. * ```
  9029. */
  9030. var filterNode = UE.filterNode = function () {
  9031. function filterNode(node,rules){
  9032. switch (node.type) {
  9033. case 'text':
  9034. break;
  9035. case 'element':
  9036. var val;
  9037. if(val = rules[node.tagName]){
  9038. if(val === '-'){
  9039. node.parentNode.removeChild(node)
  9040. }else if(utils.isFunction(val)){
  9041. var parentNode = node.parentNode,
  9042. index = node.getIndex();
  9043. val(node);
  9044. if(node.parentNode){
  9045. if(node.children){
  9046. for(var i = 0,ci;ci=node.children[i];){
  9047. filterNode(ci,rules);
  9048. if(ci.parentNode){
  9049. i++;
  9050. }
  9051. }
  9052. }
  9053. }else{
  9054. for(var i = index,ci;ci=parentNode.children[i];){
  9055. filterNode(ci,rules);
  9056. if(ci.parentNode){
  9057. i++;
  9058. }
  9059. }
  9060. }
  9061. }else{
  9062. var attrs = val['$'];
  9063. if(attrs && node.attrs){
  9064. var tmpAttrs = {},tmpVal;
  9065. for(var a in attrs){
  9066. tmpVal = node.getAttr(a);
  9067. //todo 只先对style单独处理
  9068. if(a == 'style' && utils.isArray(attrs[a])){
  9069. var tmpCssStyle = [];
  9070. utils.each(attrs[a],function(v){
  9071. var tmp;
  9072. if(tmp = node.getStyle(v)){
  9073. tmpCssStyle.push(v + ':' + tmp);
  9074. }
  9075. });
  9076. tmpVal = tmpCssStyle.join(';')
  9077. }
  9078. if(tmpVal){
  9079. tmpAttrs[a] = tmpVal;
  9080. }
  9081. }
  9082. node.attrs = tmpAttrs;
  9083. }
  9084. if(node.children){
  9085. for(var i = 0,ci;ci=node.children[i];){
  9086. filterNode(ci,rules);
  9087. if(ci.parentNode){
  9088. i++;
  9089. }
  9090. }
  9091. }
  9092. }
  9093. }else{
  9094. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9095. if(dtd.$cdata[node.tagName]){
  9096. node.parentNode.removeChild(node)
  9097. }else{
  9098. var parentNode = node.parentNode,
  9099. index = node.getIndex();
  9100. node.parentNode.removeChild(node,true);
  9101. for(var i = index,ci;ci=parentNode.children[i];){
  9102. filterNode(ci,rules);
  9103. if(ci.parentNode){
  9104. i++;
  9105. }
  9106. }
  9107. }
  9108. }
  9109. break;
  9110. case 'comment':
  9111. node.parentNode.removeChild(node)
  9112. }
  9113. }
  9114. return function(root,rules){
  9115. if(utils.isEmptyObject(rules)){
  9116. return root;
  9117. }
  9118. var val;
  9119. if(val = rules['-']){
  9120. utils.each(val.split(' '),function(k){
  9121. rules[k] = '-'
  9122. })
  9123. }
  9124. for(var i= 0,ci;ci=root.children[i];){
  9125. filterNode(ci,rules);
  9126. if(ci.parentNode){
  9127. i++;
  9128. }
  9129. }
  9130. return root;
  9131. }
  9132. }();
  9133. // core/plugin.js
  9134. /**
  9135. * Created with JetBrains PhpStorm.
  9136. * User: campaign
  9137. * Date: 10/8/13
  9138. * Time: 6:15 PM
  9139. * To change this template use File | Settings | File Templates.
  9140. */
  9141. UE.plugin = function(){
  9142. var _plugins = {};
  9143. return {
  9144. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9145. if(oldOptionName && utils.isFunction(oldOptionName)){
  9146. afterDisabled = oldOptionName;
  9147. oldOptionName = null
  9148. }
  9149. _plugins[pluginName] = {
  9150. optionName : oldOptionName || pluginName,
  9151. execFn : fn,
  9152. //当插件被禁用时执行
  9153. afterDisabled : afterDisabled
  9154. }
  9155. },
  9156. load : function(editor){
  9157. utils.each(_plugins,function(plugin){
  9158. var _export = plugin.execFn.call(editor);
  9159. if(editor.options[plugin.optionName] !== false){
  9160. if(_export){
  9161. //后边需要再做扩展
  9162. utils.each(_export,function(v,k){
  9163. switch(k.toLowerCase()){
  9164. case 'shortcutkey':
  9165. editor.addshortcutkey(v);
  9166. break;
  9167. case 'bindevents':
  9168. utils.each(v,function(fn,eventName){
  9169. editor.addListener(eventName,fn);
  9170. });
  9171. break;
  9172. case 'bindmultievents':
  9173. utils.each(utils.isArray(v) ? v:[v],function(event){
  9174. var types = utils.trim(event.type).split(/\s+/);
  9175. utils.each(types,function(eventName){
  9176. editor.addListener(eventName, event.handler);
  9177. });
  9178. });
  9179. break;
  9180. case 'commands':
  9181. utils.each(v,function(execFn,execName){
  9182. editor.commands[execName] = execFn
  9183. });
  9184. break;
  9185. case 'outputrule':
  9186. editor.addOutputRule(v);
  9187. break;
  9188. case 'inputrule':
  9189. editor.addInputRule(v);
  9190. break;
  9191. case 'defaultoptions':
  9192. editor.setOpt(v)
  9193. }
  9194. })
  9195. }
  9196. }else if(plugin.afterDisabled){
  9197. plugin.afterDisabled.call(editor)
  9198. }
  9199. });
  9200. //向下兼容
  9201. utils.each(UE.plugins,function(plugin){
  9202. plugin.call(editor);
  9203. });
  9204. },
  9205. run : function(pluginName,editor){
  9206. var plugin = _plugins[pluginName];
  9207. if(plugin){
  9208. plugin.exeFn.call(editor)
  9209. }
  9210. }
  9211. }
  9212. }();
  9213. // core/keymap.js
  9214. var keymap = UE.keymap = {
  9215. 'Backspace' : 8,
  9216. 'Tab' : 9,
  9217. 'Enter' : 13,
  9218. 'Shift':16,
  9219. 'Control':17,
  9220. 'Alt':18,
  9221. 'CapsLock':20,
  9222. 'Esc':27,
  9223. 'Spacebar':32,
  9224. 'PageUp':33,
  9225. 'PageDown':34,
  9226. 'End':35,
  9227. 'Home':36,
  9228. 'Left':37,
  9229. 'Up':38,
  9230. 'Right':39,
  9231. 'Down':40,
  9232. 'Insert':45,
  9233. 'Del':46,
  9234. 'NumLock':144,
  9235. 'Cmd':91,
  9236. '=':187,
  9237. '-':189,
  9238. "b":66,
  9239. 'i':73,
  9240. //回退
  9241. 'z':90,
  9242. 'y':89,
  9243. //粘贴
  9244. 'v' : 86,
  9245. 'x' : 88,
  9246. 's' : 83,
  9247. 'n' : 78
  9248. };
  9249. // core/localstorage.js
  9250. //存储媒介封装
  9251. var LocalStorage = UE.LocalStorage = (function () {
  9252. var storage = window.localStorage || getUserData() || null,
  9253. LOCAL_FILE = 'localStorage';
  9254. return {
  9255. saveLocalData: function (key, data) {
  9256. if (storage && data) {
  9257. storage.setItem(key, data);
  9258. return true;
  9259. }
  9260. return false;
  9261. },
  9262. getLocalData: function (key) {
  9263. if (storage) {
  9264. return storage.getItem(key);
  9265. }
  9266. return null;
  9267. },
  9268. removeItem: function (key) {
  9269. storage && storage.removeItem(key);
  9270. }
  9271. };
  9272. function getUserData() {
  9273. var container = document.createElement("div");
  9274. container.style.display = "none";
  9275. if (!container.addBehavior) {
  9276. return null;
  9277. }
  9278. container.addBehavior("#default#userdata");
  9279. return {
  9280. getItem: function (key) {
  9281. var result = null;
  9282. try {
  9283. document.body.appendChild(container);
  9284. container.load(LOCAL_FILE);
  9285. result = container.getAttribute(key);
  9286. document.body.removeChild(container);
  9287. } catch (e) {
  9288. }
  9289. return result;
  9290. },
  9291. setItem: function (key, value) {
  9292. document.body.appendChild(container);
  9293. container.setAttribute(key, value);
  9294. container.save(LOCAL_FILE);
  9295. document.body.removeChild(container);
  9296. },
  9297. //// 暂时没有用到
  9298. //clear: function () {
  9299. //
  9300. // var expiresTime = new Date();
  9301. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9302. // document.body.appendChild(container);
  9303. // container.expires = expiresTime.toUTCString();
  9304. // container.save(LOCAL_FILE);
  9305. // document.body.removeChild(container);
  9306. //
  9307. //},
  9308. removeItem: function (key) {
  9309. document.body.appendChild(container);
  9310. container.removeAttribute(key);
  9311. container.save(LOCAL_FILE);
  9312. document.body.removeChild(container);
  9313. }
  9314. };
  9315. }
  9316. })();
  9317. (function () {
  9318. var ROOTKEY = 'ueditor_preference';
  9319. UE.Editor.prototype.setPreferences = function(key,value){
  9320. var obj = {};
  9321. if (utils.isString(key)) {
  9322. obj[ key ] = value;
  9323. } else {
  9324. obj = key;
  9325. }
  9326. var data = LocalStorage.getLocalData(ROOTKEY);
  9327. if (data && (data = utils.str2json(data))) {
  9328. utils.extend(data, obj);
  9329. } else {
  9330. data = obj;
  9331. }
  9332. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9333. };
  9334. UE.Editor.prototype.getPreferences = function(key){
  9335. var data = LocalStorage.getLocalData(ROOTKEY);
  9336. if (data && (data = utils.str2json(data))) {
  9337. return key ? data[key] : data
  9338. }
  9339. return null;
  9340. };
  9341. UE.Editor.prototype.removePreferences = function (key) {
  9342. var data = LocalStorage.getLocalData(ROOTKEY);
  9343. if (data && (data = utils.str2json(data))) {
  9344. data[key] = undefined;
  9345. delete data[key]
  9346. }
  9347. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9348. };
  9349. })();
  9350. // plugins/defaultfilter.js
  9351. ///import core
  9352. ///plugin 编辑器默认的过滤转换机制
  9353. UE.plugins['defaultfilter'] = function () {
  9354. return;
  9355. var me = this;
  9356. me.setOpt({
  9357. 'allowDivTransToP':true,
  9358. 'disabledTableInTable':true
  9359. });
  9360. //默认的过滤处理
  9361. //进入编辑器的内容处理
  9362. me.addInputRule(function (root) {
  9363. var allowDivTransToP = this.options.allowDivTransToP;
  9364. var val;
  9365. function tdParent(node){
  9366. while(node && node.type == 'element'){
  9367. if(node.tagName == 'td'){
  9368. return true;
  9369. }
  9370. node = node.parentNode;
  9371. }
  9372. return false;
  9373. }
  9374. //进行默认的处理
  9375. root.traversal(function (node) {
  9376. if (node.type == 'element') {
  9377. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9378. if (!node.firstChild()) node.parentNode.removeChild(node);
  9379. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9380. node.parentNode.removeChild(node, true)
  9381. }
  9382. return;
  9383. }
  9384. switch (node.tagName) {
  9385. case 'style':
  9386. case 'script':
  9387. node.setAttr({
  9388. cdata_tag: node.tagName,
  9389. cdata_data: (node.innerHTML() || ''),
  9390. '_ue_custom_node_':'true'
  9391. });
  9392. node.tagName = 'div';
  9393. node.innerHTML('');
  9394. break;
  9395. case 'a':
  9396. if (val = node.getAttr('href')) {
  9397. node.setAttr('_href', val)
  9398. }
  9399. break;
  9400. case 'img':
  9401. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9402. if (val = node.getAttr('src')) {
  9403. if (/^data:/.test(val)) {
  9404. node.parentNode.removeChild(node);
  9405. break;
  9406. }
  9407. }
  9408. node.setAttr('_src', node.getAttr('src'));
  9409. break;
  9410. case 'span':
  9411. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9412. if (/nowrap|normal/.test(val)) {
  9413. node.setStyle('white-space', '');
  9414. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9415. node.parentNode.removeChild(node, true)
  9416. }
  9417. }
  9418. }
  9419. val = node.getAttr('id');
  9420. if(val && /^_baidu_bookmark_/i.test(val)){
  9421. node.parentNode.removeChild(node)
  9422. }
  9423. break;
  9424. case 'p':
  9425. if (val = node.getAttr('align')) {
  9426. node.setAttr('align');
  9427. node.setStyle('text-align', val)
  9428. }
  9429. //trace:3431
  9430. // var cssStyle = node.getAttr('style');
  9431. // if (cssStyle) {
  9432. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9433. // node.setAttr('style', cssStyle)
  9434. //
  9435. // }
  9436. //p标签不允许嵌套
  9437. utils.each(node.children,function(n){
  9438. if(n.type == 'element' && n.tagName == 'p'){
  9439. var next = n.nextSibling();
  9440. node.parentNode.insertAfter(n,node);
  9441. var last = n;
  9442. while(next){
  9443. var tmp = next.nextSibling();
  9444. node.parentNode.insertAfter(next,last);
  9445. last = next;
  9446. next = tmp;
  9447. }
  9448. return false;
  9449. }
  9450. });
  9451. if (!node.firstChild()) {
  9452. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9453. }
  9454. break;
  9455. case 'div':
  9456. if(node.getAttr('cdata_tag')){
  9457. break;
  9458. }
  9459. //针对代码这里不处理插入代码的div
  9460. val = node.getAttr('class');
  9461. if(val && /^line number\d+/.test(val)){
  9462. break;
  9463. }
  9464. if(!allowDivTransToP){
  9465. break;
  9466. }
  9467. var tmpNode, p = UE.uNode.createElement('p');
  9468. while (tmpNode = node.firstChild()) {
  9469. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9470. p.appendChild(tmpNode);
  9471. } else {
  9472. if (p.firstChild()) {
  9473. node.parentNode.insertBefore(p, node);
  9474. p = UE.uNode.createElement('p');
  9475. } else {
  9476. node.parentNode.insertBefore(tmpNode, node);
  9477. }
  9478. }
  9479. }
  9480. if (p.firstChild()) {
  9481. node.parentNode.insertBefore(p, node);
  9482. }
  9483. node.parentNode.removeChild(node);
  9484. break;
  9485. case 'dl':
  9486. node.tagName = 'ul';
  9487. break;
  9488. case 'dt':
  9489. case 'dd':
  9490. node.tagName = 'li';
  9491. break;
  9492. case 'li':
  9493. var className = node.getAttr('class');
  9494. if (!className || !/list\-/.test(className)) {
  9495. node.setAttr()
  9496. }
  9497. var tmpNodes = node.getNodesByTagName('ol ul');
  9498. UE.utils.each(tmpNodes, function (n) {
  9499. node.parentNode.insertAfter(n, node);
  9500. });
  9501. break;
  9502. case 'td':
  9503. case 'th':
  9504. case 'caption':
  9505. if(!node.children || !node.children.length){
  9506. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9507. }
  9508. break;
  9509. case 'table':
  9510. if(me.options.disabledTableInTable && tdParent(node)){
  9511. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9512. node.parentNode.removeChild(node)
  9513. }
  9514. }
  9515. }
  9516. // if(node.type == 'comment'){
  9517. // node.parentNode.removeChild(node);
  9518. // }
  9519. })
  9520. });
  9521. //从编辑器出去的内容处理
  9522. me.addOutputRule(function (root) {
  9523. var val;
  9524. root.traversal(function (node) {
  9525. if (node.type == 'element') {
  9526. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9527. if (!node.firstChild()) node.parentNode.removeChild(node);
  9528. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9529. node.parentNode.removeChild(node, true)
  9530. }
  9531. return;
  9532. }
  9533. switch (node.tagName) {
  9534. case 'div':
  9535. if (val = node.getAttr('cdata_tag')) {
  9536. node.tagName = val;
  9537. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9538. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9539. }
  9540. break;
  9541. case 'a':
  9542. if (val = node.getAttr('_href')) {
  9543. node.setAttr({
  9544. 'href': utils.html(val),
  9545. '_href': ''
  9546. })
  9547. }
  9548. break;
  9549. break;
  9550. case 'span':
  9551. val = node.getAttr('id');
  9552. if(val && /^_baidu_bookmark_/i.test(val)){
  9553. node.parentNode.removeChild(node)
  9554. }
  9555. break;
  9556. case 'img':
  9557. if (val = node.getAttr('_src')) {
  9558. node.setAttr({
  9559. 'src': node.getAttr('_src'),
  9560. '_src': ''
  9561. })
  9562. }
  9563. }
  9564. }
  9565. })
  9566. });
  9567. };
  9568. // plugins/inserthtml.js
  9569. /**
  9570. * 插入html字符串插件
  9571. * @file
  9572. * @since 1.2.6.1
  9573. */
  9574. /**
  9575. * 插入html代码
  9576. * @command inserthtml
  9577. * @method execCommand
  9578. * @param { String } cmd 命令字符串
  9579. * @param { String } html 插入的html字符串
  9580. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9581. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9582. * @example
  9583. * ```javascript
  9584. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9585. * //执行命令,插入<b>CC</b>
  9586. * //插入后的效果 xxx<b>CC</b>xxx
  9587. * //<p>xx|xxx</p> 当前选区为闭合状态
  9588. * //插入<p>CC</p>
  9589. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9590. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9591. * //插入 xxxx
  9592. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9593. * ```
  9594. */
  9595. UE.commands['inserthtml'] = {
  9596. execCommand: function (command,html,notNeedFilter){
  9597. var me = this,
  9598. range,
  9599. div;
  9600. if(!html){
  9601. return;
  9602. }
  9603. if(me.fireEvent('beforeinserthtml',html) === true){
  9604. return;
  9605. }
  9606. range = me.selection.getRange();
  9607. div = range.document.createElement( 'div' );
  9608. div.style.display = 'inline';
  9609. if (!notNeedFilter) {
  9610. var root = UE.htmlparser(html);
  9611. //如果给了过滤规则就先进行过滤
  9612. if(me.options.filterRules){
  9613. UE.filterNode(root,me.options.filterRules);
  9614. }
  9615. //执行默认的处理
  9616. me.filterInputRule(root);
  9617. html = root.toHtml()
  9618. }
  9619. div.innerHTML = utils.trim( html );
  9620. if ( !range.collapsed ) {
  9621. var tmpNode = range.startContainer;
  9622. if(domUtils.isFillChar(tmpNode)){
  9623. range.setStartBefore(tmpNode)
  9624. }
  9625. tmpNode = range.endContainer;
  9626. if(domUtils.isFillChar(tmpNode)){
  9627. range.setEndAfter(tmpNode)
  9628. }
  9629. range.txtToElmBoundary();
  9630. //结束边界可能放到了br的前边,要把br包含进来
  9631. // x[xxx]<br/>
  9632. if(range.endContainer && range.endContainer.nodeType == 1){
  9633. tmpNode = range.endContainer.childNodes[range.endOffset];
  9634. if(tmpNode && domUtils.isBr(tmpNode)){
  9635. range.setEndAfter(tmpNode);
  9636. }
  9637. }
  9638. if(range.startOffset == 0){
  9639. tmpNode = range.startContainer;
  9640. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9641. tmpNode = range.endContainer;
  9642. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9643. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9644. range.setStart(me.body.firstChild,0).collapse(true)
  9645. }
  9646. }
  9647. }
  9648. !range.collapsed && range.deleteContents();
  9649. if(range.startContainer.nodeType == 1){
  9650. var child = range.startContainer.childNodes[range.startOffset],pre;
  9651. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9652. range.setEnd(pre,pre.childNodes.length).collapse();
  9653. while(child.firstChild){
  9654. pre.appendChild(child.firstChild);
  9655. }
  9656. domUtils.remove(child);
  9657. }
  9658. }
  9659. }
  9660. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9661. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9662. if(range.inFillChar()){
  9663. child = range.startContainer;
  9664. if(domUtils.isFillChar(child)){
  9665. range.setStartBefore(child).collapse(true);
  9666. domUtils.remove(child);
  9667. }else if(domUtils.isFillChar(child,true)){
  9668. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9669. range.startOffset--;
  9670. range.collapsed && range.collapse(true)
  9671. }
  9672. }
  9673. //列表单独处理
  9674. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9675. if(li){
  9676. var next,last;
  9677. while(child = div.firstChild){
  9678. //针对hr单独处理一下先
  9679. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9680. next = child.nextSibling;
  9681. range.insertNode( child).collapse();
  9682. last = child;
  9683. child = next;
  9684. }
  9685. if(child){
  9686. if(/^(ol|ul)$/i.test(child.tagName)){
  9687. while(child.firstChild){
  9688. last = child.firstChild;
  9689. domUtils.insertAfter(li,child.firstChild);
  9690. li = li.nextSibling;
  9691. }
  9692. domUtils.remove(child)
  9693. }else{
  9694. var tmpLi;
  9695. next = child.nextSibling;
  9696. tmpLi = me.document.createElement('li');
  9697. domUtils.insertAfter(li,tmpLi);
  9698. tmpLi.appendChild(child);
  9699. last = child;
  9700. child = next;
  9701. li = tmpLi;
  9702. }
  9703. }
  9704. }
  9705. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9706. if(domUtils.isEmptyBlock(li)){
  9707. domUtils.remove(li)
  9708. }
  9709. if(last){
  9710. range.setStartAfter(last).collapse(true).select(true)
  9711. }
  9712. }else{
  9713. while ( child = div.firstChild ) {
  9714. if(hadBreak){
  9715. var p = me.document.createElement('p');
  9716. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9717. nextNode = child.nextSibling;
  9718. p.appendChild(child);
  9719. child = nextNode;
  9720. }
  9721. if(p.firstChild){
  9722. child = p
  9723. }
  9724. }
  9725. range.insertNode( child );
  9726. nextNode = child.nextSibling;
  9727. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9728. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9729. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9730. if(!dtd[parent.tagName][child.nodeName]){
  9731. pre = parent;
  9732. }else{
  9733. tmp = child.parentNode;
  9734. while (tmp !== parent){
  9735. pre = tmp;
  9736. tmp = tmp.parentNode;
  9737. }
  9738. }
  9739. domUtils.breakParent( child, pre || tmp );
  9740. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9741. var pre = child.previousSibling;
  9742. domUtils.trimWhiteTextNode(pre);
  9743. if(!pre.childNodes.length){
  9744. domUtils.remove(pre);
  9745. }
  9746. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9747. if(!browser.ie &&
  9748. (next = child.nextSibling) &&
  9749. domUtils.isBlockElm(next) &&
  9750. next.lastChild &&
  9751. !domUtils.isBr(next.lastChild)){
  9752. next.appendChild(me.document.createElement('br'));
  9753. }
  9754. hadBreak = 1;
  9755. }
  9756. }
  9757. var next = child.nextSibling;
  9758. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9759. range.setStart(next,0).collapse(true);
  9760. break;
  9761. }
  9762. range.setEndAfter( child ).collapse();
  9763. }
  9764. child = range.startContainer;
  9765. if(nextNode && domUtils.isBr(nextNode)){
  9766. domUtils.remove(nextNode)
  9767. }
  9768. //用chrome可能有空白展位符
  9769. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9770. if(nextNode = child.nextSibling){
  9771. domUtils.remove(child);
  9772. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9773. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9774. }
  9775. }else{
  9776. try{
  9777. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9778. }catch(e){
  9779. range.setStartBefore(child);
  9780. domUtils.remove(child)
  9781. }
  9782. }
  9783. }
  9784. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9785. try{
  9786. range.select(true);
  9787. }catch(e){}
  9788. }
  9789. setTimeout(function(){
  9790. range = me.selection.getRange();
  9791. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9792. me.fireEvent('afterinserthtml', html);
  9793. },200);
  9794. }
  9795. };
  9796. // plugins/autotypeset.js
  9797. /**
  9798. * 自动排版
  9799. * @file
  9800. * @since 1.2.6.1
  9801. */
  9802. /**
  9803. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9804. * @command autotypeset
  9805. * @method execCommand
  9806. * @param { String } cmd 命令字符串
  9807. * @example
  9808. * ```javascript
  9809. * editor.execCommand( 'autotypeset' );
  9810. * ```
  9811. */
  9812. UE.plugins['autotypeset'] = function(){
  9813. this.setOpt({'autotypeset': {
  9814. mergeEmptyline: true, //合并空行
  9815. removeClass: true, //去掉冗余的class
  9816. removeEmptyline: false, //去掉空行
  9817. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9818. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9819. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9820. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9821. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9822. removeEmptyNode: false, // 去掉空节点
  9823. //可以去掉的标签
  9824. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9825. indent: false, // 行首缩进
  9826. indentValue : '2em', //行首缩进的大小
  9827. bdc2sb: false,
  9828. tobdc: false
  9829. }});
  9830. var me = this,
  9831. opt = me.options.autotypeset,
  9832. remainClass = {
  9833. 'selectTdClass':1,
  9834. 'pagebreak':1,
  9835. 'anchorclass':1
  9836. },
  9837. remainTag = {
  9838. 'li':1
  9839. },
  9840. tags = {
  9841. div:1,
  9842. p:1,
  9843. //trace:2183 这些也认为是行
  9844. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9845. span:1
  9846. },
  9847. highlightCont;
  9848. //升级了版本,但配置项目里没有autotypeset
  9849. if(!opt){
  9850. return;
  9851. }
  9852. readLocalOpts();
  9853. function isLine(node,notEmpty){
  9854. if(!node || node.nodeType == 3)
  9855. return 0;
  9856. if(domUtils.isBr(node))
  9857. return 1;
  9858. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9859. if(highlightCont && highlightCont.contains(node)
  9860. ||
  9861. node.getAttribute('pagebreak')
  9862. ){
  9863. return 0;
  9864. }
  9865. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9866. +']','g'));
  9867. }
  9868. }
  9869. function removeNotAttributeSpan(node){
  9870. if(!node.style.cssText){
  9871. domUtils.removeAttributes(node,['style']);
  9872. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9873. domUtils.remove(node,true);
  9874. }
  9875. }
  9876. }
  9877. function autotype(type,html){
  9878. var me = this,cont;
  9879. if(html){
  9880. if(!opt.pasteFilter){
  9881. return;
  9882. }
  9883. cont = me.document.createElement('div');
  9884. cont.innerHTML = html.html;
  9885. }else{
  9886. cont = me.document.body;
  9887. }
  9888. var nodes = domUtils.getElementsByTagName(cont,'*');
  9889. // 行首缩进,段落方向,段间距,段内间距
  9890. for(var i=0,ci;ci=nodes[i++];){
  9891. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9892. continue;
  9893. }
  9894. //font-size
  9895. if(opt.clearFontSize && ci.style.fontSize){
  9896. domUtils.removeStyle(ci,'font-size');
  9897. removeNotAttributeSpan(ci);
  9898. }
  9899. //font-family
  9900. if(opt.clearFontFamily && ci.style.fontFamily){
  9901. domUtils.removeStyle(ci,'font-family');
  9902. removeNotAttributeSpan(ci);
  9903. }
  9904. if(isLine(ci)){
  9905. //合并空行
  9906. if(opt.mergeEmptyline ){
  9907. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9908. while(isLine(next)){
  9909. tmpNode = next;
  9910. next = tmpNode.nextSibling;
  9911. if(isBr && (!next || next && !domUtils.isBr(next))){
  9912. break;
  9913. }
  9914. domUtils.remove(tmpNode);
  9915. }
  9916. }
  9917. //去掉空行,保留占位的空行
  9918. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9919. if(domUtils.isBr(ci)){
  9920. next = ci.nextSibling;
  9921. if(next && !domUtils.isBr(next)){
  9922. continue;
  9923. }
  9924. }
  9925. domUtils.remove(ci);
  9926. continue;
  9927. }
  9928. }
  9929. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9930. if(opt.indent){
  9931. ci.style.textIndent = opt.indentValue;
  9932. }
  9933. if(opt.textAlign){
  9934. ci.style.textAlign = opt.textAlign;
  9935. }
  9936. // if(opt.lineHeight)
  9937. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9938. }
  9939. //去掉class,保留的class不去掉
  9940. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9941. if(highlightCont && highlightCont.contains(ci)){
  9942. continue;
  9943. }
  9944. domUtils.removeAttributes(ci,['class']);
  9945. }
  9946. //表情不处理
  9947. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9948. if(html){
  9949. var img = ci;
  9950. switch (opt.imageBlockLine){
  9951. case 'left':
  9952. case 'right':
  9953. case 'none':
  9954. var pN = img.parentNode,tmpNode,pre,next;
  9955. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9956. pN = pN.parentNode;
  9957. }
  9958. tmpNode = pN;
  9959. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9960. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9961. pre = tmpNode.previousSibling;
  9962. next = tmpNode.nextSibling;
  9963. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9964. pre.appendChild(tmpNode.firstChild);
  9965. while(next.firstChild){
  9966. pre.appendChild(next.firstChild);
  9967. }
  9968. domUtils.remove(tmpNode);
  9969. domUtils.remove(next);
  9970. }else{
  9971. domUtils.setStyle(tmpNode,'text-align','');
  9972. }
  9973. }
  9974. }
  9975. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9976. break;
  9977. case 'center':
  9978. if(me.queryCommandValue('imagefloat') != 'center'){
  9979. pN = img.parentNode;
  9980. domUtils.setStyle(img,'float','none');
  9981. tmpNode = img;
  9982. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  9983. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  9984. tmpNode = pN;
  9985. pN = pN.parentNode;
  9986. }
  9987. var pNode = me.document.createElement('p');
  9988. domUtils.setAttributes(pNode,{
  9989. style:'text-align:center'
  9990. });
  9991. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  9992. pNode.appendChild(tmpNode);
  9993. domUtils.setStyle(tmpNode,'float','');
  9994. }
  9995. }
  9996. } else {
  9997. var range = me.selection.getRange();
  9998. range.selectNode(ci).select();
  9999. me.execCommand('imagefloat', opt.imageBlockLine);
  10000. }
  10001. }
  10002. //去掉冗余的标签
  10003. if(opt.removeEmptyNode){
  10004. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  10005. domUtils.remove(ci);
  10006. }
  10007. }
  10008. }
  10009. if(opt.tobdc){
  10010. var root = UE.htmlparser(cont.innerHTML);
  10011. root.traversal(function(node){
  10012. if(node.type == 'text'){
  10013. node.data = ToDBC(node.data)
  10014. }
  10015. });
  10016. cont.innerHTML = root.toHtml()
  10017. }
  10018. if(opt.bdc2sb){
  10019. var root = UE.htmlparser(cont.innerHTML);
  10020. root.traversal(function(node){
  10021. if(node.type == 'text'){
  10022. node.data = DBC2SB(node.data)
  10023. }
  10024. });
  10025. cont.innerHTML = root.toHtml()
  10026. }
  10027. if(html){
  10028. html.html = cont.innerHTML;
  10029. }
  10030. }
  10031. if(opt.pasteFilter){
  10032. me.addListener('beforepaste',autotype);
  10033. }
  10034. function DBC2SB(str) {
  10035. var result = '';
  10036. for (var i = 0; i < str.length; i++) {
  10037. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10038. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10039. {
  10040. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10041. } else if (code == 12288)//空格
  10042. {
  10043. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10044. } else {
  10045. result += str.charAt(i);
  10046. }
  10047. }
  10048. return result;
  10049. }
  10050. function ToDBC(txtstring) {
  10051. txtstring = utils.html(txtstring);
  10052. var tmp = "";
  10053. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10054. for (var i = 0; i < txtstring.length; i++) {
  10055. if (txtstring.charCodeAt(i) == 32) {
  10056. tmp = tmp + String.fromCharCode(12288);
  10057. }
  10058. else if (txtstring.charCodeAt(i) < 127) {
  10059. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10060. }
  10061. else {
  10062. tmp += txtstring.charAt(i);
  10063. }
  10064. }
  10065. return tmp;
  10066. }
  10067. function readLocalOpts() {
  10068. var cookieOpt = me.getPreferences('autotypeset');
  10069. utils.extend(me.options.autotypeset, cookieOpt);
  10070. }
  10071. me.commands['autotypeset'] = {
  10072. execCommand:function () {
  10073. me.removeListener('beforepaste',autotype);
  10074. if(opt.pasteFilter){
  10075. me.addListener('beforepaste',autotype);
  10076. }
  10077. autotype.call(me)
  10078. }
  10079. };
  10080. };
  10081. // plugins/autosubmit.js
  10082. /**
  10083. * 快捷键提交
  10084. * @file
  10085. * @since 1.2.6.1
  10086. */
  10087. /**
  10088. * 提交表单
  10089. * @command autosubmit
  10090. * @method execCommand
  10091. * @param { String } cmd 命令字符串
  10092. * @example
  10093. * ```javascript
  10094. * editor.execCommand( 'autosubmit' );
  10095. * ```
  10096. */
  10097. UE.plugin.register('autosubmit',function(){
  10098. return {
  10099. shortcutkey:{
  10100. "autosubmit":"ctrl+13" //手动提交
  10101. },
  10102. commands:{
  10103. 'autosubmit':{
  10104. execCommand:function () {
  10105. var me=this,
  10106. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10107. if (form){
  10108. if(me.fireEvent("beforesubmit")===false){
  10109. return;
  10110. }
  10111. me.sync();
  10112. form.submit();
  10113. }
  10114. }
  10115. }
  10116. }
  10117. }
  10118. });
  10119. // plugins/background.js
  10120. /**
  10121. * 背景插件,为UEditor提供设置背景功能
  10122. * @file
  10123. * @since 1.2.6.1
  10124. */
  10125. UE.plugin.register('background', function () {
  10126. var me = this,
  10127. cssRuleId = 'editor_background',
  10128. isSetColored,
  10129. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10130. function stringToObj(str) {
  10131. var obj = {}, styles = str.split(';');
  10132. utils.each(styles, function (v) {
  10133. var index = v.indexOf(':'),
  10134. key = utils.trim(v.substr(0, index)).toLowerCase();
  10135. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10136. });
  10137. return obj;
  10138. }
  10139. function setBackground(obj) {
  10140. if (obj) {
  10141. var styles = [];
  10142. for (var name in obj) {
  10143. if (obj.hasOwnProperty(name)) {
  10144. styles.push(name + ":" + obj[name] + '; ');
  10145. }
  10146. }
  10147. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10148. } else {
  10149. utils.cssRule(cssRuleId, '', me.document)
  10150. }
  10151. }
  10152. //重写editor.hasContent方法
  10153. var orgFn = me.hasContents;
  10154. me.hasContents = function(){
  10155. if(me.queryCommandValue('background')){
  10156. return true
  10157. }
  10158. return orgFn.apply(me,arguments);
  10159. };
  10160. return {
  10161. bindEvents: {
  10162. 'getAllHtml': function (type, headHtml) {
  10163. var body = this.body,
  10164. su = domUtils.getComputedStyle(body, "background-image"),
  10165. url = "";
  10166. if (su.indexOf(me.options.imagePath) > 0) {
  10167. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10168. } else {
  10169. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10170. }
  10171. var html = '<style type="text/css">body{';
  10172. var bgObj = {
  10173. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10174. 'background-image': url ? 'url(' + url + ')' : '',
  10175. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10176. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10177. 'height': domUtils.getComputedStyle(body, "height")
  10178. };
  10179. for (var name in bgObj) {
  10180. if (bgObj.hasOwnProperty(name)) {
  10181. html += name + ":" + bgObj[name] + "; ";
  10182. }
  10183. }
  10184. html += '}</style> ';
  10185. headHtml.push(html);
  10186. },
  10187. 'aftersetcontent': function () {
  10188. if(isSetColored == false) setBackground();
  10189. }
  10190. },
  10191. inputRule: function (root) {
  10192. isSetColored = false;
  10193. utils.each(root.getNodesByTagName('p'), function (p) {
  10194. var styles = p.getAttr('data-background');
  10195. if (styles) {
  10196. isSetColored = true;
  10197. setBackground(stringToObj(styles));
  10198. p.parentNode.removeChild(p);
  10199. }
  10200. })
  10201. },
  10202. outputRule: function (root) {
  10203. var me = this,
  10204. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10205. if (styles) {
  10206. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10207. }
  10208. },
  10209. commands: {
  10210. 'background': {
  10211. execCommand: function (cmd, obj) {
  10212. setBackground(obj);
  10213. },
  10214. queryCommandValue: function () {
  10215. var me = this,
  10216. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10217. return styles ? stringToObj(styles[1]) : null;
  10218. },
  10219. notNeedUndo: true
  10220. }
  10221. }
  10222. }
  10223. });
  10224. // plugins/image.js
  10225. /**
  10226. * 图片插入、排版插件
  10227. * @file
  10228. * @since 1.2.6.1
  10229. */
  10230. /**
  10231. * 图片对齐方式
  10232. * @command imagefloat
  10233. * @method execCommand
  10234. * @remind 值center为独占一行居中
  10235. * @param { String } cmd 命令字符串
  10236. * @param { String } align 对齐方式,可传left、right、none、center
  10237. * @remaind center表示图片独占一行
  10238. * @example
  10239. * ```javascript
  10240. * editor.execCommand( 'imagefloat', 'center' );
  10241. * ```
  10242. */
  10243. /**
  10244. * 如果选区所在位置是图片区域
  10245. * @command imagefloat
  10246. * @method queryCommandValue
  10247. * @param { String } cmd 命令字符串
  10248. * @return { String } 返回图片对齐方式
  10249. * @example
  10250. * ```javascript
  10251. * editor.queryCommandValue( 'imagefloat' );
  10252. * ```
  10253. */
  10254. UE.commands['imagefloat'] = {
  10255. execCommand:function (cmd, align) {
  10256. var me = this,
  10257. range = me.selection.getRange();
  10258. if (!range.collapsed) {
  10259. var img = range.getClosedNode();
  10260. if (img && img.tagName == 'IMG') {
  10261. switch (align) {
  10262. case 'left':
  10263. case 'right':
  10264. case 'none':
  10265. var pN = img.parentNode, tmpNode, pre, next;
  10266. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10267. pN = pN.parentNode;
  10268. }
  10269. tmpNode = pN;
  10270. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10271. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10272. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10273. }) == 1) {
  10274. pre = tmpNode.previousSibling;
  10275. next = tmpNode.nextSibling;
  10276. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10277. pre.appendChild(tmpNode.firstChild);
  10278. while (next.firstChild) {
  10279. pre.appendChild(next.firstChild);
  10280. }
  10281. domUtils.remove(tmpNode);
  10282. domUtils.remove(next);
  10283. } else {
  10284. domUtils.setStyle(tmpNode, 'text-align', '');
  10285. }
  10286. }
  10287. range.selectNode(img).select();
  10288. }
  10289. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10290. if(align == 'none'){
  10291. domUtils.removeAttributes(img,'align');
  10292. }
  10293. break;
  10294. case 'center':
  10295. if (me.queryCommandValue('imagefloat') != 'center') {
  10296. pN = img.parentNode;
  10297. domUtils.setStyle(img, 'float', '');
  10298. domUtils.removeAttributes(img,'align');
  10299. tmpNode = img;
  10300. while (pN && domUtils.getChildCount(pN, function (node) {
  10301. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10302. }) == 1
  10303. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10304. tmpNode = pN;
  10305. pN = pN.parentNode;
  10306. }
  10307. range.setStartBefore(tmpNode).setCursor(false);
  10308. pN = me.document.createElement('div');
  10309. pN.appendChild(tmpNode);
  10310. domUtils.setStyle(tmpNode, 'float', '');
  10311. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10312. tmpNode = me.document.getElementById('_img_parent_tmp');
  10313. tmpNode.removeAttribute('id');
  10314. tmpNode = tmpNode.firstChild;
  10315. range.selectNode(tmpNode).select();
  10316. //去掉后边多余的元素
  10317. next = tmpNode.parentNode.nextSibling;
  10318. if (next && domUtils.isEmptyNode(next)) {
  10319. domUtils.remove(next);
  10320. }
  10321. }
  10322. break;
  10323. }
  10324. }
  10325. }
  10326. },
  10327. queryCommandValue:function () {
  10328. var range = this.selection.getRange(),
  10329. startNode, floatStyle;
  10330. if (range.collapsed) {
  10331. return 'none';
  10332. }
  10333. startNode = range.getClosedNode();
  10334. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10335. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10336. if (floatStyle == 'none') {
  10337. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10338. }
  10339. return {
  10340. left:1,
  10341. right:1,
  10342. center:1
  10343. }[floatStyle] ? floatStyle : 'none';
  10344. }
  10345. return 'none';
  10346. },
  10347. queryCommandState:function () {
  10348. var range = this.selection.getRange(),
  10349. startNode;
  10350. if (range.collapsed) return -1;
  10351. startNode = range.getClosedNode();
  10352. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10353. return 0;
  10354. }
  10355. return -1;
  10356. }
  10357. };
  10358. /**
  10359. * 插入图片
  10360. * @command insertimage
  10361. * @method execCommand
  10362. * @param { String } cmd 命令字符串
  10363. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10364. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10365. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10366. * @example
  10367. * ```javascript
  10368. * editor.execCommand( 'insertimage', {
  10369. * src:'a/b/c.jpg',
  10370. * width:'100',
  10371. * height:'100'
  10372. * } );
  10373. * ```
  10374. * @example
  10375. * ```javascript
  10376. * editor.execCommand( 'insertimage', [{
  10377. * src:'a/b/c.jpg',
  10378. * width:'100',
  10379. * height:'100'
  10380. * },{
  10381. * src:'a/b/d.jpg',
  10382. * width:'100',
  10383. * height:'100'
  10384. * }] );
  10385. * ```
  10386. */
  10387. UE.commands['insertimage'] = {
  10388. execCommand:function (cmd, opt) {
  10389. opt = utils.isArray(opt) ? opt : [opt];
  10390. if (!opt.length) {
  10391. return;
  10392. }
  10393. var me = this,
  10394. range = me.selection.getRange(),
  10395. img = range.getClosedNode();
  10396. if(me.fireEvent('beforeinsertimage', opt) === true){
  10397. return;
  10398. }
  10399. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10400. var first = opt.shift();
  10401. var floatStyle = first['floatStyle'];
  10402. delete first['floatStyle'];
  10403. //// img.style.border = (first.border||0) +"px solid #000";
  10404. //// img.style.margin = (first.margin||0) +"px";
  10405. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10406. domUtils.setAttributes(img, first);
  10407. me.execCommand('imagefloat', floatStyle);
  10408. if (opt.length > 0) {
  10409. range.setStartAfter(img).setCursor(false, true);
  10410. me.execCommand('insertimage', opt);
  10411. }
  10412. } else {
  10413. var html = [], str = '', ci;
  10414. ci = opt[0];
  10415. if (opt.length == 1) {
  10416. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10417. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10418. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10419. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10420. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10421. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10422. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10423. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10424. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10425. if (ci['floatStyle'] == 'center') {
  10426. str = '<p style="text-align: center">' + str + '</p>';
  10427. }
  10428. html.push(str);
  10429. } else {
  10430. for (var i = 0; ci = opt[i++];) {
  10431. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10432. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10433. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10434. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10435. (ci.border || '') + '" ' +
  10436. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10437. html.push(str);
  10438. }
  10439. }
  10440. me.execCommand('insertHtml', html.join(''));
  10441. }
  10442. me.fireEvent('afterinsertimage', opt)
  10443. }
  10444. };
  10445. // plugins/justify.js
  10446. /**
  10447. * 段落格式
  10448. * @file
  10449. * @since 1.2.6.1
  10450. */
  10451. /**
  10452. * 段落对齐方式
  10453. * @command justify
  10454. * @method execCommand
  10455. * @param { String } cmd 命令字符串
  10456. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10457. * @example
  10458. * ```javascript
  10459. * editor.execCommand( 'justify', 'center' );
  10460. * ```
  10461. */
  10462. /**
  10463. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10464. * @command justify
  10465. * @method queryCommandValue
  10466. * @param { String } cmd 命令字符串
  10467. * @return { String } 返回段落对齐方式
  10468. * @example
  10469. * ```javascript
  10470. * editor.queryCommandValue( 'justify' );
  10471. * ```
  10472. */
  10473. UE.plugins['justify']=function(){
  10474. var me=this,
  10475. block = domUtils.isBlockElm,
  10476. defaultValue = {
  10477. left:1,
  10478. right:1,
  10479. center:1,
  10480. justify:1
  10481. },
  10482. doJustify = function (range, style) {
  10483. var bookmark = range.createBookmark(),
  10484. filterFn = function (node) {
  10485. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10486. };
  10487. range.enlarge(true);
  10488. var bookmark2 = range.createBookmark(),
  10489. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10490. tmpRange = range.cloneRange(),
  10491. tmpNode;
  10492. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10493. if (current.nodeType == 3 || !block(current)) {
  10494. tmpRange.setStartBefore(current);
  10495. while (current && current !== bookmark2.end && !block(current)) {
  10496. tmpNode = current;
  10497. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10498. return !block(node);
  10499. });
  10500. }
  10501. tmpRange.setEndAfter(tmpNode);
  10502. var common = tmpRange.getCommonAncestor();
  10503. if (!domUtils.isBody(common) && block(common)) {
  10504. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10505. current = common;
  10506. } else {
  10507. var p = range.document.createElement('p');
  10508. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10509. var frag = tmpRange.extractContents();
  10510. p.appendChild(frag);
  10511. tmpRange.insertNode(p);
  10512. current = p;
  10513. }
  10514. current = domUtils.getNextDomNode(current, false, filterFn);
  10515. } else {
  10516. current = domUtils.getNextDomNode(current, true, filterFn);
  10517. }
  10518. }
  10519. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10520. };
  10521. UE.commands['justify'] = {
  10522. execCommand:function (cmdName, align) {
  10523. var range = this.selection.getRange(),
  10524. txt;
  10525. //闭合时单独处理
  10526. if (range.collapsed) {
  10527. txt = this.document.createTextNode('p');
  10528. range.insertNode(txt);
  10529. }
  10530. doJustify(range, align);
  10531. if (txt) {
  10532. range.setStartBefore(txt).collapse(true);
  10533. domUtils.remove(txt);
  10534. }
  10535. range.select();
  10536. return true;
  10537. },
  10538. queryCommandValue:function () {
  10539. var startNode = this.selection.getStart(),
  10540. value = domUtils.getComputedStyle(startNode, 'text-align');
  10541. return defaultValue[value] ? value : 'left';
  10542. },
  10543. queryCommandState:function () {
  10544. var start = this.selection.getStart(),
  10545. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10546. return cell? -1:0;
  10547. }
  10548. };
  10549. };
  10550. // plugins/font.js
  10551. /**
  10552. * 字体颜色,背景色,字号,字体,下划线,删除线
  10553. * @file
  10554. * @since 1.2.6.1
  10555. */
  10556. /**
  10557. * 字体颜色
  10558. * @command forecolor
  10559. * @method execCommand
  10560. * @param { String } cmd 命令字符串
  10561. * @param { String } value 色值(必须十六进制)
  10562. * @example
  10563. * ```javascript
  10564. * editor.execCommand( 'forecolor', '#000' );
  10565. * ```
  10566. */
  10567. /**
  10568. * 返回选区字体颜色
  10569. * @command forecolor
  10570. * @method queryCommandValue
  10571. * @param { String } cmd 命令字符串
  10572. * @return { String } 返回字体颜色
  10573. * @example
  10574. * ```javascript
  10575. * editor.queryCommandValue( 'forecolor' );
  10576. * ```
  10577. */
  10578. /**
  10579. * 字体背景颜色
  10580. * @command backcolor
  10581. * @method execCommand
  10582. * @param { String } cmd 命令字符串
  10583. * @param { String } value 色值(必须十六进制)
  10584. * @example
  10585. * ```javascript
  10586. * editor.execCommand( 'backcolor', '#000' );
  10587. * ```
  10588. */
  10589. /**
  10590. * 返回选区字体颜色
  10591. * @command backcolor
  10592. * @method queryCommandValue
  10593. * @param { String } cmd 命令字符串
  10594. * @return { String } 返回字体背景颜色
  10595. * @example
  10596. * ```javascript
  10597. * editor.queryCommandValue( 'backcolor' );
  10598. * ```
  10599. */
  10600. /**
  10601. * 字体大小
  10602. * @command fontsize
  10603. * @method execCommand
  10604. * @param { String } cmd 命令字符串
  10605. * @param { String } value 字体大小
  10606. * @example
  10607. * ```javascript
  10608. * editor.execCommand( 'fontsize', '14px' );
  10609. * ```
  10610. */
  10611. /**
  10612. * 返回选区字体大小
  10613. * @command fontsize
  10614. * @method queryCommandValue
  10615. * @param { String } cmd 命令字符串
  10616. * @return { String } 返回字体大小
  10617. * @example
  10618. * ```javascript
  10619. * editor.queryCommandValue( 'fontsize' );
  10620. * ```
  10621. */
  10622. /**
  10623. * 字体样式
  10624. * @command fontfamily
  10625. * @method execCommand
  10626. * @param { String } cmd 命令字符串
  10627. * @param { String } value 字体样式
  10628. * @example
  10629. * ```javascript
  10630. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10631. * ```
  10632. */
  10633. /**
  10634. * 返回选区字体样式
  10635. * @command fontfamily
  10636. * @method queryCommandValue
  10637. * @param { String } cmd 命令字符串
  10638. * @return { String } 返回字体样式
  10639. * @example
  10640. * ```javascript
  10641. * editor.queryCommandValue( 'fontfamily' );
  10642. * ```
  10643. */
  10644. /**
  10645. * 字体下划线,与删除线互斥
  10646. * @command underline
  10647. * @method execCommand
  10648. * @param { String } cmd 命令字符串
  10649. * @example
  10650. * ```javascript
  10651. * editor.execCommand( 'underline' );
  10652. * ```
  10653. */
  10654. /**
  10655. * 字体删除线,与下划线互斥
  10656. * @command strikethrough
  10657. * @method execCommand
  10658. * @param { String } cmd 命令字符串
  10659. * @example
  10660. * ```javascript
  10661. * editor.execCommand( 'strikethrough' );
  10662. * ```
  10663. */
  10664. /**
  10665. * 字体边框
  10666. * @command fontborder
  10667. * @method execCommand
  10668. * @param { String } cmd 命令字符串
  10669. * @example
  10670. * ```javascript
  10671. * editor.execCommand( 'fontborder' );
  10672. * ```
  10673. */
  10674. UE.plugins['font'] = function () {
  10675. var me = this,
  10676. fonts = {
  10677. 'forecolor': 'color',
  10678. 'backcolor': 'background-color',
  10679. 'fontsize': 'font-size',
  10680. 'fontfamily': 'font-family',
  10681. 'underline': 'text-decoration',
  10682. 'strikethrough': 'text-decoration',
  10683. 'fontborder': 'border'
  10684. },
  10685. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10686. needSetChild = {
  10687. 'forecolor': 'color',
  10688. 'backcolor': 'background-color',
  10689. 'fontsize': 'font-size',
  10690. 'fontfamily': 'font-family'
  10691. };
  10692. me.setOpt({
  10693. 'fontfamily': [
  10694. { name: 'songti', val: '宋体,SimSun'},
  10695. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10696. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10697. { name: 'heiti', val: '黑体, SimHei'},
  10698. { name: 'lishu', val: '隶书, SimLi'},
  10699. { name: 'andaleMono', val: 'andale mono'},
  10700. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10701. { name: 'arialBlack', val: 'arial black,avant garde'},
  10702. { name: 'comicSansMs', val: 'comic sans ms'},
  10703. { name: 'impact', val: 'impact,chicago'},
  10704. { name: 'timesNewRoman', val: 'times new roman'}
  10705. ],
  10706. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10707. });
  10708. function mergeWithParent(node){
  10709. var parent;
  10710. while(parent = node.parentNode){
  10711. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10712. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10713. }) == 1) {
  10714. parent.style.cssText += node.style.cssText;
  10715. domUtils.remove(node,true);
  10716. node = parent;
  10717. }else{
  10718. break;
  10719. }
  10720. }
  10721. }
  10722. function mergeChild(rng,cmdName,value){
  10723. if(needSetChild[cmdName]){
  10724. rng.adjustmentBoundary();
  10725. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10726. var start = rng.startContainer.childNodes[rng.startOffset];
  10727. if(start && domUtils.isTagNode(start,'span')){
  10728. var bk = rng.createBookmark();
  10729. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10730. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10731. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10732. return;
  10733. }
  10734. domUtils.removeStyle(span,needSetChild[cmdName]);
  10735. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10736. domUtils.remove(span,true)
  10737. }
  10738. });
  10739. rng.moveToBookmark(bk)
  10740. }
  10741. }
  10742. }
  10743. }
  10744. function mergesibling(rng,cmdName,value) {
  10745. var collapsed = rng.collapsed,
  10746. bk = rng.createBookmark(), common;
  10747. if (collapsed) {
  10748. common = bk.start.parentNode;
  10749. while (dtd.$inline[common.tagName]) {
  10750. common = common.parentNode;
  10751. }
  10752. } else {
  10753. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10754. }
  10755. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10756. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10757. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10758. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10759. domUtils.remove(span, true);
  10760. }else{
  10761. domUtils.removeStyle(span,'border');
  10762. }
  10763. return
  10764. }
  10765. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10766. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10767. }
  10768. if(!(cmdName=='fontborder' && value=='none')){
  10769. var next = span.nextSibling;
  10770. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10771. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10772. span.appendChild(next);
  10773. next = span.nextSibling;
  10774. continue;
  10775. }
  10776. if (next.style.cssText == span.style.cssText) {
  10777. domUtils.moveChild(next, span);
  10778. domUtils.remove(next);
  10779. }
  10780. if (span.nextSibling === next)
  10781. break;
  10782. next = span.nextSibling;
  10783. }
  10784. }
  10785. mergeWithParent(span);
  10786. if(browser.ie && browser.version > 8 ){
  10787. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10788. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10789. if(parent && !/background-color/.test(span.style.cssText)){
  10790. span.style.backgroundColor = parent.style.backgroundColor;
  10791. }
  10792. }
  10793. });
  10794. rng.moveToBookmark(bk);
  10795. mergeChild(rng,cmdName,value)
  10796. }
  10797. me.addInputRule(function (root) {
  10798. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10799. if (node.tagName == 'font') {
  10800. var cssStyle = [];
  10801. for (var p in node.attrs) {
  10802. switch (p) {
  10803. case 'size':
  10804. cssStyle.push('font-size:' +
  10805. ({
  10806. '1':'10',
  10807. '2':'12',
  10808. '3':'16',
  10809. '4':'18',
  10810. '5':'24',
  10811. '6':'32',
  10812. '7':'48'
  10813. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10814. break;
  10815. case 'color':
  10816. cssStyle.push('color:' + node.attrs[p]);
  10817. break;
  10818. case 'face':
  10819. cssStyle.push('font-family:' + node.attrs[p]);
  10820. break;
  10821. case 'style':
  10822. cssStyle.push(node.attrs[p]);
  10823. }
  10824. }
  10825. node.attrs = {
  10826. 'style': cssStyle.join(';')
  10827. };
  10828. } else {
  10829. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10830. node.attrs = {
  10831. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10832. }
  10833. }
  10834. node.tagName = 'span';
  10835. });
  10836. // utils.each(root.getNodesByTagName('span'), function (node) {
  10837. // var val;
  10838. // if(val = node.getAttr('class')){
  10839. // if(/fontstrikethrough/.test(val)){
  10840. // node.setStyle('text-decoration','line-through');
  10841. // if(node.attrs['class']){
  10842. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10843. // }else{
  10844. // node.setAttr('class')
  10845. // }
  10846. // }
  10847. // if(/fontborder/.test(val)){
  10848. // node.setStyle('border','1px solid #000');
  10849. // if(node.attrs['class']){
  10850. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10851. // }else{
  10852. // node.setAttr('class')
  10853. // }
  10854. // }
  10855. // }
  10856. // });
  10857. });
  10858. // me.addOutputRule(function(root){
  10859. // utils.each(root.getNodesByTagName('span'), function (node) {
  10860. // var val;
  10861. // if(val = node.getStyle('text-decoration')){
  10862. // if(/line-through/.test(val)){
  10863. // if(node.attrs['class']){
  10864. // node.attrs['class'] += ' fontstrikethrough';
  10865. // }else{
  10866. // node.setAttr('class','fontstrikethrough')
  10867. // }
  10868. // }
  10869. //
  10870. // node.setStyle('text-decoration')
  10871. // }
  10872. // if(val = node.getStyle('border')){
  10873. // if(/1px/.test(val) && /solid/.test(val)){
  10874. // if(node.attrs['class']){
  10875. // node.attrs['class'] += ' fontborder';
  10876. //
  10877. // }else{
  10878. // node.setAttr('class','fontborder')
  10879. // }
  10880. // }
  10881. // node.setStyle('border')
  10882. //
  10883. // }
  10884. // });
  10885. // });
  10886. for (var p in fonts) {
  10887. (function (cmd, style) {
  10888. UE.commands[cmd] = {
  10889. execCommand: function (cmdName, value) {
  10890. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10891. cmdName == 'fontborder' ? '1px solid #000' :
  10892. 'line-through');
  10893. var me = this,
  10894. range = this.selection.getRange(),
  10895. text;
  10896. if (value == 'default') {
  10897. if (range.collapsed) {
  10898. text = me.document.createTextNode('font');
  10899. range.insertNode(text).select();
  10900. }
  10901. me.execCommand('removeFormat', 'span,a', style);
  10902. if (text) {
  10903. range.setStartBefore(text).collapse(true);
  10904. domUtils.remove(text);
  10905. }
  10906. mergesibling(range,cmdName,value);
  10907. range.select()
  10908. } else {
  10909. if (!range.collapsed) {
  10910. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10911. me.execCommand('removeFormat', 'span,a', style);
  10912. }
  10913. range = me.selection.getRange();
  10914. range.applyInlineStyle('span', {'style': style + ':' + value});
  10915. mergesibling(range, cmdName,value);
  10916. range.select();
  10917. } else {
  10918. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10919. text = me.document.createTextNode('font');
  10920. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10921. //for ie hack when enter
  10922. range.insertNode(text);
  10923. if (needCmd[cmd]) {
  10924. range.selectNode(text).select();
  10925. me.execCommand('removeFormat', 'span,a', style, null);
  10926. span = domUtils.findParentByTagName(text, 'span', true);
  10927. range.setStartBefore(text);
  10928. }
  10929. span && (span.style.cssText += ';' + style + ':' + value);
  10930. range.collapse(true).select();
  10931. } else {
  10932. range.insertNode(text);
  10933. range.selectNode(text).select();
  10934. span = range.document.createElement('span');
  10935. if (needCmd[cmd]) {
  10936. //a标签内的不处理跳过
  10937. if (domUtils.findParentByTagName(text, 'a', true)) {
  10938. range.setStartBefore(text).setCursor();
  10939. domUtils.remove(text);
  10940. return;
  10941. }
  10942. me.execCommand('removeFormat', 'span,a', style);
  10943. }
  10944. span.style.cssText = style + ':' + value;
  10945. text.parentNode.insertBefore(span, text);
  10946. //修复,span套span 但样式不继承的问题
  10947. if (!browser.ie || browser.ie && browser.version == 9) {
  10948. var spanParent = span.parentNode;
  10949. while (!domUtils.isBlockElm(spanParent)) {
  10950. if (spanParent.tagName == 'SPAN') {
  10951. //opera合并style不会加入";"
  10952. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10953. }
  10954. spanParent = spanParent.parentNode;
  10955. }
  10956. }
  10957. if (opera) {
  10958. setTimeout(function () {
  10959. range.setStart(span, 0).collapse(true);
  10960. mergesibling(range, cmdName,value);
  10961. range.select();
  10962. });
  10963. } else {
  10964. range.setStart(span, 0).collapse(true);
  10965. mergesibling(range,cmdName,value);
  10966. range.select();
  10967. }
  10968. //trace:981
  10969. //domUtils.mergeToParent(span)
  10970. }
  10971. domUtils.remove(text);
  10972. }
  10973. }
  10974. return true;
  10975. },
  10976. queryCommandValue: function (cmdName) {
  10977. var startNode = this.selection.getStart();
  10978. //trace:946
  10979. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  10980. var tmpNode = startNode, value;
  10981. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  10982. if (tmpNode.nodeType == 1) {
  10983. value = domUtils.getComputedStyle(tmpNode, style);
  10984. if (value != 'none') {
  10985. return value;
  10986. }
  10987. }
  10988. tmpNode = tmpNode.parentNode;
  10989. }
  10990. return 'none';
  10991. }
  10992. if (cmdName == 'fontborder') {
  10993. var tmp = startNode, val;
  10994. while (tmp && dtd.$inline[tmp.tagName]) {
  10995. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  10996. if (/1px/.test(val) && /solid/.test(val)) {
  10997. return val;
  10998. }
  10999. }
  11000. tmp = tmp.parentNode;
  11001. }
  11002. return ''
  11003. }
  11004. if( cmdName == 'FontSize' ) {
  11005. var styleVal = domUtils.getComputedStyle(startNode, style),
  11006. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  11007. if( tmp ) {
  11008. return Math.floor( tmp[1] ) + tmp[2];
  11009. }
  11010. return styleVal;
  11011. }
  11012. return domUtils.getComputedStyle(startNode, style);
  11013. },
  11014. queryCommandState: function (cmdName) {
  11015. if (!needCmd[cmdName])
  11016. return 0;
  11017. var val = this.queryCommandValue(cmdName);
  11018. if (cmdName == 'fontborder') {
  11019. return /1px/.test(val) && /solid/.test(val)
  11020. } else {
  11021. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11022. }
  11023. }
  11024. };
  11025. })(p, fonts[p]);
  11026. }
  11027. };
  11028. // plugins/link.js
  11029. /**
  11030. * 超链接
  11031. * @file
  11032. * @since 1.2.6.1
  11033. */
  11034. /**
  11035. * 插入超链接
  11036. * @command link
  11037. * @method execCommand
  11038. * @param { String } cmd 命令字符串
  11039. * @param { Object } options 设置自定义属性,例如:url、title、target
  11040. * @example
  11041. * ```javascript
  11042. * editor.execCommand( 'link', '{
  11043. * url:'ueditor.baidu.com',
  11044. * title:'ueditor',
  11045. * target:'_blank'
  11046. * }' );
  11047. * ```
  11048. */
  11049. /**
  11050. * 返回当前选中的第一个超链接节点
  11051. * @command link
  11052. * @method queryCommandValue
  11053. * @param { String } cmd 命令字符串
  11054. * @return { Element } 超链接节点
  11055. * @example
  11056. * ```javascript
  11057. * editor.queryCommandValue( 'link' );
  11058. * ```
  11059. */
  11060. /**
  11061. * 取消超链接
  11062. * @command unlink
  11063. * @method execCommand
  11064. * @param { String } cmd 命令字符串
  11065. * @example
  11066. * ```javascript
  11067. * editor.execCommand( 'unlink');
  11068. * ```
  11069. */
  11070. UE.plugins['link'] = function(){
  11071. function optimize( range ) {
  11072. var start = range.startContainer,end = range.endContainer;
  11073. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11074. range.setStartBefore( start );
  11075. }
  11076. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11077. range.setEndAfter( end );
  11078. }
  11079. }
  11080. UE.commands['unlink'] = {
  11081. execCommand : function() {
  11082. var range = this.selection.getRange(),
  11083. bookmark;
  11084. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11085. return;
  11086. }
  11087. bookmark = range.createBookmark();
  11088. optimize( range );
  11089. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11090. },
  11091. queryCommandState : function(){
  11092. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11093. }
  11094. };
  11095. function doLink(range,opt,me){
  11096. var rngClone = range.cloneRange(),
  11097. link = me.queryCommandValue('link');
  11098. optimize( range = range.adjustmentBoundary() );
  11099. var start = range.startContainer;
  11100. if(start.nodeType == 1 && link){
  11101. start = start.childNodes[range.startOffset];
  11102. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11103. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11104. }
  11105. }
  11106. if( !rngClone.collapsed || link){
  11107. range.removeInlineStyle( 'a' );
  11108. rngClone = range.cloneRange();
  11109. }
  11110. if ( rngClone.collapsed ) {
  11111. var a = range.document.createElement( 'a'),
  11112. text = '';
  11113. if(opt.textValue){
  11114. text = utils.html(opt.textValue);
  11115. delete opt.textValue;
  11116. }else{
  11117. text = utils.html(opt.href);
  11118. }
  11119. domUtils.setAttributes( a, opt );
  11120. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11121. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11122. range.setStartAfter(start).collapse(true);
  11123. }
  11124. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11125. range.insertNode(a).selectNode( a );
  11126. } else {
  11127. range.applyInlineStyle( 'a', opt );
  11128. }
  11129. }
  11130. UE.commands['link'] = {
  11131. execCommand : function( cmdName, opt ) {
  11132. var range;
  11133. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11134. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11135. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11136. doLink(range=this.selection.getRange(),opt,this);
  11137. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11138. range.collapse().select(true);
  11139. },
  11140. queryCommandValue : function() {
  11141. var range = this.selection.getRange(),
  11142. node;
  11143. if ( range.collapsed ) {
  11144. // node = this.selection.getStart();
  11145. //在ie下getstart()取值偏上了
  11146. node = range.startContainer;
  11147. node = node.nodeType == 1 ? node : node.parentNode;
  11148. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11149. return node;
  11150. }
  11151. } else {
  11152. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11153. range.shrinkBoundary();
  11154. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11155. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11156. common = range.getCommonAncestor();
  11157. node = domUtils.findParentByTagName( common, 'a', true );
  11158. if ( !node && common.nodeType == 1){
  11159. var as = common.getElementsByTagName( 'a' ),
  11160. ps,pe;
  11161. for ( var i = 0,ci; ci = as[i++]; ) {
  11162. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11163. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11164. &&
  11165. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11166. ) {
  11167. node = ci;
  11168. break;
  11169. }
  11170. }
  11171. }
  11172. return node;
  11173. }
  11174. },
  11175. queryCommandState : function() {
  11176. //判断如果是视频的话连接不可用
  11177. //fix 853
  11178. var img = this.selection.getRange().getClosedNode(),
  11179. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11180. return flag ? -1 : 0;
  11181. }
  11182. };
  11183. };
  11184. // plugins/iframe.js
  11185. ///import core
  11186. ///import plugins\inserthtml.js
  11187. ///commands 插入框架
  11188. ///commandsName InsertFrame
  11189. ///commandsTitle 插入Iframe
  11190. ///commandsDialog dialogs\insertframe
  11191. UE.plugins['insertframe'] = function() {
  11192. var me =this;
  11193. function deleteIframe(){
  11194. me._iframe && delete me._iframe;
  11195. }
  11196. me.addListener("selectionchange",function(){
  11197. deleteIframe();
  11198. });
  11199. };
  11200. // plugins/scrawl.js
  11201. ///import core
  11202. ///commands 涂鸦
  11203. ///commandsName Scrawl
  11204. ///commandsTitle 涂鸦
  11205. ///commandsDialog dialogs\scrawl
  11206. UE.commands['scrawl'] = {
  11207. queryCommandState : function(){
  11208. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11209. }
  11210. };
  11211. // plugins/removeformat.js
  11212. /**
  11213. * 清除格式
  11214. * @file
  11215. * @since 1.2.6.1
  11216. */
  11217. /**
  11218. * 清除文字样式
  11219. * @command removeformat
  11220. * @method execCommand
  11221. * @param { String } cmd 命令字符串
  11222. * @param {String} tags 以逗号隔开的标签。如:strong
  11223. * @param {String} style 样式如:color
  11224. * @param {String} attrs 属性如:width
  11225. * @example
  11226. * ```javascript
  11227. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11228. * ```
  11229. */
  11230. UE.plugins['removeformat'] = function(){
  11231. var me = this;
  11232. me.setOpt({
  11233. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11234. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11235. });
  11236. me.commands['removeformat'] = {
  11237. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11238. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11239. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11240. range = new dom.Range( this.document ),
  11241. bookmark,node,parent,
  11242. filter = function( node ) {
  11243. return node.nodeType == 1;
  11244. };
  11245. function isRedundantSpan (node) {
  11246. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11247. return 0;
  11248. }
  11249. if (browser.ie) {
  11250. //ie 下判断实效,所以只能简单用style来判断
  11251. //return node.style.cssText == '' ? 1 : 0;
  11252. var attrs = node.attributes;
  11253. if ( attrs.length ) {
  11254. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11255. if ( attrs[i].specified ) {
  11256. return 0;
  11257. }
  11258. }
  11259. return 1;
  11260. }
  11261. }
  11262. return !node.attributes.length;
  11263. }
  11264. function doRemove( range ) {
  11265. var bookmark1 = range.createBookmark();
  11266. if ( range.collapsed ) {
  11267. range.enlarge( true );
  11268. }
  11269. //不能把a标签切了
  11270. if(!notIncludeA){
  11271. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11272. if(aNode){
  11273. range.setStartBefore(aNode);
  11274. }
  11275. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11276. if(aNode){
  11277. range.setEndAfter(aNode);
  11278. }
  11279. }
  11280. bookmark = range.createBookmark();
  11281. node = bookmark.start;
  11282. //切开始
  11283. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11284. domUtils.breakParent( node, parent );
  11285. domUtils.clearEmptySibling( node );
  11286. }
  11287. if ( bookmark.end ) {
  11288. //切结束
  11289. node = bookmark.end;
  11290. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11291. domUtils.breakParent( node, parent );
  11292. domUtils.clearEmptySibling( node );
  11293. }
  11294. //开始去除样式
  11295. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11296. next;
  11297. while ( current ) {
  11298. if ( current == bookmark.end ) {
  11299. break;
  11300. }
  11301. next = domUtils.getNextDomNode( current, true, filter );
  11302. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11303. if ( tagReg.test( current.tagName ) ) {
  11304. if ( style ) {
  11305. domUtils.removeStyle( current, style );
  11306. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11307. domUtils.remove( current, true );
  11308. }
  11309. } else {
  11310. domUtils.remove( current, true );
  11311. }
  11312. } else {
  11313. //trace:939 不能把list上的样式去掉
  11314. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11315. domUtils.removeAttributes( current, removeFormatAttributes );
  11316. if ( isRedundantSpan( current ) ){
  11317. domUtils.remove( current, true );
  11318. }
  11319. }
  11320. }
  11321. }
  11322. current = next;
  11323. }
  11324. }
  11325. //trace:1035
  11326. //trace:1096 不能把td上的样式去掉,比如边框
  11327. var pN = bookmark.start.parentNode;
  11328. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11329. domUtils.removeAttributes( pN,removeFormatAttributes );
  11330. }
  11331. pN = bookmark.end.parentNode;
  11332. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11333. domUtils.removeAttributes( pN,removeFormatAttributes );
  11334. }
  11335. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11336. //清除冗余的代码 <b><bookmark></b>
  11337. var node = range.startContainer,
  11338. tmp,
  11339. collapsed = range.collapsed;
  11340. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11341. tmp = node.parentNode;
  11342. range.setStartBefore(node);
  11343. //trace:937
  11344. //更新结束边界
  11345. if(range.startContainer === range.endContainer){
  11346. range.endOffset--;
  11347. }
  11348. domUtils.remove(node);
  11349. node = tmp;
  11350. }
  11351. if(!collapsed){
  11352. node = range.endContainer;
  11353. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11354. tmp = node.parentNode;
  11355. range.setEndBefore(node);
  11356. domUtils.remove(node);
  11357. node = tmp;
  11358. }
  11359. }
  11360. }
  11361. range = this.selection.getRange();
  11362. doRemove( range );
  11363. range.select();
  11364. }
  11365. };
  11366. };
  11367. // plugins/blockquote.js
  11368. /**
  11369. * 添加引用
  11370. * @file
  11371. * @since 1.2.6.1
  11372. */
  11373. /**
  11374. * 添加引用
  11375. * @command blockquote
  11376. * @method execCommand
  11377. * @param { String } cmd 命令字符串
  11378. * @example
  11379. * ```javascript
  11380. * editor.execCommand( 'blockquote' );
  11381. * ```
  11382. */
  11383. /**
  11384. * 添加引用
  11385. * @command blockquote
  11386. * @method execCommand
  11387. * @param { String } cmd 命令字符串
  11388. * @param { Object } attrs 节点属性
  11389. * @example
  11390. * ```javascript
  11391. * editor.execCommand( 'blockquote',{
  11392. * style: "color: red;"
  11393. * } );
  11394. * ```
  11395. */
  11396. UE.plugins['blockquote'] = function(){
  11397. var me = this;
  11398. function getObj(editor){
  11399. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11400. }
  11401. me.commands['blockquote'] = {
  11402. execCommand : function( cmdName, attrs ) {
  11403. var range = this.selection.getRange(),
  11404. obj = getObj(this),
  11405. blockquote = dtd.blockquote,
  11406. bookmark = range.createBookmark();
  11407. if ( obj ) {
  11408. var start = range.startContainer,
  11409. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11410. end = range.endContainer,
  11411. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11412. //处理一下li
  11413. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11414. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11415. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11416. domUtils.remove(obj,true);
  11417. }else{
  11418. domUtils.breakParent(startBlock,obj);
  11419. }
  11420. if(startBlock !== endBlock){
  11421. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11422. if(obj){
  11423. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11424. obj.parentNode && domUtils.remove(obj,true);
  11425. }else{
  11426. domUtils.breakParent(endBlock,obj);
  11427. }
  11428. }
  11429. }
  11430. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11431. for(var i=0,bi;bi=blockquotes[i++];){
  11432. if(!bi.childNodes.length){
  11433. domUtils.remove(bi);
  11434. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11435. domUtils.remove(bi,true);
  11436. }
  11437. }
  11438. } else {
  11439. var tmpRange = range.cloneRange(),
  11440. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11441. preNode = node,
  11442. doEnd = 1;
  11443. //调整开始
  11444. while ( 1 ) {
  11445. if ( domUtils.isBody(node) ) {
  11446. if ( preNode !== node ) {
  11447. if ( range.collapsed ) {
  11448. tmpRange.selectNode( preNode );
  11449. doEnd = 0;
  11450. } else {
  11451. tmpRange.setStartBefore( preNode );
  11452. }
  11453. }else{
  11454. tmpRange.setStart(node,0);
  11455. }
  11456. break;
  11457. }
  11458. if ( !blockquote[node.tagName] ) {
  11459. if ( range.collapsed ) {
  11460. tmpRange.selectNode( preNode );
  11461. } else{
  11462. tmpRange.setStartBefore( preNode);
  11463. }
  11464. break;
  11465. }
  11466. preNode = node;
  11467. node = node.parentNode;
  11468. }
  11469. //调整结束
  11470. if ( doEnd ) {
  11471. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11472. while ( 1 ) {
  11473. if ( domUtils.isBody( node ) ) {
  11474. if ( preNode !== node ) {
  11475. tmpRange.setEndAfter( preNode );
  11476. } else {
  11477. tmpRange.setEnd( node, node.childNodes.length );
  11478. }
  11479. break;
  11480. }
  11481. if ( !blockquote[node.tagName] ) {
  11482. tmpRange.setEndAfter( preNode );
  11483. break;
  11484. }
  11485. preNode = node;
  11486. node = node.parentNode;
  11487. }
  11488. }
  11489. node = range.document.createElement( 'blockquote' );
  11490. domUtils.setAttributes( node, attrs );
  11491. node.appendChild( tmpRange.extractContents() );
  11492. tmpRange.insertNode( node );
  11493. //去除重复的
  11494. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11495. for(var i=0,ci;ci=childs[i++];){
  11496. if(ci.parentNode){
  11497. domUtils.remove(ci,true);
  11498. }
  11499. }
  11500. }
  11501. range.moveToBookmark( bookmark ).select();
  11502. },
  11503. queryCommandState : function() {
  11504. return getObj(this) ? 1 : 0;
  11505. }
  11506. };
  11507. };
  11508. // plugins/convertcase.js
  11509. /**
  11510. * 大小写转换
  11511. * @file
  11512. * @since 1.2.6.1
  11513. */
  11514. /**
  11515. * 把选区内文本变大写,与“tolowercase”命令互斥
  11516. * @command touppercase
  11517. * @method execCommand
  11518. * @param { String } cmd 命令字符串
  11519. * @example
  11520. * ```javascript
  11521. * editor.execCommand( 'touppercase' );
  11522. * ```
  11523. */
  11524. /**
  11525. * 把选区内文本变小写,与“touppercase”命令互斥
  11526. * @command tolowercase
  11527. * @method execCommand
  11528. * @param { String } cmd 命令字符串
  11529. * @example
  11530. * ```javascript
  11531. * editor.execCommand( 'tolowercase' );
  11532. * ```
  11533. */
  11534. UE.commands['touppercase'] =
  11535. UE.commands['tolowercase'] = {
  11536. execCommand:function (cmd) {
  11537. var me = this;
  11538. var rng = me.selection.getRange();
  11539. if(rng.collapsed){
  11540. return rng;
  11541. }
  11542. var bk = rng.createBookmark(),
  11543. bkEnd = bk.end,
  11544. filterFn = function( node ) {
  11545. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11546. },
  11547. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11548. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11549. if ( curNode.nodeType == 3 ) {
  11550. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11551. }
  11552. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11553. if(curNode === bkEnd){
  11554. break;
  11555. }
  11556. }
  11557. rng.moveToBookmark(bk).select();
  11558. }
  11559. };
  11560. // plugins/indent.js
  11561. /**
  11562. * 首行缩进
  11563. * @file
  11564. * @since 1.2.6.1
  11565. */
  11566. /**
  11567. * 缩进
  11568. * @command indent
  11569. * @method execCommand
  11570. * @param { String } cmd 命令字符串
  11571. * @example
  11572. * ```javascript
  11573. * editor.execCommand( 'indent' );
  11574. * ```
  11575. */
  11576. UE.commands['indent'] = {
  11577. execCommand : function() {
  11578. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11579. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11580. },
  11581. queryCommandState : function() {
  11582. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11583. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11584. }
  11585. };
  11586. // plugins/print.js
  11587. /**
  11588. * 打印
  11589. * @file
  11590. * @since 1.2.6.1
  11591. */
  11592. /**
  11593. * 打印
  11594. * @command print
  11595. * @method execCommand
  11596. * @param { String } cmd 命令字符串
  11597. * @example
  11598. * ```javascript
  11599. * editor.execCommand( 'print' );
  11600. * ```
  11601. */
  11602. UE.commands['print'] = {
  11603. execCommand : function(){
  11604. this.window.print();
  11605. },
  11606. notNeedUndo : 1
  11607. };
  11608. // plugins/preview.js
  11609. /**
  11610. * 预览
  11611. * @file
  11612. * @since 1.2.6.1
  11613. */
  11614. /**
  11615. * 预览
  11616. * @command preview
  11617. * @method execCommand
  11618. * @param { String } cmd 命令字符串
  11619. * @example
  11620. * ```javascript
  11621. * editor.execCommand( 'preview' );
  11622. * ```
  11623. */
  11624. UE.commands['preview'] = {
  11625. execCommand : function(){
  11626. var w = window.open('', '_blank', ''),
  11627. d = w.document;
  11628. d.open();
  11629. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11630. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11631. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11632. d.close();
  11633. },
  11634. notNeedUndo : 1
  11635. };
  11636. // plugins/selectall.js
  11637. /**
  11638. * 全选
  11639. * @file
  11640. * @since 1.2.6.1
  11641. */
  11642. /**
  11643. * 选中所有内容
  11644. * @command selectall
  11645. * @method execCommand
  11646. * @param { String } cmd 命令字符串
  11647. * @example
  11648. * ```javascript
  11649. * editor.execCommand( 'selectall' );
  11650. * ```
  11651. */
  11652. UE.plugins['selectall'] = function(){
  11653. var me = this;
  11654. me.commands['selectall'] = {
  11655. execCommand : function(){
  11656. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11657. var me = this,body = me.body,
  11658. range = me.selection.getRange();
  11659. range.selectNodeContents(body);
  11660. if(domUtils.isEmptyBlock(body)){
  11661. //opera不能自动合并到元素的里边,要手动处理一下
  11662. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11663. range.setStartAtFirst(body.firstChild);
  11664. }
  11665. range.collapse(true);
  11666. }
  11667. range.select(true);
  11668. },
  11669. notNeedUndo : 1
  11670. };
  11671. //快捷键
  11672. me.addshortcutkey({
  11673. "selectAll" : "ctrl+65"
  11674. });
  11675. };
  11676. // plugins/paragraph.js
  11677. /**
  11678. * 段落样式
  11679. * @file
  11680. * @since 1.2.6.1
  11681. */
  11682. /**
  11683. * 段落格式
  11684. * @command paragraph
  11685. * @method execCommand
  11686. * @param { String } cmd 命令字符串
  11687. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11688. * @param {Object} attrs 标签的属性
  11689. * @example
  11690. * ```javascript
  11691. * editor.execCommand( 'Paragraph','h1','{
  11692. * class:'test'
  11693. * }' );
  11694. * ```
  11695. */
  11696. /**
  11697. * 返回选区内节点标签名
  11698. * @command paragraph
  11699. * @method queryCommandValue
  11700. * @param { String } cmd 命令字符串
  11701. * @return { String } 节点标签名
  11702. * @example
  11703. * ```javascript
  11704. * editor.queryCommandValue( 'Paragraph' );
  11705. * ```
  11706. */
  11707. UE.plugins['paragraph'] = function() {
  11708. var me = this,
  11709. block = domUtils.isBlockElm,
  11710. notExchange = ['TD','LI','PRE'],
  11711. doParagraph = function(range,style,attrs,sourceCmdName){
  11712. var bookmark = range.createBookmark(),
  11713. filterFn = function( node ) {
  11714. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11715. },
  11716. para;
  11717. range.enlarge( true );
  11718. var bookmark2 = range.createBookmark(),
  11719. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11720. tmpRange = range.cloneRange(),
  11721. tmpNode;
  11722. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11723. if ( current.nodeType == 3 || !block( current ) ) {
  11724. tmpRange.setStartBefore( current );
  11725. while ( current && current !== bookmark2.end && !block( current ) ) {
  11726. tmpNode = current;
  11727. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11728. return !block( node );
  11729. } );
  11730. }
  11731. tmpRange.setEndAfter( tmpNode );
  11732. para = range.document.createElement( style );
  11733. if(attrs){
  11734. domUtils.setAttributes(para,attrs);
  11735. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11736. para.style.cssText = attrs.style;
  11737. }
  11738. }
  11739. para.appendChild( tmpRange.extractContents() );
  11740. //需要内容占位
  11741. if(domUtils.isEmptyNode(para)){
  11742. domUtils.fillChar(range.document,para);
  11743. }
  11744. tmpRange.insertNode( para );
  11745. var parent = para.parentNode;
  11746. //如果para上一级是一个block元素且不是body,td就删除它
  11747. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11748. //存储dir,style
  11749. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11750. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11751. //trace:1070
  11752. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11753. //trace:1030
  11754. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11755. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11756. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11757. }
  11758. //trace:1706 选择的就是h1-6要删除
  11759. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11760. domUtils.setAttributes(parent,attrs);
  11761. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11762. parent.style.cssText = attrs.style;
  11763. }
  11764. domUtils.remove(para,true);
  11765. para = parent;
  11766. }else{
  11767. domUtils.remove( para.parentNode, true );
  11768. }
  11769. }
  11770. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11771. current = parent;
  11772. }else{
  11773. current = para;
  11774. }
  11775. current = domUtils.getNextDomNode( current, false, filterFn );
  11776. } else {
  11777. current = domUtils.getNextDomNode( current, true, filterFn );
  11778. }
  11779. }
  11780. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11781. };
  11782. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11783. me.commands['paragraph'] = {
  11784. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11785. var range = this.selection.getRange();
  11786. //闭合时单独处理
  11787. if(range.collapsed){
  11788. var txt = this.document.createTextNode('p');
  11789. range.insertNode(txt);
  11790. //去掉冗余的fillchar
  11791. if(browser.ie){
  11792. var node = txt.previousSibling;
  11793. if(node && domUtils.isWhitespace(node)){
  11794. domUtils.remove(node);
  11795. }
  11796. node = txt.nextSibling;
  11797. if(node && domUtils.isWhitespace(node)){
  11798. domUtils.remove(node);
  11799. }
  11800. }
  11801. }
  11802. range = doParagraph(range,style,attrs,sourceCmdName);
  11803. if(txt){
  11804. range.setStartBefore(txt).collapse(true);
  11805. pN = txt.parentNode;
  11806. domUtils.remove(txt);
  11807. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11808. domUtils.fillNode(this.document,pN);
  11809. }
  11810. }
  11811. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11812. var child = range.startContainer.childNodes[range.startOffset];
  11813. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11814. range.setStart(child,0).collapse(true);
  11815. }
  11816. }
  11817. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11818. range.select();
  11819. return true;
  11820. },
  11821. queryCommandValue : function() {
  11822. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11823. return node ? node.tagName.toLowerCase() : '';
  11824. }
  11825. };
  11826. };
  11827. // plugins/directionality.js
  11828. /**
  11829. * 设置文字输入的方向的插件
  11830. * @file
  11831. * @since 1.2.6.1
  11832. */
  11833. (function() {
  11834. var block = domUtils.isBlockElm ,
  11835. getObj = function(editor){
  11836. // var startNode = editor.selection.getStart(),
  11837. // parents;
  11838. // if ( startNode ) {
  11839. // //查找所有的是block的父亲节点
  11840. // parents = domUtils.findParents( startNode, true, block, true );
  11841. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11842. // if ( ci.getAttribute( 'dir' ) ) {
  11843. // return ci;
  11844. // }
  11845. // }
  11846. // }
  11847. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n && n.nodeType == 1 && n.getAttribute('dir')});
  11848. },
  11849. doDirectionality = function(range,editor,forward){
  11850. var bookmark,
  11851. filterFn = function( node ) {
  11852. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11853. },
  11854. obj = getObj( editor );
  11855. if ( obj && range.collapsed ) {
  11856. obj.setAttribute( 'dir', forward );
  11857. return range;
  11858. }
  11859. bookmark = range.createBookmark();
  11860. range.enlarge( true );
  11861. var bookmark2 = range.createBookmark(),
  11862. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11863. tmpRange = range.cloneRange(),
  11864. tmpNode;
  11865. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11866. if ( current.nodeType == 3 || !block( current ) ) {
  11867. tmpRange.setStartBefore( current );
  11868. while ( current && current !== bookmark2.end && !block( current ) ) {
  11869. tmpNode = current;
  11870. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11871. return !block( node );
  11872. } );
  11873. }
  11874. tmpRange.setEndAfter( tmpNode );
  11875. var common = tmpRange.getCommonAncestor();
  11876. if ( !domUtils.isBody( common ) && block( common ) ) {
  11877. //遍历到了block节点
  11878. common.setAttribute( 'dir', forward );
  11879. current = common;
  11880. } else {
  11881. //没有遍历到,添加一个block节点
  11882. var p = range.document.createElement( 'p' );
  11883. p.setAttribute( 'dir', forward );
  11884. var frag = tmpRange.extractContents();
  11885. p.appendChild( frag );
  11886. tmpRange.insertNode( p );
  11887. current = p;
  11888. }
  11889. current = domUtils.getNextDomNode( current, false, filterFn );
  11890. } else {
  11891. current = domUtils.getNextDomNode( current, true, filterFn );
  11892. }
  11893. }
  11894. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11895. };
  11896. /**
  11897. * 文字输入方向
  11898. * @command directionality
  11899. * @method execCommand
  11900. * @param { String } cmdName 命令字符串
  11901. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11902. * @example
  11903. * ```javascript
  11904. * editor.execCommand( 'directionality', 'ltr');
  11905. * ```
  11906. */
  11907. /**
  11908. * 查询当前选区的文字输入方向
  11909. * @command directionality
  11910. * @method queryCommandValue
  11911. * @param { String } cmdName 命令字符串
  11912. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11913. * @example
  11914. * ```javascript
  11915. * editor.queryCommandValue( 'directionality');
  11916. * ```
  11917. */
  11918. UE.commands['directionality'] = {
  11919. execCommand : function( cmdName,forward ) {
  11920. var range = this.selection.getRange();
  11921. //闭合时单独处理
  11922. if(range.collapsed){
  11923. var txt = this.document.createTextNode('d');
  11924. range.insertNode(txt);
  11925. }
  11926. doDirectionality(range,this,forward);
  11927. if(txt){
  11928. range.setStartBefore(txt).collapse(true);
  11929. domUtils.remove(txt);
  11930. }
  11931. range.select();
  11932. return true;
  11933. },
  11934. queryCommandValue : function() {
  11935. var node = getObj(this);
  11936. return node ? node.getAttribute('dir') : 'ltr';
  11937. }
  11938. };
  11939. })();
  11940. // plugins/horizontal.js
  11941. /**
  11942. * 插入分割线插件
  11943. * @file
  11944. * @since 1.2.6.1
  11945. */
  11946. /**
  11947. * 插入分割线
  11948. * @command horizontal
  11949. * @method execCommand
  11950. * @param { String } cmdName 命令字符串
  11951. * @example
  11952. * ```javascript
  11953. * editor.execCommand( 'horizontal' );
  11954. * ```
  11955. */
  11956. UE.plugins['horizontal'] = function(){
  11957. var me = this;
  11958. me.commands['horizontal'] = {
  11959. execCommand : function( cmdName ) {
  11960. var me = this;
  11961. if(me.queryCommandState(cmdName)!==-1){
  11962. me.execCommand('insertHtml','<hr>');
  11963. var range = me.selection.getRange(),
  11964. start = range.startContainer;
  11965. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  11966. var tmp;
  11967. if(tmp = start.childNodes[range.startOffset - 1]){
  11968. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  11969. if(me.options.enterTag == 'p'){
  11970. tmp = me.document.createElement('p');
  11971. range.insertNode(tmp);
  11972. range.setStart(tmp,0).setCursor();
  11973. }else{
  11974. tmp = me.document.createElement('br');
  11975. range.insertNode(tmp);
  11976. range.setStartBefore(tmp).setCursor();
  11977. }
  11978. }
  11979. }
  11980. }
  11981. return true;
  11982. }
  11983. },
  11984. //边界在table里不能加分隔线
  11985. queryCommandState : function() {
  11986. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  11987. }
  11988. };
  11989. // me.addListener('delkeyup',function(){
  11990. // var rng = this.selection.getRange();
  11991. // if(browser.ie && browser.version > 8){
  11992. // rng.txtToElmBoundary(true);
  11993. // if(domUtils.isStartInblock(rng)){
  11994. // var tmpNode = rng.startContainer;
  11995. // var pre = tmpNode.previousSibling;
  11996. // if(pre && domUtils.isTagNode(pre,'hr')){
  11997. // domUtils.remove(pre);
  11998. // rng.select();
  11999. // return;
  12000. // }
  12001. // }
  12002. // }
  12003. // if(domUtils.isBody(rng.startContainer)){
  12004. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12005. // if(hr && hr.nodeName == 'HR'){
  12006. // var next = hr.nextSibling;
  12007. // if(next){
  12008. // rng.setStart(next,0)
  12009. // }else if(hr.previousSibling){
  12010. // rng.setStartAtLast(hr.previousSibling)
  12011. // }else{
  12012. // var p = this.document.createElement('p');
  12013. // hr.parentNode.insertBefore(p,hr);
  12014. // domUtils.fillNode(this.document,p);
  12015. // rng.setStart(p,0);
  12016. // }
  12017. // domUtils.remove(hr);
  12018. // rng.setCursor(false,true);
  12019. // }
  12020. // }
  12021. // })
  12022. me.addListener('delkeydown',function(name,evt){
  12023. var rng = this.selection.getRange();
  12024. rng.txtToElmBoundary(true);
  12025. if(domUtils.isStartInblock(rng)){
  12026. var tmpNode = rng.startContainer;
  12027. var pre = tmpNode.previousSibling;
  12028. if(pre && domUtils.isTagNode(pre,'hr')){
  12029. domUtils.remove(pre);
  12030. rng.select();
  12031. domUtils.preventDefault(evt);
  12032. return true;
  12033. }
  12034. }
  12035. })
  12036. };
  12037. // plugins/time.js
  12038. /**
  12039. * 插入时间和日期
  12040. * @file
  12041. * @since 1.2.6.1
  12042. */
  12043. /**
  12044. * 插入时间,默认格式:12:59:59
  12045. * @command time
  12046. * @method execCommand
  12047. * @param { String } cmd 命令字符串
  12048. * @example
  12049. * ```javascript
  12050. * editor.execCommand( 'time');
  12051. * ```
  12052. */
  12053. /**
  12054. * 插入日期,默认格式:2013-08-30
  12055. * @command date
  12056. * @method execCommand
  12057. * @param { String } cmd 命令字符串
  12058. * @example
  12059. * ```javascript
  12060. * editor.execCommand( 'date');
  12061. * ```
  12062. */
  12063. UE.commands['time'] = UE.commands["date"] = {
  12064. execCommand : function(cmd, format){
  12065. var date = new Date;
  12066. function formatTime(date, format) {
  12067. var hh = ('0' + date.getHours()).slice(-2),
  12068. ii = ('0' + date.getMinutes()).slice(-2),
  12069. ss = ('0' + date.getSeconds()).slice(-2);
  12070. format = format || 'hh:ii:ss';
  12071. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12072. }
  12073. function formatDate(date, format) {
  12074. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12075. yy = yyyy.slice(-2),
  12076. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12077. dd = ('0' + date.getDate()).slice(-2);
  12078. format = format || 'yyyy-mm-dd';
  12079. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12080. }
  12081. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12082. }
  12083. };
  12084. // plugins/rowspacing.js
  12085. /**
  12086. * 段前段后间距插件
  12087. * @file
  12088. * @since 1.2.6.1
  12089. */
  12090. /**
  12091. * 设置段间距
  12092. * @command rowspacing
  12093. * @method execCommand
  12094. * @param { String } cmd 命令字符串
  12095. * @param { String } value 段间距的值,以px为单位
  12096. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12097. * @example
  12098. * ```javascript
  12099. * editor.execCommand( 'rowspacing', '10', 'top' );
  12100. * ```
  12101. */
  12102. UE.plugins['rowspacing'] = function(){
  12103. var me = this;
  12104. me.setOpt({
  12105. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12106. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12107. });
  12108. me.commands['rowspacing'] = {
  12109. execCommand : function( cmdName,value,dir ) {
  12110. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12111. return true;
  12112. },
  12113. queryCommandValue : function(cmdName,dir) {
  12114. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12115. value;
  12116. //trace:1026
  12117. if(pN){
  12118. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12119. return !value ? 0 : value;
  12120. }
  12121. return 0;
  12122. }
  12123. };
  12124. };
  12125. // plugins/lineheight.js
  12126. /**
  12127. * 设置行内间距
  12128. * @file
  12129. * @since 1.2.6.1
  12130. */
  12131. UE.plugins['lineheight'] = function(){
  12132. var me = this;
  12133. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12134. /**
  12135. * 行距
  12136. * @command lineheight
  12137. * @method execCommand
  12138. * @param { String } cmdName 命令字符串
  12139. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12140. * @example
  12141. * ```javascript
  12142. * editor.execCommand( 'lineheight', 1.5);
  12143. * ```
  12144. */
  12145. /**
  12146. * 查询当前选区内容的行高大小
  12147. * @command lineheight
  12148. * @method queryCommandValue
  12149. * @param { String } cmd 命令字符串
  12150. * @return { String } 返回当前行高大小
  12151. * @example
  12152. * ```javascript
  12153. * editor.queryCommandValue( 'lineheight' );
  12154. * ```
  12155. */
  12156. me.commands['lineheight'] = {
  12157. execCommand : function( cmdName,value ) {
  12158. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12159. return true;
  12160. },
  12161. queryCommandValue : function() {
  12162. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12163. if(pN){
  12164. var value = domUtils.getComputedStyle(pN,'line-height');
  12165. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12166. }
  12167. }
  12168. };
  12169. };
  12170. // plugins/insertcode.js
  12171. /**
  12172. * 插入代码插件
  12173. * @file
  12174. * @since 1.2.6.1
  12175. */
  12176. UE.plugins['insertcode'] = function() {
  12177. var me = this;
  12178. me.ready(function(){
  12179. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12180. me.document)
  12181. });
  12182. me.setOpt('insertcode',{
  12183. 'as3':'ActionScript3',
  12184. 'bash':'Bash/Shell',
  12185. 'cpp':'C/C++',
  12186. 'css':'Css',
  12187. 'cf':'CodeFunction',
  12188. 'c#':'C#',
  12189. 'delphi':'Delphi',
  12190. 'diff':'Diff',
  12191. 'erlang':'Erlang',
  12192. 'groovy':'Groovy',
  12193. 'html':'Html',
  12194. 'java':'Java',
  12195. 'jfx':'JavaFx',
  12196. 'js':'Javascript',
  12197. 'pl':'Perl',
  12198. 'php':'Php',
  12199. 'plain':'Plain Text',
  12200. 'ps':'PowerShell',
  12201. 'python':'Python',
  12202. 'ruby':'Ruby',
  12203. 'scala':'Scala',
  12204. 'sql':'Sql',
  12205. 'vb':'Vb',
  12206. 'xml':'Xml'
  12207. });
  12208. /**
  12209. * 插入代码
  12210. * @command insertcode
  12211. * @method execCommand
  12212. * @param { String } cmd 命令字符串
  12213. * @param { String } lang 插入代码的语言
  12214. * @example
  12215. * ```javascript
  12216. * editor.execCommand( 'insertcode', 'javascript' );
  12217. * ```
  12218. */
  12219. /**
  12220. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12221. * @command insertcode
  12222. * @method queryCommandValue
  12223. * @param { String } cmd 命令字符串
  12224. * @return { String } 返回代码的语言
  12225. * @example
  12226. * ```javascript
  12227. * editor.queryCommandValue( 'insertcode' );
  12228. * ```
  12229. */
  12230. me.commands['insertcode'] = {
  12231. execCommand : function(cmd,lang){
  12232. var me = this,
  12233. rng = me.selection.getRange(),
  12234. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12235. if(pre){
  12236. pre.className = 'brush:'+lang+';toolbar:false;';
  12237. }else{
  12238. var code = '';
  12239. if(rng.collapsed){
  12240. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12241. }else{
  12242. var frag = rng.extractContents();
  12243. var div = me.document.createElement('div');
  12244. div.appendChild(frag);
  12245. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12246. if(browser.ie && browser.ie11below && browser.version > 8){
  12247. if(node.type =='element'){
  12248. if(node.tagName == 'br'){
  12249. code += '\n'
  12250. }else if(!dtd.$empty[node.tagName]){
  12251. utils.each(node.children,function(cn){
  12252. if(cn.type =='element'){
  12253. if(cn.tagName == 'br'){
  12254. code += '\n'
  12255. }else if(!dtd.$empty[node.tagName]){
  12256. code += cn.innerText();
  12257. }
  12258. }else{
  12259. code += cn.data
  12260. }
  12261. })
  12262. if(!/\n$/.test(code)){
  12263. code += '\n';
  12264. }
  12265. }
  12266. }else{
  12267. code += node.data + '\n'
  12268. }
  12269. if(!node.nextSibling() && /\n$/.test(code)){
  12270. code = code.replace(/\n$/,'');
  12271. }
  12272. }else{
  12273. if(browser.ie && browser.ie11below){
  12274. if(node.type =='element'){
  12275. if(node.tagName == 'br'){
  12276. code += '<br>'
  12277. }else if(!dtd.$empty[node.tagName]){
  12278. utils.each(node.children,function(cn){
  12279. if(cn.type =='element'){
  12280. if(cn.tagName == 'br'){
  12281. code += '<br>'
  12282. }else if(!dtd.$empty[node.tagName]){
  12283. code += cn.innerText();
  12284. }
  12285. }else{
  12286. code += cn.data
  12287. }
  12288. });
  12289. if(!/br>$/.test(code)){
  12290. code += '<br>';
  12291. }
  12292. }
  12293. }else{
  12294. code += node.data + '<br>'
  12295. }
  12296. if(!node.nextSibling() && /<br>$/.test(code)){
  12297. code = code.replace(/<br>$/,'');
  12298. }
  12299. }else{
  12300. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12301. if(!/br\/?\s*>$/.test(code)){
  12302. if(!node.nextSibling())
  12303. return;
  12304. code += '<br>'
  12305. }
  12306. }
  12307. }
  12308. });
  12309. }
  12310. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12311. pre = me.document.getElementById('coder');
  12312. domUtils.removeAttributes(pre,'id');
  12313. var tmpNode = pre.previousSibling;
  12314. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12315. domUtils.remove(tmpNode)
  12316. }
  12317. var rng = me.selection.getRange();
  12318. if(domUtils.isEmptyBlock(pre)){
  12319. rng.setStart(pre,0).setCursor(false,true)
  12320. }else{
  12321. rng.selectNodeContents(pre).select()
  12322. }
  12323. }
  12324. },
  12325. queryCommandValue : function(){
  12326. var path = this.selection.getStartElementPath();
  12327. var lang = '';
  12328. utils.each(path,function(node){
  12329. if(node.nodeName =='PRE'){
  12330. var match = node.className.match(/brush:([^;]+)/);
  12331. lang = match && match[1] ? match[1] : '';
  12332. return false;
  12333. }
  12334. });
  12335. return lang;
  12336. }
  12337. };
  12338. me.addInputRule(function(root){
  12339. utils.each(root.getNodesByTagName('pre'),function(pre){
  12340. var brs = pre.getNodesByTagName('br');
  12341. if(brs.length){
  12342. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12343. var txt = UE.uNode.createText('\n');
  12344. br.parentNode.insertBefore(txt,br);
  12345. br.parentNode.removeChild(br);
  12346. });
  12347. return;
  12348. }
  12349. if(browser.ie && browser.ie11below && browser.version > 8)
  12350. return;
  12351. var code = pre.innerText().split(/\n/);
  12352. pre.innerHTML('');
  12353. utils.each(code,function(c){
  12354. if(c.length){
  12355. pre.appendChild(UE.uNode.createText(c));
  12356. }
  12357. pre.appendChild(UE.uNode.createElement('br'))
  12358. })
  12359. })
  12360. });
  12361. me.addOutputRule(function(root){
  12362. utils.each(root.getNodesByTagName('pre'),function(pre){
  12363. var code = '';
  12364. utils.each(pre.children,function(n){
  12365. if(n.type == 'text'){
  12366. //在ie下文本内容有可能末尾带有\n要去掉
  12367. //trace:3396
  12368. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12369. }else{
  12370. if(n.tagName == 'br'){
  12371. code += '\n'
  12372. }else{
  12373. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12374. }
  12375. }
  12376. });
  12377. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12378. })
  12379. });
  12380. //不需要判断highlight的command列表
  12381. me.notNeedCodeQuery ={
  12382. help:1,
  12383. undo:1,
  12384. redo:1,
  12385. source:1,
  12386. print:1,
  12387. searchreplace:1,
  12388. fullscreen:1,
  12389. preview:1,
  12390. insertparagraph:1,
  12391. elementpath:1,
  12392. insertcode:1,
  12393. inserthtml:1,
  12394. selectall:1
  12395. };
  12396. //将queyCommamndState重置
  12397. var orgQuery = me.queryCommandState;
  12398. me.queryCommandState = function(cmd){
  12399. var me = this;
  12400. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12401. return -1;
  12402. }
  12403. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12404. };
  12405. me.addListener('beforeenterkeydown',function(){
  12406. var rng = me.selection.getRange();
  12407. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12408. if(pre){
  12409. me.fireEvent('saveScene');
  12410. if(!rng.collapsed){
  12411. rng.deleteContents();
  12412. }
  12413. if(!browser.ie || browser.ie9above){
  12414. var tmpNode = me.document.createElement('br'),pre;
  12415. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12416. var next = tmpNode.nextSibling;
  12417. if(!next && (!browser.ie || browser.version > 10)){
  12418. rng.insertNode(tmpNode.cloneNode(false));
  12419. }else{
  12420. rng.setStartAfter(tmpNode);
  12421. }
  12422. pre = tmpNode.previousSibling;
  12423. var tmp;
  12424. while(pre ){
  12425. tmp = pre;
  12426. pre = pre.previousSibling;
  12427. if(!pre || pre.nodeName == 'BR'){
  12428. pre = tmp;
  12429. break;
  12430. }
  12431. }
  12432. if(pre){
  12433. var str = '';
  12434. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12435. str += pre.nodeValue;
  12436. pre = pre.nextSibling;
  12437. }
  12438. if(pre.nodeName != 'BR'){
  12439. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12440. if(match && match[1]){
  12441. str += match[1]
  12442. }
  12443. }
  12444. if(str){
  12445. str = me.document.createTextNode(str);
  12446. rng.insertNode(str).setStartAfter(str);
  12447. }
  12448. }
  12449. rng.collapse(true).select(true);
  12450. }else{
  12451. if(browser.version > 8){
  12452. var txt = me.document.createTextNode('\n');
  12453. var start = rng.startContainer;
  12454. if(rng.startOffset == 0){
  12455. var preNode = start.previousSibling;
  12456. if(preNode){
  12457. rng.insertNode(txt);
  12458. var fillchar = me.document.createTextNode(' ');
  12459. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12460. }
  12461. }else{
  12462. rng.insertNode(txt).setStartAfter(txt);
  12463. var fillchar = me.document.createTextNode(' ');
  12464. start = rng.startContainer.childNodes[rng.startOffset];
  12465. if(start && !/^\n/.test(start.nodeValue)){
  12466. rng.setStartBefore(txt)
  12467. }
  12468. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12469. }
  12470. }else{
  12471. var tmpNode = me.document.createElement('br');
  12472. rng.insertNode(tmpNode);
  12473. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12474. rng.setStartAfter(tmpNode);
  12475. pre = tmpNode.previousSibling;
  12476. var tmp;
  12477. while(pre ){
  12478. tmp = pre;
  12479. pre = pre.previousSibling;
  12480. if(!pre || pre.nodeName == 'BR'){
  12481. pre = tmp;
  12482. break;
  12483. }
  12484. }
  12485. if(pre){
  12486. var str = '';
  12487. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12488. str += pre.nodeValue;
  12489. pre = pre.nextSibling;
  12490. }
  12491. if(pre.nodeName != 'BR'){
  12492. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12493. if(match && match[1]){
  12494. str += match[1]
  12495. }
  12496. }
  12497. str = me.document.createTextNode(str);
  12498. rng.insertNode(str).setStartAfter(str);
  12499. }
  12500. rng.collapse(true).select();
  12501. }
  12502. }
  12503. me.fireEvent('saveScene');
  12504. return true;
  12505. }
  12506. });
  12507. me.addListener('tabkeydown',function(cmd,evt){
  12508. var rng = me.selection.getRange();
  12509. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12510. if(pre){
  12511. me.fireEvent('saveScene');
  12512. if(evt.shiftKey){
  12513. }else{
  12514. if(!rng.collapsed){
  12515. var bk = rng.createBookmark();
  12516. var start = bk.start.previousSibling;
  12517. while(start){
  12518. if(pre.firstChild === start && !domUtils.isBr(start)){
  12519. pre.insertBefore(me.document.createTextNode(' '),start);
  12520. break;
  12521. }
  12522. if(domUtils.isBr(start)){
  12523. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12524. break;
  12525. }
  12526. start = start.previousSibling;
  12527. }
  12528. var end = bk.end;
  12529. start = bk.start.nextSibling;
  12530. if(pre.firstChild === bk.start){
  12531. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12532. }
  12533. while(start && start !== end){
  12534. if(domUtils.isBr(start) && start.nextSibling){
  12535. if(start.nextSibling === end){
  12536. break;
  12537. }
  12538. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12539. }
  12540. start = start.nextSibling;
  12541. }
  12542. rng.moveToBookmark(bk).select();
  12543. }else{
  12544. var tmpNode = me.document.createTextNode(' ');
  12545. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12546. }
  12547. }
  12548. me.fireEvent('saveScene');
  12549. return true;
  12550. }
  12551. });
  12552. me.addListener('beforeinserthtml',function(evtName,html){
  12553. var me = this,
  12554. rng = me.selection.getRange(),
  12555. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12556. if(pre){
  12557. if(!rng.collapsed){
  12558. rng.deleteContents()
  12559. }
  12560. var htmlstr = '';
  12561. if(browser.ie && browser.version > 8){
  12562. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12563. if(node.type =='element'){
  12564. if(node.tagName == 'br'){
  12565. htmlstr += '\n'
  12566. }else if(!dtd.$empty[node.tagName]){
  12567. utils.each(node.children,function(cn){
  12568. if(cn.type =='element'){
  12569. if(cn.tagName == 'br'){
  12570. htmlstr += '\n'
  12571. }else if(!dtd.$empty[node.tagName]){
  12572. htmlstr += cn.innerText();
  12573. }
  12574. }else{
  12575. htmlstr += cn.data
  12576. }
  12577. })
  12578. if(!/\n$/.test(htmlstr)){
  12579. htmlstr += '\n';
  12580. }
  12581. }
  12582. }else{
  12583. htmlstr += node.data + '\n'
  12584. }
  12585. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12586. htmlstr = htmlstr.replace(/\n$/,'');
  12587. }
  12588. });
  12589. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12590. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12591. }else{
  12592. var frag = me.document.createDocumentFragment();
  12593. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12594. if(node.type =='element'){
  12595. if(node.tagName == 'br'){
  12596. frag.appendChild(me.document.createElement('br'))
  12597. }else if(!dtd.$empty[node.tagName]){
  12598. utils.each(node.children,function(cn){
  12599. if(cn.type =='element'){
  12600. if(cn.tagName == 'br'){
  12601. frag.appendChild(me.document.createElement('br'))
  12602. }else if(!dtd.$empty[node.tagName]){
  12603. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12604. }
  12605. }else{
  12606. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12607. }
  12608. })
  12609. if(frag.lastChild.nodeName != 'BR'){
  12610. frag.appendChild(me.document.createElement('br'))
  12611. }
  12612. }
  12613. }else{
  12614. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12615. }
  12616. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12617. frag.removeChild(frag.lastChild)
  12618. }
  12619. });
  12620. rng.insertNode(frag).select();
  12621. }
  12622. return true;
  12623. }
  12624. });
  12625. //方向键的处理
  12626. me.addListener('keydown',function(cmd,evt){
  12627. var me = this,keyCode = evt.keyCode || evt.which;
  12628. if(keyCode == 40){
  12629. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12630. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12631. var last = pre.lastChild
  12632. while(last && last.nodeName == 'BR'){
  12633. last = last.previousSibling;
  12634. }
  12635. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12636. me.execCommand('insertparagraph');
  12637. domUtils.preventDefault(evt)
  12638. }
  12639. }
  12640. }
  12641. });
  12642. //trace:3395
  12643. me.addListener('delkeydown',function(type,evt){
  12644. var rng = this.selection.getRange();
  12645. rng.txtToElmBoundary(true);
  12646. var start = rng.startContainer;
  12647. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12648. var p = me.document.createElement('p');
  12649. domUtils.fillNode(me.document,p);
  12650. start.parentNode.insertBefore(p,start);
  12651. domUtils.remove(start);
  12652. rng.setStart(p,0).setCursor(false,true);
  12653. domUtils.preventDefault(evt);
  12654. return true;
  12655. }
  12656. })
  12657. };
  12658. // plugins/cleardoc.js
  12659. /**
  12660. * 清空文档插件
  12661. * @file
  12662. * @since 1.2.6.1
  12663. */
  12664. /**
  12665. * 清空文档
  12666. * @command cleardoc
  12667. * @method execCommand
  12668. * @param { String } cmd 命令字符串
  12669. * @example
  12670. * ```javascript
  12671. * //editor 是编辑器实例
  12672. * editor.execCommand('cleardoc');
  12673. * ```
  12674. */
  12675. UE.commands['cleardoc'] = {
  12676. execCommand : function( cmdName) {
  12677. var me = this,
  12678. enterTag = me.options.enterTag,
  12679. range = me.selection.getRange();
  12680. if(enterTag == "br"){
  12681. me.body.innerHTML = "<br/>";
  12682. range.setStart(me.body,0).setCursor();
  12683. }else{
  12684. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12685. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12686. }
  12687. setTimeout(function(){
  12688. me.fireEvent("clearDoc");
  12689. },0);
  12690. }
  12691. };
  12692. // plugins/anchor.js
  12693. /**
  12694. * 锚点插件,为UEditor提供插入锚点支持
  12695. * @file
  12696. * @since 1.2.6.1
  12697. */
  12698. UE.plugin.register('anchor', function (){
  12699. return {
  12700. bindEvents:{
  12701. 'ready':function(){
  12702. utils.cssRule('anchor',
  12703. '.anchorclass{background: url(\''
  12704. + this.options.themePath
  12705. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12706. this.document);
  12707. }
  12708. },
  12709. outputRule: function(root){
  12710. utils.each(root.getNodesByTagName('img'),function(a){
  12711. var val;
  12712. if(val = a.getAttr('anchorname')){
  12713. a.tagName = 'a';
  12714. a.setAttr({
  12715. anchorname : '',
  12716. name : val,
  12717. 'class' : ''
  12718. })
  12719. }
  12720. })
  12721. },
  12722. inputRule:function(root){
  12723. utils.each(root.getNodesByTagName('a'),function(a){
  12724. var val;
  12725. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12726. a.tagName = 'img';
  12727. a.setAttr({
  12728. anchorname :a.getAttr('name'),
  12729. 'class' : 'anchorclass'
  12730. });
  12731. a.setAttr('name')
  12732. }
  12733. })
  12734. },
  12735. commands:{
  12736. /**
  12737. * 插入锚点
  12738. * @command anchor
  12739. * @method execCommand
  12740. * @param { String } cmd 命令字符串
  12741. * @param { String } name 锚点名称字符串
  12742. * @example
  12743. * ```javascript
  12744. * //editor 是编辑器实例
  12745. * editor.execCommand('anchor', 'anchor1');
  12746. * ```
  12747. */
  12748. 'anchor':{
  12749. execCommand:function (cmd, name) {
  12750. var range = this.selection.getRange(),img = range.getClosedNode();
  12751. if (img && img.getAttribute('anchorname')) {
  12752. if (name) {
  12753. img.setAttribute('anchorname', name);
  12754. } else {
  12755. range.setStartBefore(img).setCursor();
  12756. domUtils.remove(img);
  12757. }
  12758. } else {
  12759. if (name) {
  12760. //只在选区的开始插入
  12761. var anchor = this.document.createElement('img');
  12762. range.collapse(true);
  12763. domUtils.setAttributes(anchor,{
  12764. 'anchorname':name,
  12765. 'class':'anchorclass'
  12766. });
  12767. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12768. }
  12769. }
  12770. }
  12771. }
  12772. }
  12773. }
  12774. });
  12775. // plugins/wordcount.js
  12776. ///import core
  12777. ///commands 字数统计
  12778. ///commandsName WordCount,wordCount
  12779. ///commandsTitle 字数统计
  12780. /*
  12781. * Created by JetBrains WebStorm.
  12782. * User: taoqili
  12783. * Date: 11-9-7
  12784. * Time: 下午8:18
  12785. * To change this template use File | Settings | File Templates.
  12786. */
  12787. UE.plugins['wordcount'] = function(){
  12788. var me = this;
  12789. me.setOpt('wordCount',true);
  12790. me.addListener('contentchange',function(){
  12791. me.fireEvent('wordcount');
  12792. });
  12793. var timer;
  12794. me.addListener('ready',function(){
  12795. var me = this;
  12796. domUtils.on(me.body,"keyup",function(evt){
  12797. var code = evt.keyCode||evt.which,
  12798. //忽略的按键,ctr,alt,shift,方向键
  12799. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12800. if(code in ignores) return;
  12801. clearTimeout(timer);
  12802. timer = setTimeout(function(){
  12803. me.fireEvent('wordcount');
  12804. },200)
  12805. })
  12806. });
  12807. };
  12808. // plugins/pagebreak.js
  12809. /**
  12810. * 分页功能插件
  12811. * @file
  12812. * @since 1.2.6.1
  12813. */
  12814. UE.plugins['pagebreak'] = function () {
  12815. var me = this,
  12816. notBreakTags = ['td'];
  12817. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12818. function fillNode(node){
  12819. if(domUtils.isEmptyBlock(node)){
  12820. var firstChild = node.firstChild,tmpNode;
  12821. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12822. tmpNode = firstChild;
  12823. firstChild = firstChild.firstChild;
  12824. }
  12825. !tmpNode && (tmpNode = node);
  12826. domUtils.fillNode(me.document,tmpNode);
  12827. }
  12828. }
  12829. //分页符样式添加
  12830. me.ready(function(){
  12831. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12832. });
  12833. function isHr(node){
  12834. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12835. }
  12836. me.addInputRule(function(root){
  12837. root.traversal(function(node){
  12838. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12839. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12840. node.parentNode.insertBefore(hr,node);
  12841. node.parentNode.removeChild(node)
  12842. }
  12843. })
  12844. });
  12845. me.addOutputRule(function(node){
  12846. utils.each(node.getNodesByTagName('hr'),function(n){
  12847. if(n.getAttr('class') == 'pagebreak'){
  12848. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12849. n.parentNode.insertBefore(txt,n);
  12850. n.parentNode.removeChild(n);
  12851. }
  12852. })
  12853. });
  12854. /**
  12855. * 插入分页符
  12856. * @command pagebreak
  12857. * @method execCommand
  12858. * @param { String } cmd 命令字符串
  12859. * @remind 在表格中插入分页符会把表格切分成两部分
  12860. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12861. * 以便于提交数据到服务器端后处理分页。
  12862. * @example
  12863. * ```javascript
  12864. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12865. * ```
  12866. */
  12867. me.commands['pagebreak'] = {
  12868. execCommand:function () {
  12869. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12870. domUtils.setAttributes(hr,{
  12871. 'class' : 'pagebreak',
  12872. noshade:"noshade",
  12873. size:"5"
  12874. });
  12875. domUtils.unSelectable(hr);
  12876. //table单独处理
  12877. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12878. parents = [], pN;
  12879. if (node) {
  12880. switch (node.tagName) {
  12881. case 'TD':
  12882. pN = node.parentNode;
  12883. if (!pN.previousSibling) {
  12884. var table = domUtils.findParentByTagName(pN, 'table');
  12885. // var tableWrapDiv = table.parentNode;
  12886. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12887. // && tableWrapDiv.tagName == 'DIV'
  12888. // && tableWrapDiv.getAttribute('dropdrag')
  12889. // ){
  12890. // domUtils.remove(tableWrapDiv,true);
  12891. // }
  12892. table.parentNode.insertBefore(hr, table);
  12893. parents = domUtils.findParents(hr, true);
  12894. } else {
  12895. pN.parentNode.insertBefore(hr, pN);
  12896. parents = domUtils.findParents(hr);
  12897. }
  12898. pN = parents[1];
  12899. if (hr !== pN) {
  12900. domUtils.breakParent(hr, pN);
  12901. }
  12902. //table要重写绑定一下拖拽
  12903. me.fireEvent('afteradjusttable',me.document);
  12904. }
  12905. } else {
  12906. if (!range.collapsed) {
  12907. range.deleteContents();
  12908. var start = range.startContainer;
  12909. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12910. range.setStartBefore(start).collapse(true);
  12911. domUtils.remove(start);
  12912. start = range.startContainer;
  12913. }
  12914. }
  12915. range.insertNode(hr);
  12916. var pN = hr.parentNode, nextNode;
  12917. while (!domUtils.isBody(pN)) {
  12918. domUtils.breakParent(hr, pN);
  12919. nextNode = hr.nextSibling;
  12920. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12921. domUtils.remove(nextNode);
  12922. }
  12923. pN = hr.parentNode;
  12924. }
  12925. nextNode = hr.nextSibling;
  12926. var pre = hr.previousSibling;
  12927. if(isHr(pre)){
  12928. domUtils.remove(pre);
  12929. }else{
  12930. pre && fillNode(pre);
  12931. }
  12932. if(!nextNode){
  12933. var p = me.document.createElement('p');
  12934. hr.parentNode.appendChild(p);
  12935. domUtils.fillNode(me.document,p);
  12936. range.setStart(p,0).collapse(true);
  12937. }else{
  12938. if(isHr(nextNode)){
  12939. domUtils.remove(nextNode);
  12940. }else{
  12941. fillNode(nextNode);
  12942. }
  12943. range.setEndAfter(hr).collapse(false);
  12944. }
  12945. range.select(true);
  12946. }
  12947. }
  12948. };
  12949. };
  12950. // plugins/wordimage.js
  12951. ///import core
  12952. ///commands 本地图片引导上传
  12953. ///commandsName WordImage
  12954. ///commandsTitle 本地图片引导上传
  12955. ///commandsDialog dialogs\wordimage
  12956. UE.plugin.register('wordimage',function(){
  12957. var me = this,
  12958. images = [];
  12959. return {
  12960. commands : {
  12961. 'wordimage':{
  12962. execCommand:function () {
  12963. var images = domUtils.getElementsByTagName(me.body, "img");
  12964. var urlList = [];
  12965. for (var i = 0, ci; ci = images[i++];) {
  12966. var url = ci.getAttribute("word_img");
  12967. url && urlList.push(url);
  12968. }
  12969. return urlList;
  12970. },
  12971. queryCommandState:function () {
  12972. images = domUtils.getElementsByTagName(me.body, "img");
  12973. for (var i = 0, ci; ci = images[i++];) {
  12974. if (ci.getAttribute("word_img")) {
  12975. return 1;
  12976. }
  12977. }
  12978. return -1;
  12979. },
  12980. notNeedUndo:true
  12981. }
  12982. },
  12983. inputRule : function (root) {
  12984. utils.each(root.getNodesByTagName('img'), function (img) {
  12985. var attrs = img.attrs,
  12986. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  12987. opt = me.options,
  12988. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  12989. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  12990. img.setAttr({
  12991. width:attrs.width,
  12992. height:attrs.height,
  12993. alt:attrs.alt,
  12994. word_img: attrs.src,
  12995. src:src,
  12996. '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'
  12997. })
  12998. }
  12999. })
  13000. }
  13001. }
  13002. });
  13003. // plugins/dragdrop.js
  13004. UE.plugins['dragdrop'] = function (){
  13005. var me = this;
  13006. me.ready(function(){
  13007. domUtils.on(this.body,'dragend',function(){
  13008. var rng = me.selection.getRange();
  13009. var node = rng.getClosedNode()||me.selection.getStart();
  13010. if(node && node.tagName == 'IMG'){
  13011. var pre = node.previousSibling,next;
  13012. while(next = node.nextSibling){
  13013. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  13014. domUtils.remove(next)
  13015. }else{
  13016. break;
  13017. }
  13018. }
  13019. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13020. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13021. pre.appendChild(node);
  13022. domUtils.moveChild(next,pre);
  13023. domUtils.remove(next);
  13024. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13025. next.insertBefore(node,next.firstChild);
  13026. }
  13027. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13028. domUtils.remove(pre)
  13029. }
  13030. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13031. domUtils.remove(next)
  13032. }
  13033. rng.selectNode(node).select();
  13034. me.fireEvent('saveScene');
  13035. }
  13036. }
  13037. })
  13038. });
  13039. me.addListener('keyup', function(type, evt) {
  13040. var keyCode = evt.keyCode || evt.which;
  13041. if (keyCode == 13) {
  13042. var rng = me.selection.getRange(),node;
  13043. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13044. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13045. domUtils.removeStyle(node,'text-align')
  13046. }
  13047. }
  13048. }
  13049. })
  13050. };
  13051. // plugins/undo.js
  13052. /**
  13053. * undo redo
  13054. * @file
  13055. * @since 1.2.6.1
  13056. */
  13057. /**
  13058. * 撤销上一次执行的命令
  13059. * @command undo
  13060. * @method execCommand
  13061. * @param { String } cmd 命令字符串
  13062. * @example
  13063. * ```javascript
  13064. * editor.execCommand( 'undo' );
  13065. * ```
  13066. */
  13067. /**
  13068. * 重做上一次执行的命令
  13069. * @command redo
  13070. * @method execCommand
  13071. * @param { String } cmd 命令字符串
  13072. * @example
  13073. * ```javascript
  13074. * editor.execCommand( 'redo' );
  13075. * ```
  13076. */
  13077. UE.plugins['undo'] = function () {
  13078. var saveSceneTimer;
  13079. var me = this,
  13080. maxUndoCount = me.options.maxUndoCount || 20,
  13081. maxInputCount = me.options.maxInputCount || 20,
  13082. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13083. var noNeedFillCharTags = {
  13084. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13085. };
  13086. var orgState = me.options.autoClearEmptyNode;
  13087. function compareAddr(indexA, indexB) {
  13088. if (indexA.length != indexB.length)
  13089. return 0;
  13090. for (var i = 0, l = indexA.length; i < l; i++) {
  13091. if (indexA[i] != indexB[i])
  13092. return 0
  13093. }
  13094. return 1;
  13095. }
  13096. function compareRangeAddress(rngAddrA, rngAddrB) {
  13097. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13098. return 0;
  13099. }
  13100. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13101. return 0;
  13102. }
  13103. return 1;
  13104. }
  13105. function UndoManager() {
  13106. this.list = [];
  13107. this.index = 0;
  13108. this.hasUndo = false;
  13109. this.hasRedo = false;
  13110. this.undo = function () {
  13111. if (this.hasUndo) {
  13112. if (!this.list[this.index - 1] && this.list.length == 1) {
  13113. this.reset();
  13114. return;
  13115. }
  13116. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13117. this.index--;
  13118. if (this.index == 0) {
  13119. return this.restore(0);
  13120. }
  13121. }
  13122. this.restore(--this.index);
  13123. }
  13124. };
  13125. this.redo = function () {
  13126. if (this.hasRedo) {
  13127. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13128. this.index++;
  13129. if (this.index == this.list.length - 1) {
  13130. return this.restore(this.index);
  13131. }
  13132. }
  13133. this.restore(++this.index);
  13134. }
  13135. };
  13136. this.restore = function () {
  13137. var me = this.editor;
  13138. var scene = this.list[this.index];
  13139. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13140. me.options.autoClearEmptyNode = false;
  13141. me.filterInputRule(root);
  13142. me.options.autoClearEmptyNode = orgState;
  13143. //trace:873
  13144. //去掉展位符
  13145. me.document.body.innerHTML = root.toHtml();
  13146. me.fireEvent('afterscencerestore');
  13147. //处理undo后空格不展位的问题
  13148. if (browser.ie) {
  13149. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13150. if(domUtils.isEmptyNode(node)){
  13151. domUtils.fillNode(me.document, node);
  13152. }
  13153. })
  13154. }
  13155. try{
  13156. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13157. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13158. }catch(e){}
  13159. this.update();
  13160. this.clearKey();
  13161. //不能把自己reset了
  13162. me.fireEvent('reset', true);
  13163. };
  13164. this.getScene = function () {
  13165. var me = this.editor;
  13166. var rng = me.selection.getRange(),
  13167. rngAddress = rng.createAddress(false,true);
  13168. me.fireEvent('beforegetscene');
  13169. var root = UE.htmlparser(me.body.innerHTML);
  13170. me.options.autoClearEmptyNode = false;
  13171. me.filterOutputRule(root);
  13172. me.options.autoClearEmptyNode = orgState;
  13173. var cont = root.toHtml();
  13174. //trace:3461
  13175. //这个会引起回退时导致空格丢失的情况
  13176. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13177. me.fireEvent('aftergetscene');
  13178. return {
  13179. address:rngAddress,
  13180. content:cont
  13181. }
  13182. };
  13183. this.save = function (notCompareRange,notSetCursor) {
  13184. clearTimeout(saveSceneTimer);
  13185. var currentScene = this.getScene(notSetCursor),
  13186. lastScene = this.list[this.index];
  13187. if(lastScene && lastScene.content != currentScene.content){
  13188. me.trigger('contentchange')
  13189. }
  13190. //内容相同位置相同不存
  13191. if (lastScene && lastScene.content == currentScene.content &&
  13192. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13193. ) {
  13194. return;
  13195. }
  13196. this.list = this.list.slice(0, this.index + 1);
  13197. this.list.push(currentScene);
  13198. //如果大于最大数量了,就把最前的剔除
  13199. if (this.list.length > maxUndoCount) {
  13200. this.list.shift();
  13201. }
  13202. this.index = this.list.length - 1;
  13203. this.clearKey();
  13204. //跟新undo/redo状态
  13205. this.update();
  13206. };
  13207. this.update = function () {
  13208. this.hasRedo = !!this.list[this.index + 1];
  13209. this.hasUndo = !!this.list[this.index - 1];
  13210. };
  13211. this.reset = function () {
  13212. this.list = [];
  13213. this.index = 0;
  13214. this.hasUndo = false;
  13215. this.hasRedo = false;
  13216. this.clearKey();
  13217. };
  13218. this.clearKey = function () {
  13219. keycont = 0;
  13220. lastKeyCode = null;
  13221. };
  13222. }
  13223. me.undoManger = new UndoManager();
  13224. me.undoManger.editor = me;
  13225. function saveScene() {
  13226. this.undoManger.save();
  13227. }
  13228. me.addListener('saveScene', function () {
  13229. var args = Array.prototype.splice.call(arguments,1);
  13230. this.undoManger.save.apply(this.undoManger,args);
  13231. });
  13232. // me.addListener('beforeexeccommand', saveScene);
  13233. // me.addListener('afterexeccommand', saveScene);
  13234. me.addListener('reset', function (type, exclude) {
  13235. if (!exclude) {
  13236. this.undoManger.reset();
  13237. }
  13238. });
  13239. me.commands['redo'] = me.commands['undo'] = {
  13240. execCommand:function (cmdName) {
  13241. this.undoManger[cmdName]();
  13242. },
  13243. queryCommandState:function (cmdName) {
  13244. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13245. },
  13246. notNeedUndo:1
  13247. };
  13248. var keys = {
  13249. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13250. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13251. 37:1, 38:1, 39:1, 40:1
  13252. },
  13253. keycont = 0,
  13254. lastKeyCode;
  13255. //输入法状态下不计算字符数
  13256. var inputType = false;
  13257. me.addListener('ready', function () {
  13258. domUtils.on(this.body, 'compositionstart', function () {
  13259. inputType = true;
  13260. });
  13261. domUtils.on(this.body, 'compositionend', function () {
  13262. inputType = false;
  13263. })
  13264. });
  13265. //快捷键
  13266. me.addshortcutkey({
  13267. "Undo":"ctrl+90", //undo
  13268. "Redo":"ctrl+89" //redo
  13269. });
  13270. var isCollapsed = true;
  13271. me.addListener('keydown', function (type, evt) {
  13272. var me = this;
  13273. var keyCode = evt.keyCode || evt.which;
  13274. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13275. if (inputType)
  13276. return;
  13277. if(!me.selection.getRange().collapsed){
  13278. me.undoManger.save(false,true);
  13279. isCollapsed = false;
  13280. return;
  13281. }
  13282. if (me.undoManger.list.length == 0) {
  13283. me.undoManger.save(true);
  13284. }
  13285. clearTimeout(saveSceneTimer);
  13286. function save(cont){
  13287. cont.undoManger.save(false,true);
  13288. cont.fireEvent('selectionchange');
  13289. }
  13290. saveSceneTimer = setTimeout(function(){
  13291. if(inputType){
  13292. var interalTimer = setInterval(function(){
  13293. if(!inputType){
  13294. save(me);
  13295. clearInterval(interalTimer)
  13296. }
  13297. },300)
  13298. return;
  13299. }
  13300. save(me);
  13301. },200);
  13302. lastKeyCode = keyCode;
  13303. keycont++;
  13304. if (keycont >= maxInputCount ) {
  13305. save(me)
  13306. }
  13307. }
  13308. });
  13309. me.addListener('keyup', function (type, evt) {
  13310. var keyCode = evt.keyCode || evt.which;
  13311. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13312. if (inputType)
  13313. return;
  13314. if(!isCollapsed){
  13315. this.undoManger.save(false,true);
  13316. isCollapsed = true;
  13317. }
  13318. }
  13319. });
  13320. //扩展实例,添加关闭和开启命令undo
  13321. me.stopCmdUndo = function(){
  13322. me.__hasEnterExecCommand = true;
  13323. };
  13324. me.startCmdUndo = function(){
  13325. me.__hasEnterExecCommand = false;
  13326. }
  13327. };
  13328. // plugins/copy.js
  13329. UE.plugin.register('copy', function () {
  13330. var me = this;
  13331. function initZeroClipboard() {
  13332. ZeroClipboard.config({
  13333. debug: false,
  13334. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13335. });
  13336. var client = me.zeroclipboard = new ZeroClipboard();
  13337. // 复制内容
  13338. client.on('copy', function (e) {
  13339. var client = e.client,
  13340. rng = me.selection.getRange(),
  13341. div = document.createElement('div');
  13342. div.appendChild(rng.cloneContents());
  13343. client.setText(div.innerText || div.textContent);
  13344. client.setHtml(div.innerHTML);
  13345. rng.select();
  13346. });
  13347. // hover事件传递到target
  13348. client.on('mouseover mouseout', function (e) {
  13349. var target = e.target;
  13350. if (e.type == 'mouseover') {
  13351. domUtils.addClass(target, 'edui-state-hover');
  13352. } else if (e.type == 'mouseout') {
  13353. domUtils.removeClasses(target, 'edui-state-hover');
  13354. }
  13355. });
  13356. // flash加载不成功
  13357. client.on('wrongflash noflash', function () {
  13358. ZeroClipboard.destroy();
  13359. });
  13360. }
  13361. return {
  13362. bindEvents: {
  13363. 'ready': function () {
  13364. if (!browser.ie) {
  13365. if (window.ZeroClipboard) {
  13366. initZeroClipboard();
  13367. } else {
  13368. utils.loadFile(document, {
  13369. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13370. tag: "script",
  13371. type: "text/javascript",
  13372. defer: "defer"
  13373. }, function () {
  13374. initZeroClipboard();
  13375. });
  13376. }
  13377. }
  13378. }
  13379. },
  13380. commands: {
  13381. 'copy': {
  13382. execCommand: function (cmd) {
  13383. if (!me.document.execCommand('copy')) {
  13384. alert(me.getLang('copymsg'));
  13385. }
  13386. }
  13387. }
  13388. }
  13389. }
  13390. });
  13391. // plugins/paste.js
  13392. ///import core
  13393. ///import plugins/inserthtml.js
  13394. ///import plugins/undo.js
  13395. ///import plugins/serialize.js
  13396. ///commands 粘贴
  13397. ///commandsName PastePlain
  13398. ///commandsTitle 纯文本粘贴模式
  13399. /**
  13400. * @description 粘贴
  13401. * @author zhanyi
  13402. */
  13403. UE.plugins['paste'] = function () {
  13404. function getClipboardData(callback) {
  13405. var doc = this.document;
  13406. if (doc.getElementById('baidu_pastebin')) {
  13407. return;
  13408. }
  13409. var range = this.selection.getRange(),
  13410. bk = range.createBookmark(),
  13411. //创建剪贴的容器div
  13412. pastebin = doc.createElement('div');
  13413. pastebin.id = 'baidu_pastebin';
  13414. // Safari 要求div必须有内容,才能粘贴内容进来
  13415. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13416. doc.body.appendChild(pastebin);
  13417. //trace:717 隐藏的span不能得到top
  13418. //bk.start.innerHTML = '&nbsp;';
  13419. bk.start.style.display = '';
  13420. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13421. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13422. domUtils.getXY(bk.start).y + 'px';
  13423. range.selectNodeContents(pastebin).select(true);
  13424. setTimeout(function () {
  13425. if (browser.webkit) {
  13426. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13427. if (domUtils.isEmptyNode(pi)) {
  13428. domUtils.remove(pi);
  13429. } else {
  13430. pastebin = pi;
  13431. break;
  13432. }
  13433. }
  13434. }
  13435. try {
  13436. pastebin.parentNode.removeChild(pastebin);
  13437. } catch (e) {
  13438. }
  13439. range.moveToBookmark(bk).select(true);
  13440. callback(pastebin);
  13441. }, 0);
  13442. }
  13443. var me = this;
  13444. me.setOpt({
  13445. retainOnlyLabelPasted : false
  13446. });
  13447. var txtContent, htmlContent, address;
  13448. function getPureHtml(html){
  13449. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13450. tagName = tagName.toLowerCase();
  13451. if ({img: 1}[tagName]) {
  13452. return a;
  13453. }
  13454. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13455. if ({
  13456. 'src': 1,
  13457. 'href': 1,
  13458. 'name': 1
  13459. }[atr.toLowerCase()]) {
  13460. return atr + '=' + val + ' '
  13461. }
  13462. return ''
  13463. });
  13464. if ({
  13465. 'span': 1,
  13466. 'div': 1
  13467. }[tagName]) {
  13468. return ''
  13469. } else {
  13470. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13471. }
  13472. });
  13473. }
  13474. function filter(div) {
  13475. var html;
  13476. if (div.firstChild) {
  13477. //去掉cut中添加的边界值
  13478. var nodes = domUtils.getElementsByTagName(div, 'span');
  13479. for (var i = 0, ni; ni = nodes[i++];) {
  13480. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13481. domUtils.remove(ni);
  13482. }
  13483. }
  13484. if (browser.webkit) {
  13485. var brs = div.querySelectorAll('div br');
  13486. for (var i = 0, bi; bi = brs[i++];) {
  13487. var pN = bi.parentNode;
  13488. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13489. pN.innerHTML = '<p><br/></p>';
  13490. domUtils.remove(pN);
  13491. }
  13492. }
  13493. var divs = div.querySelectorAll('#baidu_pastebin');
  13494. for (var i = 0, di; di = divs[i++];) {
  13495. var tmpP = me.document.createElement('p');
  13496. di.parentNode.insertBefore(tmpP, di);
  13497. while (di.firstChild) {
  13498. tmpP.appendChild(di.firstChild);
  13499. }
  13500. domUtils.remove(di);
  13501. }
  13502. var metas = div.querySelectorAll('meta');
  13503. for (var i = 0, ci; ci = metas[i++];) {
  13504. domUtils.remove(ci);
  13505. }
  13506. var brs = div.querySelectorAll('br');
  13507. for (i = 0; ci = brs[i++];) {
  13508. if (/^apple-/i.test(ci.className)) {
  13509. domUtils.remove(ci);
  13510. }
  13511. }
  13512. }
  13513. if (browser.gecko) {
  13514. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13515. for (i = 0; ci = dirtyNodes[i++];) {
  13516. ci.removeAttribute('_moz_dirty');
  13517. }
  13518. }
  13519. if (!browser.ie) {
  13520. var spans = div.querySelectorAll('span.Apple-style-span');
  13521. for (var i = 0, ci; ci = spans[i++];) {
  13522. domUtils.remove(ci, true);
  13523. }
  13524. }
  13525. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13526. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13527. //过滤word粘贴过来的冗余属性
  13528. html = UE.filterWord(html);
  13529. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13530. var root = UE.htmlparser(html);
  13531. //如果给了过滤规则就先进行过滤
  13532. if (me.options.filterRules) {
  13533. UE.filterNode(root, me.options.filterRules);
  13534. }
  13535. //执行默认的处理
  13536. me.filterInputRule(root);
  13537. //针对chrome的处理
  13538. if (browser.webkit) {
  13539. var br = root.lastChild();
  13540. if (br && br.type == 'element' && br.tagName == 'br') {
  13541. root.removeChild(br)
  13542. }
  13543. utils.each(me.body.querySelectorAll('div'), function (node) {
  13544. if (domUtils.isEmptyBlock(node)) {
  13545. domUtils.remove(node,true)
  13546. }
  13547. })
  13548. }
  13549. html = {'html': root.toHtml()};
  13550. me.fireEvent('beforepaste', html, root);
  13551. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13552. if(!html.html){
  13553. return;
  13554. }
  13555. root = UE.htmlparser(html.html,true);
  13556. //如果开启了纯文本模式
  13557. if (me.queryCommandState('pasteplain') === 1) {
  13558. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13559. } else {
  13560. //文本模式
  13561. UE.filterNode(root, me.options.filterTxtRules);
  13562. txtContent = root.toHtml();
  13563. //完全模式
  13564. htmlContent = html.html;
  13565. address = me.selection.getRange().createAddress(true);
  13566. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13567. }
  13568. me.fireEvent("afterpaste", html);
  13569. }
  13570. }
  13571. me.addListener('pasteTransfer', function (cmd, plainType) {
  13572. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13573. var range = me.selection.getRange();
  13574. range.moveToAddress(address, true);
  13575. if (!range.collapsed) {
  13576. while (!domUtils.isBody(range.startContainer)
  13577. ) {
  13578. var start = range.startContainer;
  13579. if(start.nodeType == 1){
  13580. start = start.childNodes[range.startOffset];
  13581. if(!start){
  13582. range.setStartBefore(range.startContainer);
  13583. continue;
  13584. }
  13585. var pre = start.previousSibling;
  13586. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13587. range.setStartBefore(pre)
  13588. }
  13589. }
  13590. if(range.startOffset == 0){
  13591. range.setStartBefore(range.startContainer);
  13592. }else{
  13593. break;
  13594. }
  13595. }
  13596. while (!domUtils.isBody(range.endContainer)
  13597. ) {
  13598. var end = range.endContainer;
  13599. if(end.nodeType == 1){
  13600. end = end.childNodes[range.endOffset];
  13601. if(!end){
  13602. range.setEndAfter(range.endContainer);
  13603. continue;
  13604. }
  13605. var next = end.nextSibling;
  13606. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13607. range.setEndAfter(next)
  13608. }
  13609. }
  13610. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13611. range.setEndAfter(range.endContainer);
  13612. }else{
  13613. break;
  13614. }
  13615. }
  13616. }
  13617. range.deleteContents();
  13618. range.select(true);
  13619. me.__hasEnterExecCommand = true;
  13620. var html = htmlContent;
  13621. if (plainType === 2 ) {
  13622. html = getPureHtml(html);
  13623. } else if (plainType) {
  13624. html = txtContent;
  13625. }
  13626. me.execCommand('inserthtml', html, true);
  13627. me.__hasEnterExecCommand = false;
  13628. var rng = me.selection.getRange();
  13629. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13630. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13631. ) {
  13632. rng.setStartBefore(rng.startContainer);
  13633. }
  13634. var tmpAddress = rng.createAddress(true);
  13635. address.endAddress = tmpAddress.startAddress;
  13636. }
  13637. });
  13638. me.addListener('ready', function () {
  13639. domUtils.on(me.body, 'cut', function () {
  13640. var range = me.selection.getRange();
  13641. if (!range.collapsed && me.undoManger) {
  13642. me.undoManger.save();
  13643. }
  13644. });
  13645. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13646. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13647. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13648. return;
  13649. }
  13650. getClipboardData.call(me, function (div) {
  13651. filter(div);
  13652. });
  13653. });
  13654. });
  13655. me.commands['paste'] = {
  13656. execCommand: function (cmd) {
  13657. if (browser.ie) {
  13658. getClipboardData.call(me, function (div) {
  13659. filter(div);
  13660. });
  13661. me.document.execCommand('paste');
  13662. } else {
  13663. alert(me.getLang('pastemsg'));
  13664. }
  13665. }
  13666. }
  13667. };
  13668. // plugins/puretxtpaste.js
  13669. /**
  13670. * 纯文本粘贴插件
  13671. * @file
  13672. * @since 1.2.6.1
  13673. */
  13674. UE.plugins['pasteplain'] = function(){
  13675. var me = this;
  13676. me.setOpt({
  13677. 'pasteplain':false,
  13678. 'filterTxtRules' : function(){
  13679. function transP(node){
  13680. node.tagName = 'p';
  13681. node.setStyle();
  13682. }
  13683. function removeNode(node){
  13684. node.parentNode.removeChild(node,true)
  13685. }
  13686. return {
  13687. //直接删除及其字节点内容
  13688. '-' : 'script style object iframe embed input select',
  13689. 'p': {$:{}},
  13690. 'br':{$:{}},
  13691. div: function (node) {
  13692. var tmpNode, p = UE.uNode.createElement('p');
  13693. while (tmpNode = node.firstChild()) {
  13694. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13695. p.appendChild(tmpNode);
  13696. } else {
  13697. if (p.firstChild()) {
  13698. node.parentNode.insertBefore(p, node);
  13699. p = UE.uNode.createElement('p');
  13700. } else {
  13701. node.parentNode.insertBefore(tmpNode, node);
  13702. }
  13703. }
  13704. }
  13705. if (p.firstChild()) {
  13706. node.parentNode.insertBefore(p, node);
  13707. }
  13708. node.parentNode.removeChild(node);
  13709. },
  13710. ol: removeNode,
  13711. ul: removeNode,
  13712. dl:removeNode,
  13713. dt:removeNode,
  13714. dd:removeNode,
  13715. 'li':removeNode,
  13716. 'caption':transP,
  13717. 'th':transP,
  13718. 'tr':transP,
  13719. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13720. 'td':function(node){
  13721. //没有内容的td直接删掉
  13722. var txt = !!node.innerText();
  13723. if(txt){
  13724. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13725. }
  13726. node.parentNode.removeChild(node,node.innerText())
  13727. }
  13728. }
  13729. }()
  13730. });
  13731. //暂时这里支持一下老版本的属性
  13732. var pasteplain = me.options.pasteplain;
  13733. /**
  13734. * 启用或取消纯文本粘贴模式
  13735. * @command pasteplain
  13736. * @method execCommand
  13737. * @param { String } cmd 命令字符串
  13738. * @example
  13739. * ```javascript
  13740. * editor.queryCommandState( 'pasteplain' );
  13741. * ```
  13742. */
  13743. /**
  13744. * 查询当前是否处于纯文本粘贴模式
  13745. * @command pasteplain
  13746. * @method queryCommandState
  13747. * @param { String } cmd 命令字符串
  13748. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13749. * @example
  13750. * ```javascript
  13751. * editor.queryCommandState( 'pasteplain' );
  13752. * ```
  13753. */
  13754. me.commands['pasteplain'] = {
  13755. queryCommandState: function (){
  13756. return pasteplain ? 1 : 0;
  13757. },
  13758. execCommand: function (){
  13759. pasteplain = !pasteplain|0;
  13760. },
  13761. notNeedUndo : 1
  13762. };
  13763. };
  13764. // plugins/list.js
  13765. /**
  13766. * 有序列表,无序列表插件
  13767. * @file
  13768. * @since 1.2.6.1
  13769. */
  13770. UE.plugins['list'] = function () {
  13771. var me = this,
  13772. notExchange = {
  13773. 'TD':1,
  13774. 'PRE':1,
  13775. 'BLOCKQUOTE':1
  13776. };
  13777. var customStyle = {
  13778. 'cn' : 'cn-1-',
  13779. 'cn1' : 'cn-2-',
  13780. 'cn2' : 'cn-3-',
  13781. 'num': 'num-1-',
  13782. 'num1' : 'num-2-',
  13783. 'num2' : 'num-3-',
  13784. 'dash' : 'dash',
  13785. 'dot':'dot'
  13786. };
  13787. me.setOpt( {
  13788. 'autoTransWordToList':false,
  13789. 'insertorderedlist':{
  13790. 'num':'',
  13791. 'num1':'',
  13792. 'num2':'',
  13793. 'cn':'',
  13794. 'cn1':'',
  13795. 'cn2':'',
  13796. 'decimal':'',
  13797. 'lower-alpha':'',
  13798. 'lower-roman':'',
  13799. 'upper-alpha':'',
  13800. 'upper-roman':''
  13801. },
  13802. 'insertunorderedlist':{
  13803. 'circle':'',
  13804. 'disc':'',
  13805. 'square':'',
  13806. 'dash' : '',
  13807. 'dot':''
  13808. },
  13809. listDefaultPaddingLeft : '30',
  13810. listiconpath : 'http://bs.baidu.com/listicon/',
  13811. maxListLevel : -1,//-1不限制
  13812. disablePInList:false
  13813. } );
  13814. function listToArray(list){
  13815. var arr = [];
  13816. for(var p in list){
  13817. arr.push(p)
  13818. }
  13819. return arr;
  13820. }
  13821. var listStyle = {
  13822. 'OL':listToArray(me.options.insertorderedlist),
  13823. 'UL':listToArray(me.options.insertunorderedlist)
  13824. };
  13825. var liiconpath = me.options.listiconpath;
  13826. //根据用户配置,调整customStyle
  13827. for(var s in customStyle){
  13828. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13829. delete customStyle[s];
  13830. }
  13831. }
  13832. me.ready(function () {
  13833. var customCss = [];
  13834. for(var p in customStyle){
  13835. if(p == 'dash' || p == 'dot'){
  13836. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13837. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13838. }else{
  13839. for(var i= 0;i<99;i++){
  13840. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13841. }
  13842. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13843. }
  13844. switch(p){
  13845. case 'cn':
  13846. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13847. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13848. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13849. break;
  13850. case 'cn1':
  13851. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13852. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13853. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13854. break;
  13855. case 'cn2':
  13856. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13857. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13858. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13859. break;
  13860. case 'num':
  13861. case 'num1':
  13862. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13863. break;
  13864. case 'num2':
  13865. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13866. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13867. break;
  13868. case 'dash':
  13869. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13870. break;
  13871. case 'dot':
  13872. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13873. }
  13874. }
  13875. customCss.push('.list-paddingleft-1{padding-left:0}');
  13876. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13877. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13878. //如果不给宽度会在自定应样式里出现滚动条
  13879. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13880. });
  13881. //单独处理剪切的问题
  13882. me.ready(function(){
  13883. domUtils.on(me.body,'cut',function(){
  13884. setTimeout(function(){
  13885. var rng = me.selection.getRange(),li;
  13886. //trace:3416
  13887. if(!rng.collapsed){
  13888. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13889. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13890. var pn = li.parentNode,node;
  13891. if(node = pn.previousSibling){
  13892. domUtils.remove(pn);
  13893. rng.setStartAtLast(node).collapse(true);
  13894. rng.select(true);
  13895. }else if(node = pn.nextSibling){
  13896. domUtils.remove(pn);
  13897. rng.setStartAtFirst(node).collapse(true);
  13898. rng.select(true);
  13899. }else{
  13900. var tmpNode = me.document.createElement('p');
  13901. domUtils.fillNode(me.document,tmpNode);
  13902. pn.parentNode.insertBefore(tmpNode,pn);
  13903. domUtils.remove(pn);
  13904. rng.setStart(tmpNode,0).collapse(true);
  13905. rng.select(true);
  13906. }
  13907. }
  13908. }
  13909. }
  13910. })
  13911. })
  13912. });
  13913. function getStyle(node){
  13914. var cls = node.className;
  13915. if(domUtils.hasClass(node,/custom_/)){
  13916. return cls.match(/custom_(\w+)/)[1]
  13917. }
  13918. return domUtils.getStyle(node, 'list-style-type')
  13919. }
  13920. me.addListener('beforepaste',function(type,html){
  13921. var me = this,
  13922. rng = me.selection.getRange(),li;
  13923. var root = UE.htmlparser(html.html,true);
  13924. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13925. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13926. utils.each(root.getNodesByTagName(tagName),function(n){
  13927. n.tagName = list.tagName;
  13928. n.setAttr();
  13929. if(n.parentNode === root){
  13930. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13931. }else{
  13932. var className = n.parentNode.getAttr('class');
  13933. if(className && /custom_/.test(className)){
  13934. type = className.match(/custom_(\w+)/)[1]
  13935. }else{
  13936. type = n.parentNode.getStyle('list-style-type');
  13937. }
  13938. if(!type){
  13939. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13940. }
  13941. }
  13942. var index = utils.indexOf(listStyle[list.tagName], type);
  13943. if(n.parentNode !== root)
  13944. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13945. var currentStyle = listStyle[list.tagName][index];
  13946. if(customStyle[currentStyle]){
  13947. n.setAttr('class', 'custom_' + currentStyle)
  13948. }else{
  13949. n.setStyle('list-style-type',currentStyle)
  13950. }
  13951. })
  13952. }
  13953. html.html = root.toHtml();
  13954. });
  13955. //导出时,去掉p标签
  13956. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13957. utils.each(root.getNodesByTagName('li'),function(li){
  13958. var newChildrens = [],index=0;
  13959. utils.each(li.children,function(n){
  13960. if(n.tagName == 'p'){
  13961. var tmpNode;
  13962. while(tmpNode = n.children.pop()) {
  13963. newChildrens.splice(index,0,tmpNode);
  13964. tmpNode.parentNode = li;
  13965. lastNode = tmpNode;
  13966. }
  13967. tmpNode = newChildrens[newChildrens.length-1];
  13968. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  13969. var br = UE.uNode.createElement('br');
  13970. br.parentNode = li;
  13971. newChildrens.push(br);
  13972. }
  13973. index = newChildrens.length;
  13974. }
  13975. });
  13976. if(newChildrens.length){
  13977. li.children = newChildrens;
  13978. }
  13979. });
  13980. });
  13981. //进入编辑器的li要套p标签
  13982. me.addInputRule(function(root){
  13983. utils.each(root.getNodesByTagName('li'),function(li){
  13984. var tmpP = UE.uNode.createElement('p');
  13985. for(var i= 0,ci;ci=li.children[i];){
  13986. if(ci.type == 'text' || dtd.p[ci.tagName]){
  13987. tmpP.appendChild(ci);
  13988. }else{
  13989. if(tmpP.firstChild()){
  13990. li.insertBefore(tmpP,ci);
  13991. tmpP = UE.uNode.createElement('p');
  13992. i = i + 2;
  13993. }else{
  13994. i++;
  13995. }
  13996. }
  13997. }
  13998. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  13999. li.appendChild(tmpP);
  14000. }
  14001. //trace:3357
  14002. //p不能为空
  14003. if (!tmpP.firstChild()) {
  14004. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14005. }
  14006. //去掉末尾的空白
  14007. var p = li.firstChild();
  14008. var lastChild = p.lastChild();
  14009. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  14010. p.removeChild(lastChild)
  14011. }
  14012. });
  14013. if(me.options.autoTransWordToList){
  14014. var orderlisttype = {
  14015. 'num1':/^\d+\)/,
  14016. 'decimal':/^\d+\./,
  14017. 'lower-alpha':/^[a-z]+\)/,
  14018. 'upper-alpha':/^[A-Z]+\./,
  14019. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14020. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14021. },
  14022. unorderlisttype = {
  14023. 'square':'n'
  14024. };
  14025. function checkListType(content,container){
  14026. var span = container.firstChild();
  14027. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14028. for(var p in unorderlisttype){
  14029. if(unorderlisttype[p] == span.data){
  14030. return p
  14031. }
  14032. }
  14033. return 'disc'
  14034. }
  14035. for(var p in orderlisttype){
  14036. if(orderlisttype[p].test(content)){
  14037. return p;
  14038. }
  14039. }
  14040. }
  14041. utils.each(root.getNodesByTagName('p'),function(node){
  14042. if(node.getAttr('class') != 'MsoListParagraph'){
  14043. return
  14044. }
  14045. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14046. node.setStyle('margin','');
  14047. node.setStyle('margin-left','');
  14048. node.setAttr('class','');
  14049. function appendLi(list,p,type){
  14050. if(list.tagName == 'ol'){
  14051. if(browser.ie){
  14052. var first = p.firstChild();
  14053. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14054. p.removeChild(first);
  14055. }
  14056. }else{
  14057. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14058. }
  14059. }else{
  14060. p.removeChild(p.firstChild())
  14061. }
  14062. var li = UE.uNode.createElement('li');
  14063. li.appendChild(p);
  14064. list.appendChild(li);
  14065. }
  14066. var tmp = node,type,cacheNode = node;
  14067. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14068. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14069. if(customStyle[type]){
  14070. list.setAttr('class','custom_'+type)
  14071. }else{
  14072. list.setStyle('list-style-type',type)
  14073. }
  14074. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14075. tmp = node.nextSibling();
  14076. if(!tmp){
  14077. node.parentNode.insertBefore(list,node)
  14078. }
  14079. appendLi(list,node,type);
  14080. node = tmp;
  14081. }
  14082. if(!list.parentNode && node && node.parentNode){
  14083. node.parentNode.insertBefore(list,node)
  14084. }
  14085. }
  14086. var span = cacheNode.firstChild();
  14087. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14088. span.parentNode.removeChild(span)
  14089. }
  14090. })
  14091. }
  14092. });
  14093. //调整索引标签
  14094. me.addListener('contentchange',function(){
  14095. adjustListStyle(me.document)
  14096. });
  14097. function adjustListStyle(doc,ignore){
  14098. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14099. if(!domUtils.inDoc(node,doc))
  14100. return;
  14101. var parent = node.parentNode;
  14102. if(parent.tagName == node.tagName){
  14103. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14104. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14105. if(nodeStyleType == parentStyleType){
  14106. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14107. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14108. setListStyle(node,listStyle[node.tagName][styleIndex])
  14109. }
  14110. }
  14111. var index = 0,type = 2;
  14112. if( domUtils.hasClass(node,/custom_/)){
  14113. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14114. type = 1;
  14115. }
  14116. }else{
  14117. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14118. type = 3;
  14119. }
  14120. }
  14121. var style = domUtils.getStyle(node, 'list-style-type');
  14122. style && (node.style.cssText = 'list-style-type:' + style);
  14123. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14124. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14125. li.style.cssText && (li.style.cssText = '');
  14126. if(!li.firstChild){
  14127. domUtils.remove(li);
  14128. return;
  14129. }
  14130. if(li.parentNode !== node){
  14131. return;
  14132. }
  14133. index++;
  14134. if(domUtils.hasClass(node,/custom_/) ){
  14135. var paddingLeft = 1,currentStyle = getStyle(node);
  14136. if(node.tagName == 'OL'){
  14137. if(currentStyle){
  14138. switch(currentStyle){
  14139. case 'cn' :
  14140. case 'cn1':
  14141. case 'cn2':
  14142. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14143. paddingLeft = 2
  14144. }else if(index > 20){
  14145. paddingLeft = 3
  14146. }
  14147. break;
  14148. case 'num2' :
  14149. if(index > 9){
  14150. paddingLeft = 2
  14151. }
  14152. }
  14153. }
  14154. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14155. }else{
  14156. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14157. }
  14158. }else{
  14159. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14160. }
  14161. var className = li.getAttribute('class');
  14162. if(className !== null && !className.replace(/\s/g,'')){
  14163. domUtils.removeAttributes(li,'class')
  14164. }
  14165. });
  14166. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14167. })
  14168. }
  14169. function adjustList(list, tag, style,ignoreEmpty) {
  14170. var nextList = list.nextSibling;
  14171. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14172. domUtils.moveChild(nextList, list);
  14173. if (nextList.childNodes.length == 0) {
  14174. domUtils.remove(nextList);
  14175. }
  14176. }
  14177. if(nextList && domUtils.isFillChar(nextList)){
  14178. domUtils.remove(nextList);
  14179. }
  14180. var preList = list.previousSibling;
  14181. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14182. domUtils.moveChild(list, preList);
  14183. }
  14184. if(preList && domUtils.isFillChar(preList)){
  14185. domUtils.remove(preList);
  14186. }
  14187. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14188. if(getStyle(list)){
  14189. adjustListStyle(list.ownerDocument,true)
  14190. }
  14191. }
  14192. function setListStyle(list,style){
  14193. if(customStyle[style]){
  14194. list.className = 'custom_' + style;
  14195. }
  14196. try{
  14197. domUtils.setStyle(list, 'list-style-type', style);
  14198. }catch(e){}
  14199. }
  14200. function clearEmptySibling(node) {
  14201. var tmpNode = node.previousSibling;
  14202. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14203. domUtils.remove(tmpNode);
  14204. }
  14205. tmpNode = node.nextSibling;
  14206. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14207. domUtils.remove(tmpNode);
  14208. }
  14209. }
  14210. me.addListener('keydown', function (type, evt) {
  14211. function preventAndSave() {
  14212. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14213. me.fireEvent('contentchange');
  14214. me.undoManger && me.undoManger.save();
  14215. }
  14216. function findList(node,filterFn){
  14217. while(node && !domUtils.isBody(node)){
  14218. if(filterFn(node)){
  14219. return null
  14220. }
  14221. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14222. return node;
  14223. }
  14224. node = node.parentNode;
  14225. }
  14226. return null;
  14227. }
  14228. var keyCode = evt.keyCode || evt.which;
  14229. if (keyCode == 13 && !evt.shiftKey) {//回车
  14230. var rng = me.selection.getRange(),
  14231. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14232. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14233. if(parent && parent.tagName != 'PRE' && !li){
  14234. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14235. if(/^\s*1\s*\.[^\d]/.test(html)){
  14236. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14237. rng.setStartAtLast(parent).collapse(true).select();
  14238. me.__hasEnterExecCommand = true;
  14239. me.execCommand('insertorderedlist');
  14240. me.__hasEnterExecCommand = false;
  14241. }
  14242. }
  14243. var range = me.selection.getRange(),
  14244. start = findList(range.startContainer,function (node) {
  14245. return node.tagName == 'TABLE';
  14246. }),
  14247. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14248. return node.tagName == 'TABLE';
  14249. });
  14250. if (start && end && start === end) {
  14251. if (!range.collapsed) {
  14252. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14253. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14254. if (start && end && start === end) {
  14255. range.deleteContents();
  14256. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14257. if (li && domUtils.isEmptyBlock(li)) {
  14258. pre = li.previousSibling;
  14259. next = li.nextSibling;
  14260. p = me.document.createElement('p');
  14261. domUtils.fillNode(me.document, p);
  14262. parentList = li.parentNode;
  14263. if (pre && next) {
  14264. range.setStart(next, 0).collapse(true).select(true);
  14265. domUtils.remove(li);
  14266. } else {
  14267. if (!pre && !next || !pre) {
  14268. parentList.parentNode.insertBefore(p, parentList);
  14269. } else {
  14270. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14271. }
  14272. domUtils.remove(li);
  14273. if (!parentList.firstChild) {
  14274. domUtils.remove(parentList);
  14275. }
  14276. range.setStart(p, 0).setCursor();
  14277. }
  14278. preventAndSave();
  14279. return;
  14280. }
  14281. } else {
  14282. var tmpRange = range.cloneRange(),
  14283. bk = tmpRange.collapse(false).createBookmark();
  14284. range.deleteContents();
  14285. tmpRange.moveToBookmark(bk);
  14286. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14287. clearEmptySibling(li);
  14288. tmpRange.select();
  14289. preventAndSave();
  14290. return;
  14291. }
  14292. }
  14293. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14294. if (li) {
  14295. if (domUtils.isEmptyBlock(li)) {
  14296. bk = range.createBookmark();
  14297. var parentList = li.parentNode;
  14298. if (li !== parentList.lastChild) {
  14299. domUtils.breakParent(li, parentList);
  14300. clearEmptySibling(li);
  14301. } else {
  14302. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14303. if (domUtils.isEmptyNode(parentList)) {
  14304. domUtils.remove(parentList);
  14305. }
  14306. }
  14307. //嵌套不处理
  14308. if (!dtd.$list[li.parentNode.tagName]) {
  14309. if (!domUtils.isBlockElm(li.firstChild)) {
  14310. p = me.document.createElement('p');
  14311. li.parentNode.insertBefore(p, li);
  14312. while (li.firstChild) {
  14313. p.appendChild(li.firstChild);
  14314. }
  14315. domUtils.remove(li);
  14316. } else {
  14317. domUtils.remove(li, true);
  14318. }
  14319. }
  14320. range.moveToBookmark(bk).select();
  14321. } else {
  14322. var first = li.firstChild;
  14323. if (!first || !domUtils.isBlockElm(first)) {
  14324. var p = me.document.createElement('p');
  14325. !li.firstChild && domUtils.fillNode(me.document, p);
  14326. while (li.firstChild) {
  14327. p.appendChild(li.firstChild);
  14328. }
  14329. li.appendChild(p);
  14330. first = p;
  14331. }
  14332. var span = me.document.createElement('span');
  14333. range.insertNode(span);
  14334. domUtils.breakParent(span, li);
  14335. var nextLi = span.nextSibling;
  14336. first = nextLi.firstChild;
  14337. if (!first) {
  14338. p = me.document.createElement('p');
  14339. domUtils.fillNode(me.document, p);
  14340. nextLi.appendChild(p);
  14341. first = p;
  14342. }
  14343. if (domUtils.isEmptyNode(first)) {
  14344. first.innerHTML = '';
  14345. domUtils.fillNode(me.document, first);
  14346. }
  14347. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14348. domUtils.remove(span);
  14349. var pre = nextLi.previousSibling;
  14350. if (pre && domUtils.isEmptyBlock(pre)) {
  14351. pre.innerHTML = '<p></p>';
  14352. domUtils.fillNode(me.document, pre.firstChild);
  14353. }
  14354. }
  14355. // }
  14356. preventAndSave();
  14357. }
  14358. }
  14359. }
  14360. if (keyCode == 8) {
  14361. //修中ie中li下的问题
  14362. range = me.selection.getRange();
  14363. if (range.collapsed && domUtils.isStartInblock(range)) {
  14364. tmpRange = range.cloneRange().trimBoundary();
  14365. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14366. //要在li的最左边,才能处理
  14367. if (li && domUtils.isStartInblock(tmpRange)) {
  14368. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14369. if (start && start !== li.firstChild) {
  14370. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14371. domUtils.breakParent(start,parentList);
  14372. clearEmptySibling(start);
  14373. me.fireEvent('contentchange');
  14374. range.setStart(start,0).setCursor(false,true);
  14375. me.fireEvent('saveScene');
  14376. domUtils.preventDefault(evt);
  14377. return;
  14378. }
  14379. if (li && (pre = li.previousSibling)) {
  14380. if (keyCode == 46 && li.childNodes.length) {
  14381. return;
  14382. }
  14383. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14384. if (dtd.$list[pre.tagName]) {
  14385. pre = pre.lastChild;
  14386. }
  14387. me.undoManger && me.undoManger.save();
  14388. first = li.firstChild;
  14389. if (domUtils.isBlockElm(first)) {
  14390. if (domUtils.isEmptyNode(first)) {
  14391. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14392. pre.appendChild(first);
  14393. range.setStart(first, 0).setCursor(false, true);
  14394. //first不是唯一的节点
  14395. while (li.firstChild) {
  14396. pre.appendChild(li.firstChild);
  14397. }
  14398. } else {
  14399. span = me.document.createElement('span');
  14400. range.insertNode(span);
  14401. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14402. if (domUtils.isEmptyBlock(pre)) {
  14403. pre.innerHTML = '';
  14404. }
  14405. domUtils.moveChild(li, pre);
  14406. range.setStartBefore(span).collapse(true).select(true);
  14407. domUtils.remove(span);
  14408. }
  14409. } else {
  14410. if (domUtils.isEmptyNode(li)) {
  14411. var p = me.document.createElement('p');
  14412. pre.appendChild(p);
  14413. range.setStart(p, 0).setCursor();
  14414. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14415. } else {
  14416. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14417. while (li.firstChild) {
  14418. pre.appendChild(li.firstChild);
  14419. }
  14420. }
  14421. }
  14422. domUtils.remove(li);
  14423. me.fireEvent('contentchange');
  14424. me.fireEvent('saveScene');
  14425. domUtils.preventDefault(evt);
  14426. return;
  14427. }
  14428. //trace:980
  14429. if (li && !li.previousSibling) {
  14430. var parentList = li.parentNode;
  14431. var bk = range.createBookmark();
  14432. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14433. parentList.parentNode.insertBefore(li,parentList);
  14434. if(domUtils.isEmptyNode(parentList)){
  14435. domUtils.remove(parentList)
  14436. }
  14437. }else{
  14438. while(li.firstChild){
  14439. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14440. }
  14441. domUtils.remove(li);
  14442. if(domUtils.isEmptyNode(parentList)){
  14443. domUtils.remove(parentList)
  14444. }
  14445. }
  14446. range.moveToBookmark(bk).setCursor(false,true);
  14447. me.fireEvent('contentchange');
  14448. me.fireEvent('saveScene');
  14449. domUtils.preventDefault(evt);
  14450. return;
  14451. }
  14452. }
  14453. }
  14454. }
  14455. });
  14456. me.addListener('keyup',function(type, evt){
  14457. var keyCode = evt.keyCode || evt.which;
  14458. if (keyCode == 8) {
  14459. var rng = me.selection.getRange(),list;
  14460. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14461. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14462. }
  14463. }
  14464. });
  14465. //处理tab键
  14466. me.addListener('tabkeydown',function(){
  14467. var range = me.selection.getRange();
  14468. //控制级数
  14469. function checkLevel(li){
  14470. if(me.options.maxListLevel != -1){
  14471. var level = li.parentNode,levelNum = 0;
  14472. while(/[ou]l/i.test(level.tagName)){
  14473. levelNum++;
  14474. level = level.parentNode;
  14475. }
  14476. if(levelNum >= me.options.maxListLevel){
  14477. return true;
  14478. }
  14479. }
  14480. }
  14481. //只以开始为准
  14482. //todo 后续改进
  14483. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14484. if(li){
  14485. var bk;
  14486. if(range.collapsed){
  14487. if(checkLevel(li))
  14488. return true;
  14489. var parentLi = li.parentNode,
  14490. list = me.document.createElement(parentLi.tagName),
  14491. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14492. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14493. var currentStyle = listStyle[list.tagName][index];
  14494. setListStyle(list,currentStyle);
  14495. if(domUtils.isStartInblock(range)){
  14496. me.fireEvent('saveScene');
  14497. bk = range.createBookmark();
  14498. parentLi.insertBefore(list, li);
  14499. list.appendChild(li);
  14500. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14501. me.fireEvent('contentchange');
  14502. range.moveToBookmark(bk).select(true);
  14503. return true;
  14504. }
  14505. }else{
  14506. me.fireEvent('saveScene');
  14507. bk = range.createBookmark();
  14508. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14509. if(domUtils.isTagNode(ci,'ol ul')){
  14510. closeList = ci;
  14511. break;
  14512. }
  14513. }
  14514. var current = li;
  14515. if(bk.end){
  14516. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14517. if(checkLevel(current)){
  14518. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14519. continue;
  14520. }
  14521. var parentLi = current.parentNode,
  14522. list = me.document.createElement(parentLi.tagName),
  14523. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14524. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14525. var currentStyle = listStyle[list.tagName][currentIndex];
  14526. setListStyle(list,currentStyle);
  14527. parentLi.insertBefore(list, current);
  14528. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14529. li = current.nextSibling;
  14530. list.appendChild(current);
  14531. if(!li || domUtils.isTagNode(li,'ol ul')){
  14532. if(li){
  14533. while(li = li.firstChild){
  14534. if(li.tagName == 'LI'){
  14535. break;
  14536. }
  14537. }
  14538. }else{
  14539. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14540. }
  14541. break;
  14542. }
  14543. current = li;
  14544. }
  14545. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14546. current = li;
  14547. }
  14548. }
  14549. me.fireEvent('contentchange');
  14550. range.moveToBookmark(bk).select();
  14551. return true;
  14552. }
  14553. }
  14554. });
  14555. function getLi(start){
  14556. while(start && !domUtils.isBody(start)){
  14557. if(start.nodeName == 'TABLE'){
  14558. return null;
  14559. }
  14560. if(start.nodeName == 'LI'){
  14561. return start
  14562. }
  14563. start = start.parentNode;
  14564. }
  14565. }
  14566. /**
  14567. * 有序列表,与“insertunorderedlist”命令互斥
  14568. * @command insertorderedlist
  14569. * @method execCommand
  14570. * @param { String } command 命令字符串
  14571. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14572. * @example
  14573. * ```javascript
  14574. * editor.execCommand( 'insertorderedlist','decimal');
  14575. * ```
  14576. */
  14577. /**
  14578. * 查询当前选区内容是否有序列表
  14579. * @command insertorderedlist
  14580. * @method queryCommandState
  14581. * @param { String } cmd 命令字符串
  14582. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14583. * @example
  14584. * ```javascript
  14585. * editor.queryCommandState( 'insertorderedlist' );
  14586. * ```
  14587. */
  14588. /**
  14589. * 查询当前选区内容是否有序列表
  14590. * @command insertorderedlist
  14591. * @method queryCommandValue
  14592. * @param { String } cmd 命令字符串
  14593. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14594. * @example
  14595. * ```javascript
  14596. * editor.queryCommandValue( 'insertorderedlist' );
  14597. * ```
  14598. */
  14599. /**
  14600. * 无序列表,与“insertorderedlist”命令互斥
  14601. * @command insertunorderedlist
  14602. * @method execCommand
  14603. * @param { String } command 命令字符串
  14604. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14605. * @example
  14606. * ```javascript
  14607. * editor.execCommand( 'insertunorderedlist','circle');
  14608. * ```
  14609. */
  14610. /**
  14611. * 查询当前是否有word文档粘贴进来的图片
  14612. * @command insertunorderedlist
  14613. * @method insertunorderedlist
  14614. * @param { String } command 命令字符串
  14615. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14616. * @example
  14617. * ```javascript
  14618. * editor.queryCommandState( 'insertunorderedlist' );
  14619. * ```
  14620. */
  14621. /**
  14622. * 查询当前选区内容是否有序列表
  14623. * @command insertunorderedlist
  14624. * @method queryCommandValue
  14625. * @param { String } command 命令字符串
  14626. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14627. * @example
  14628. * ```javascript
  14629. * editor.queryCommandValue( 'insertunorderedlist' );
  14630. * ```
  14631. */
  14632. me.commands['insertorderedlist'] =
  14633. me.commands['insertunorderedlist'] = {
  14634. execCommand:function (command, style) {
  14635. if (!style) {
  14636. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14637. }
  14638. var me = this,
  14639. range = this.selection.getRange(),
  14640. filterFn = function (node) {
  14641. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14642. },
  14643. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14644. frag = me.document.createDocumentFragment();
  14645. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14646. //range.shrinkBoundary();//.adjustmentBoundary();
  14647. range.adjustmentBoundary().shrinkBoundary();
  14648. var bko = range.createBookmark(true),
  14649. start = getLi(me.document.getElementById(bko.start)),
  14650. modifyStart = 0,
  14651. end = getLi(me.document.getElementById(bko.end)),
  14652. modifyEnd = 0,
  14653. startParent, endParent,
  14654. list, tmp;
  14655. if (start || end) {
  14656. start && (startParent = start.parentNode);
  14657. if (!bko.end) {
  14658. end = start;
  14659. }
  14660. end && (endParent = end.parentNode);
  14661. if (startParent === endParent) {
  14662. while (start !== end) {
  14663. tmp = start;
  14664. start = start.nextSibling;
  14665. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14666. var p = me.document.createElement('p');
  14667. while (tmp.firstChild) {
  14668. p.appendChild(tmp.firstChild);
  14669. }
  14670. tmp.appendChild(p);
  14671. }
  14672. frag.appendChild(tmp);
  14673. }
  14674. tmp = me.document.createElement('span');
  14675. startParent.insertBefore(tmp, end);
  14676. if (!domUtils.isBlockElm(end.firstChild)) {
  14677. p = me.document.createElement('p');
  14678. while (end.firstChild) {
  14679. p.appendChild(end.firstChild);
  14680. }
  14681. end.appendChild(p);
  14682. }
  14683. frag.appendChild(end);
  14684. domUtils.breakParent(tmp, startParent);
  14685. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14686. domUtils.remove(tmp.previousSibling);
  14687. }
  14688. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14689. domUtils.remove(tmp.nextSibling)
  14690. }
  14691. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14692. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14693. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14694. if(domUtils.isTagNode(ci,'ol ul')){
  14695. // 删除时,子列表不处理
  14696. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14697. // while(li.firstChild){
  14698. // tmpFrag.appendChild(li.firstChild);
  14699. // }
  14700. //
  14701. // });
  14702. tmpFrag.appendChild(ci);
  14703. }else{
  14704. while (ci.firstChild) {
  14705. tmpFrag.appendChild(ci.firstChild);
  14706. domUtils.remove(ci);
  14707. }
  14708. }
  14709. }
  14710. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14711. } else {
  14712. list = me.document.createElement(tag);
  14713. setListStyle(list,style);
  14714. list.appendChild(frag);
  14715. tmp.parentNode.insertBefore(list, tmp);
  14716. }
  14717. domUtils.remove(tmp);
  14718. list && adjustList(list, tag, style);
  14719. range.moveToBookmark(bko).select();
  14720. return;
  14721. }
  14722. //开始
  14723. if (start) {
  14724. while (start) {
  14725. tmp = start.nextSibling;
  14726. if (domUtils.isTagNode(start, 'ol ul')) {
  14727. frag.appendChild(start);
  14728. } else {
  14729. var tmpfrag = me.document.createDocumentFragment(),
  14730. hasBlock = 0;
  14731. while (start.firstChild) {
  14732. if (domUtils.isBlockElm(start.firstChild)) {
  14733. hasBlock = 1;
  14734. }
  14735. tmpfrag.appendChild(start.firstChild);
  14736. }
  14737. if (!hasBlock) {
  14738. var tmpP = me.document.createElement('p');
  14739. tmpP.appendChild(tmpfrag);
  14740. frag.appendChild(tmpP);
  14741. } else {
  14742. frag.appendChild(tmpfrag);
  14743. }
  14744. domUtils.remove(start);
  14745. }
  14746. start = tmp;
  14747. }
  14748. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14749. if (domUtils.isEmptyNode(startParent)) {
  14750. range.setStartBefore(startParent);
  14751. domUtils.remove(startParent);
  14752. } else {
  14753. range.setStartAfter(startParent);
  14754. }
  14755. modifyStart = 1;
  14756. }
  14757. if (end && domUtils.inDoc(endParent, me.document)) {
  14758. //结束
  14759. start = endParent.firstChild;
  14760. while (start && start !== end) {
  14761. tmp = start.nextSibling;
  14762. if (domUtils.isTagNode(start, 'ol ul')) {
  14763. frag.appendChild(start);
  14764. } else {
  14765. tmpfrag = me.document.createDocumentFragment();
  14766. hasBlock = 0;
  14767. while (start.firstChild) {
  14768. if (domUtils.isBlockElm(start.firstChild)) {
  14769. hasBlock = 1;
  14770. }
  14771. tmpfrag.appendChild(start.firstChild);
  14772. }
  14773. if (!hasBlock) {
  14774. tmpP = me.document.createElement('p');
  14775. tmpP.appendChild(tmpfrag);
  14776. frag.appendChild(tmpP);
  14777. } else {
  14778. frag.appendChild(tmpfrag);
  14779. }
  14780. domUtils.remove(start);
  14781. }
  14782. start = tmp;
  14783. }
  14784. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14785. 'tmpDiv':1
  14786. });
  14787. domUtils.moveChild(end, tmpDiv);
  14788. frag.appendChild(tmpDiv);
  14789. domUtils.remove(end);
  14790. endParent.parentNode.insertBefore(frag, endParent);
  14791. range.setEndBefore(endParent);
  14792. if (domUtils.isEmptyNode(endParent)) {
  14793. domUtils.remove(endParent);
  14794. }
  14795. modifyEnd = 1;
  14796. }
  14797. }
  14798. if (!modifyStart) {
  14799. range.setStartBefore(me.document.getElementById(bko.start));
  14800. }
  14801. if (bko.end && !modifyEnd) {
  14802. range.setEndAfter(me.document.getElementById(bko.end));
  14803. }
  14804. range.enlarge(true, function (node) {
  14805. return notExchange[node.tagName];
  14806. });
  14807. frag = me.document.createDocumentFragment();
  14808. var bk = range.createBookmark(),
  14809. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14810. tmpRange = range.cloneRange(),
  14811. tmpNode,
  14812. block = domUtils.isBlockElm;
  14813. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14814. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14815. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14816. while (current.firstChild) {
  14817. frag.appendChild(current.firstChild);
  14818. }
  14819. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14820. domUtils.remove(current);
  14821. current = tmpNode;
  14822. continue;
  14823. }
  14824. tmpNode = current;
  14825. tmpRange.setStartBefore(current);
  14826. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14827. tmpNode = current;
  14828. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14829. return !notExchange[node.tagName];
  14830. });
  14831. }
  14832. if (current && block(current)) {
  14833. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14834. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14835. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14836. tmpNode = tmp;
  14837. }
  14838. }
  14839. tmpRange.setEndAfter(tmpNode);
  14840. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14841. var li = range.document.createElement('li');
  14842. li.appendChild(tmpRange.extractContents());
  14843. if(domUtils.isEmptyNode(li)){
  14844. var tmpNode = range.document.createElement('p');
  14845. while(li.firstChild){
  14846. tmpNode.appendChild(li.firstChild)
  14847. }
  14848. li.appendChild(tmpNode);
  14849. }
  14850. frag.appendChild(li);
  14851. } else {
  14852. current = domUtils.getNextDomNode(current, true, filterFn);
  14853. }
  14854. }
  14855. range.moveToBookmark(bk).collapse(true);
  14856. list = me.document.createElement(tag);
  14857. setListStyle(list,style);
  14858. list.appendChild(frag);
  14859. range.insertNode(list);
  14860. //当前list上下看能否合并
  14861. adjustList(list, tag, style);
  14862. //去掉冗余的tmpDiv
  14863. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14864. if (ci.getAttribute('tmpDiv')) {
  14865. domUtils.remove(ci, true)
  14866. }
  14867. }
  14868. range.moveToBookmark(bko).select();
  14869. },
  14870. queryCommandState:function (command) {
  14871. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14872. var path = this.selection.getStartElementPath();
  14873. for(var i= 0,ci;ci = path[i++];){
  14874. if(ci.nodeName == 'TABLE'){
  14875. return 0
  14876. }
  14877. if(tag == ci.nodeName.toLowerCase()){
  14878. return 1
  14879. };
  14880. }
  14881. return 0;
  14882. },
  14883. queryCommandValue:function (command) {
  14884. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14885. var path = this.selection.getStartElementPath(),
  14886. node;
  14887. for(var i= 0,ci;ci = path[i++];){
  14888. if(ci.nodeName == 'TABLE'){
  14889. node = null;
  14890. break;
  14891. }
  14892. if(tag == ci.nodeName.toLowerCase()){
  14893. node = ci;
  14894. break;
  14895. };
  14896. }
  14897. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14898. }
  14899. };
  14900. };
  14901. // plugins/source.js
  14902. /**
  14903. * 源码编辑插件
  14904. * @file
  14905. * @since 1.2.6.1
  14906. */
  14907. (function (){
  14908. var sourceEditors = {
  14909. textarea: function (editor, holder){
  14910. var textarea = holder.ownerDocument.createElement('textarea');
  14911. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14912. // todo: IE下只有onresize属性可用... 很纠结
  14913. if (browser.ie && browser.version < 8) {
  14914. textarea.style.width = holder.offsetWidth + 'px';
  14915. textarea.style.height = holder.offsetHeight + 'px';
  14916. holder.onresize = function (){
  14917. textarea.style.width = holder.offsetWidth + 'px';
  14918. textarea.style.height = holder.offsetHeight + 'px';
  14919. };
  14920. }
  14921. holder.appendChild(textarea);
  14922. return {
  14923. setContent: function (content){
  14924. textarea.value = content;
  14925. },
  14926. getContent: function (){
  14927. return textarea.value;
  14928. },
  14929. select: function (){
  14930. var range;
  14931. if (browser.ie) {
  14932. range = textarea.createTextRange();
  14933. range.collapse(true);
  14934. range.select();
  14935. } else {
  14936. //todo: chrome下无法设置焦点
  14937. textarea.setSelectionRange(0, 0);
  14938. textarea.focus();
  14939. }
  14940. },
  14941. dispose: function (){
  14942. holder.removeChild(textarea);
  14943. // todo
  14944. holder.onresize = null;
  14945. textarea = null;
  14946. holder = null;
  14947. }
  14948. };
  14949. },
  14950. codemirror: function (editor, holder){
  14951. var codeEditor = window.CodeMirror(holder, {
  14952. mode: "text/html",
  14953. tabMode: "indent",
  14954. lineNumbers: true,
  14955. lineWrapping:true
  14956. });
  14957. var dom = codeEditor.getWrapperElement();
  14958. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14959. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14960. codeEditor.refresh();
  14961. return {
  14962. getCodeMirror:function(){
  14963. return codeEditor;
  14964. },
  14965. setContent: function (content){
  14966. codeEditor.setValue(content);
  14967. },
  14968. getContent: function (){
  14969. return codeEditor.getValue();
  14970. },
  14971. select: function (){
  14972. codeEditor.focus();
  14973. },
  14974. dispose: function (){
  14975. holder.removeChild(dom);
  14976. dom = null;
  14977. codeEditor = null;
  14978. }
  14979. };
  14980. }
  14981. };
  14982. UE.plugins['source'] = function (){
  14983. var me = this;
  14984. var opt = this.options;
  14985. var sourceMode = false;
  14986. var sourceEditor;
  14987. var orgSetContent;
  14988. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  14989. me.setOpt({
  14990. sourceEditorFirst:false
  14991. });
  14992. function createSourceEditor(holder){
  14993. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  14994. }
  14995. var bakCssText;
  14996. //解决在源码模式下getContent不能得到最新的内容问题
  14997. var oldGetContent,
  14998. bakAddress;
  14999. /**
  15000. * 切换源码模式和编辑模式
  15001. * @command source
  15002. * @method execCommand
  15003. * @param { String } cmd 命令字符串
  15004. * @example
  15005. * ```javascript
  15006. * editor.execCommand( 'source');
  15007. * ```
  15008. */
  15009. /**
  15010. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15011. * @command source
  15012. * @method queryCommandState
  15013. * @param { String } cmd 命令字符串
  15014. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15015. * @example
  15016. * ```javascript
  15017. * editor.queryCommandState( 'source' );
  15018. * ```
  15019. */
  15020. me.commands['source'] = {
  15021. execCommand: function (){
  15022. sourceMode = !sourceMode;
  15023. if (sourceMode) {
  15024. bakAddress = me.selection.getRange().createAddress(false,true);
  15025. me.undoManger && me.undoManger.save(true);
  15026. if(browser.gecko){
  15027. me.body.contentEditable = false;
  15028. }
  15029. bakCssText = me.iframe.style.cssText;
  15030. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15031. me.fireEvent('beforegetcontent');
  15032. var root = UE.htmlparser(me.body.innerHTML);
  15033. me.filterOutputRule(root);
  15034. root.traversal(function (node) {
  15035. if (node.type == 'element') {
  15036. switch (node.tagName) {
  15037. case 'td':
  15038. case 'th':
  15039. case 'caption':
  15040. if(node.children && node.children.length == 1){
  15041. if(node.firstChild().tagName == 'br' ){
  15042. node.removeChild(node.firstChild())
  15043. }
  15044. };
  15045. break;
  15046. case 'pre':
  15047. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15048. }
  15049. }
  15050. });
  15051. me.fireEvent('aftergetcontent');
  15052. var content = root.toHtml(true);
  15053. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15054. sourceEditor.setContent(content);
  15055. orgSetContent = me.setContent;
  15056. me.setContent = function(html){
  15057. //这里暂时不触发事件,防止报错
  15058. var root = UE.htmlparser(html);
  15059. me.filterInputRule(root);
  15060. html = root.toHtml();
  15061. sourceEditor.setContent(html);
  15062. };
  15063. setTimeout(function (){
  15064. sourceEditor.select();
  15065. me.addListener('fullscreenchanged', function(){
  15066. try{
  15067. sourceEditor.getCodeMirror().refresh()
  15068. }catch(e){}
  15069. });
  15070. });
  15071. //重置getContent,源码模式下取值也能是最新的数据
  15072. oldGetContent = me.getContent;
  15073. me.getContent = function (){
  15074. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15075. };
  15076. } else {
  15077. me.iframe.style.cssText = bakCssText;
  15078. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15079. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15080. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15081. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15082. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15083. }
  15084. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15085. });
  15086. me.setContent = orgSetContent;
  15087. me.setContent(cont);
  15088. sourceEditor.dispose();
  15089. sourceEditor = null;
  15090. //还原getContent方法
  15091. me.getContent = oldGetContent;
  15092. var first = me.body.firstChild;
  15093. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15094. if(!first){
  15095. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15096. first = me.body.firstChild;
  15097. }
  15098. //要在ifm为显示时ff才能取到selection,否则报错
  15099. //这里不能比较位置了
  15100. me.undoManger && me.undoManger.save(true);
  15101. if(browser.gecko){
  15102. var input = document.createElement('input');
  15103. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15104. document.body.appendChild(input);
  15105. me.body.contentEditable = false;
  15106. setTimeout(function(){
  15107. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15108. input.focus();
  15109. setTimeout(function(){
  15110. me.body.contentEditable = true;
  15111. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15112. domUtils.remove(input);
  15113. });
  15114. });
  15115. }else{
  15116. //ie下有可能报错,比如在代码顶头的情况
  15117. try{
  15118. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15119. }catch(e){}
  15120. }
  15121. }
  15122. this.fireEvent('sourcemodechanged', sourceMode);
  15123. },
  15124. queryCommandState: function (){
  15125. return sourceMode|0;
  15126. },
  15127. notNeedUndo : 1
  15128. };
  15129. var oldQueryCommandState = me.queryCommandState;
  15130. me.queryCommandState = function (cmdName){
  15131. cmdName = cmdName.toLowerCase();
  15132. if (sourceMode) {
  15133. //源码模式下可以开启的命令
  15134. return cmdName in {
  15135. 'source' : 1,
  15136. 'fullscreen' : 1
  15137. } ? 1 : -1
  15138. }
  15139. return oldQueryCommandState.apply(this, arguments);
  15140. };
  15141. if(opt.sourceEditor == "codemirror"){
  15142. me.addListener("ready",function(){
  15143. utils.loadFile(document,{
  15144. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15145. tag : "script",
  15146. type : "text/javascript",
  15147. defer : "defer"
  15148. },function(){
  15149. if(opt.sourceEditorFirst){
  15150. setTimeout(function(){
  15151. me.execCommand("source");
  15152. },0);
  15153. }
  15154. });
  15155. utils.loadFile(document,{
  15156. tag : "link",
  15157. rel : "stylesheet",
  15158. type : "text/css",
  15159. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15160. });
  15161. });
  15162. }
  15163. };
  15164. })();
  15165. // plugins/enterkey.js
  15166. ///import core
  15167. ///import plugins/undo.js
  15168. ///commands 设置回车标签p或br
  15169. ///commandsName EnterKey
  15170. ///commandsTitle 设置回车标签p或br
  15171. /**
  15172. * @description 处理回车
  15173. * @author zhanyi
  15174. */
  15175. UE.plugins['enterkey'] = function() {
  15176. var hTag,
  15177. me = this,
  15178. tag = me.options.enterTag;
  15179. me.addListener('keyup', function(type, evt) {
  15180. var keyCode = evt.keyCode || evt.which;
  15181. if (keyCode == 13) {
  15182. var range = me.selection.getRange(),
  15183. start = range.startContainer,
  15184. doSave;
  15185. //修正在h1-h6里边回车后不能嵌套p的问题
  15186. if (!browser.ie) {
  15187. if (/h\d/i.test(hTag)) {
  15188. if (browser.gecko) {
  15189. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15190. if (!h) {
  15191. me.document.execCommand('formatBlock', false, '<p>');
  15192. doSave = 1;
  15193. }
  15194. } else {
  15195. //chrome remove div
  15196. if (start.nodeType == 1) {
  15197. var tmp = me.document.createTextNode(''),div;
  15198. range.insertNode(tmp);
  15199. div = domUtils.findParentByTagName(tmp, 'div', true);
  15200. if (div) {
  15201. var p = me.document.createElement('p');
  15202. while (div.firstChild) {
  15203. p.appendChild(div.firstChild);
  15204. }
  15205. div.parentNode.insertBefore(p, div);
  15206. domUtils.remove(div);
  15207. range.setStartBefore(tmp).setCursor();
  15208. doSave = 1;
  15209. }
  15210. domUtils.remove(tmp);
  15211. }
  15212. }
  15213. if (me.undoManger && doSave) {
  15214. me.undoManger.save();
  15215. }
  15216. }
  15217. //没有站位符,会出现多行的问题
  15218. browser.opera && range.select();
  15219. }else{
  15220. me.fireEvent('saveScene',true,true)
  15221. }
  15222. }
  15223. });
  15224. me.addListener('keydown', function(type, evt) {
  15225. var keyCode = evt.keyCode || evt.which;
  15226. if (keyCode == 13) {//回车
  15227. if(me.fireEvent('beforeenterkeydown')){
  15228. domUtils.preventDefault(evt);
  15229. return;
  15230. }
  15231. me.fireEvent('saveScene',true,true);
  15232. hTag = '';
  15233. var range = me.selection.getRange();
  15234. if (!range.collapsed) {
  15235. //跨td不能删
  15236. var start = range.startContainer,
  15237. end = range.endContainer,
  15238. startTd = domUtils.findParentByTagName(start, 'td', true),
  15239. endTd = domUtils.findParentByTagName(end, 'td', true);
  15240. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15241. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15242. return;
  15243. }
  15244. }
  15245. if (tag == 'p') {
  15246. if (!browser.ie) {
  15247. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15248. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15249. //trace:2431
  15250. if (!start && !browser.opera) {
  15251. me.document.execCommand('formatBlock', false, '<p>');
  15252. if (browser.gecko) {
  15253. range = me.selection.getRange();
  15254. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15255. start && domUtils.removeDirtyAttr(start);
  15256. }
  15257. } else {
  15258. hTag = start.tagName;
  15259. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15260. }
  15261. }
  15262. } else {
  15263. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15264. if (!range.collapsed) {
  15265. range.deleteContents();
  15266. start = range.startContainer;
  15267. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15268. while (start.nodeType == 1) {
  15269. if (dtd.$empty[start.tagName]) {
  15270. range.setStartBefore(start).setCursor();
  15271. if (me.undoManger) {
  15272. me.undoManger.save();
  15273. }
  15274. return false;
  15275. }
  15276. if (!start.firstChild) {
  15277. var br = range.document.createElement('br');
  15278. start.appendChild(br);
  15279. range.setStart(start, 0).setCursor();
  15280. if (me.undoManger) {
  15281. me.undoManger.save();
  15282. }
  15283. return false;
  15284. }
  15285. start = start.firstChild;
  15286. }
  15287. if (start === range.startContainer.childNodes[range.startOffset]) {
  15288. br = range.document.createElement('br');
  15289. range.insertNode(br).setCursor();
  15290. } else {
  15291. range.setStart(start, 0).setCursor();
  15292. }
  15293. } else {
  15294. br = range.document.createElement('br');
  15295. range.insertNode(br).setStartAfter(br).setCursor();
  15296. }
  15297. } else {
  15298. br = range.document.createElement('br');
  15299. range.insertNode(br);
  15300. var parent = br.parentNode;
  15301. if (parent.lastChild === br) {
  15302. br.parentNode.insertBefore(br.cloneNode(true), br);
  15303. range.setStartBefore(br);
  15304. } else {
  15305. range.setStartAfter(br);
  15306. }
  15307. range.setCursor();
  15308. }
  15309. }
  15310. }
  15311. });
  15312. };
  15313. // plugins/keystrokes.js
  15314. /* 处理特殊键的兼容性问题 */
  15315. UE.plugins['keystrokes'] = function() {
  15316. var me = this;
  15317. var collapsed = true;
  15318. me.addListener('keydown', function(type, evt) {
  15319. var keyCode = evt.keyCode || evt.which,
  15320. rng = me.selection.getRange();
  15321. //处理全选的情况
  15322. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15323. || keyCode >= 48 && keyCode <= 57 ||
  15324. keyCode >= 96 && keyCode <= 111 || {
  15325. 13:1,
  15326. 8:1,
  15327. 46:1
  15328. }[keyCode])
  15329. ){
  15330. var tmpNode = rng.startContainer;
  15331. if(domUtils.isFillChar(tmpNode)){
  15332. rng.setStartBefore(tmpNode)
  15333. }
  15334. tmpNode = rng.endContainer;
  15335. if(domUtils.isFillChar(tmpNode)){
  15336. rng.setEndAfter(tmpNode)
  15337. }
  15338. rng.txtToElmBoundary();
  15339. //结束边界可能放到了br的前边,要把br包含进来
  15340. // x[xxx]<br/>
  15341. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15342. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15343. if(tmpNode && domUtils.isBr(tmpNode)){
  15344. rng.setEndAfter(tmpNode);
  15345. }
  15346. }
  15347. if(rng.startOffset == 0){
  15348. tmpNode = rng.startContainer;
  15349. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15350. tmpNode = rng.endContainer;
  15351. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15352. me.fireEvent('saveScene');
  15353. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15354. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15355. me._selectionChange();
  15356. return;
  15357. }
  15358. }
  15359. }
  15360. }
  15361. //处理backspace
  15362. if (keyCode == keymap.Backspace) {
  15363. rng = me.selection.getRange();
  15364. collapsed = rng.collapsed;
  15365. if(me.fireEvent('delkeydown',evt)){
  15366. return;
  15367. }
  15368. var start,end;
  15369. //避免按两次删除才能生效的问题
  15370. if(rng.collapsed && rng.inFillChar()){
  15371. start = rng.startContainer;
  15372. if(domUtils.isFillChar(start)){
  15373. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15374. domUtils.remove(start)
  15375. }else{
  15376. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15377. rng.startOffset--;
  15378. rng.collapse(true).select(true)
  15379. }
  15380. }
  15381. //解决选中control元素不能删除的问题
  15382. if (start = rng.getClosedNode()) {
  15383. me.fireEvent('saveScene');
  15384. rng.setStartBefore(start);
  15385. domUtils.remove(start);
  15386. rng.setCursor();
  15387. me.fireEvent('saveScene');
  15388. domUtils.preventDefault(evt);
  15389. return;
  15390. }
  15391. //阻止在table上的删除
  15392. if (!browser.ie) {
  15393. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15394. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15395. if (start && !end || !start && end || start !== end) {
  15396. evt.preventDefault();
  15397. return;
  15398. }
  15399. }
  15400. }
  15401. //处理tab键的逻辑
  15402. if (keyCode == keymap.Tab) {
  15403. //不处理以下标签
  15404. var excludeTagNameForTabKey = {
  15405. 'ol' : 1,
  15406. 'ul' : 1,
  15407. 'table':1
  15408. };
  15409. //处理组件里的tab按下事件
  15410. if(me.fireEvent('tabkeydown',evt)){
  15411. domUtils.preventDefault(evt);
  15412. return;
  15413. }
  15414. var range = me.selection.getRange();
  15415. me.fireEvent('saveScene');
  15416. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15417. txt += tabNode;
  15418. }
  15419. var span = me.document.createElement('span');
  15420. span.innerHTML = txt + domUtils.fillChar;
  15421. if (range.collapsed) {
  15422. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15423. } else {
  15424. var filterFn = function(node) {
  15425. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15426. };
  15427. //普通的情况
  15428. start = domUtils.findParent(range.startContainer, filterFn,true);
  15429. end = domUtils.findParent(range.endContainer, filterFn,true);
  15430. if (start && end && start === end) {
  15431. range.deleteContents();
  15432. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15433. } else {
  15434. var bookmark = range.createBookmark();
  15435. range.enlarge(true);
  15436. var bookmark2 = range.createBookmark(),
  15437. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15438. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15439. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15440. current = domUtils.getNextDomNode(current, false, filterFn);
  15441. }
  15442. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15443. }
  15444. }
  15445. domUtils.preventDefault(evt)
  15446. }
  15447. //trace:1634
  15448. //ff的del键在容器空的时候,也会删除
  15449. if(browser.gecko && keyCode == 46){
  15450. range = me.selection.getRange();
  15451. if(range.collapsed){
  15452. start = range.startContainer;
  15453. if(domUtils.isEmptyBlock(start)){
  15454. var parent = start.parentNode;
  15455. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15456. start = parent;
  15457. parent = parent.parentNode;
  15458. }
  15459. if(start === parent.lastChild)
  15460. evt.preventDefault();
  15461. return;
  15462. }
  15463. }
  15464. }
  15465. });
  15466. me.addListener('keyup', function(type, evt) {
  15467. var keyCode = evt.keyCode || evt.which,
  15468. rng,me = this;
  15469. if(keyCode == keymap.Backspace){
  15470. if(me.fireEvent('delkeyup')){
  15471. return;
  15472. }
  15473. rng = me.selection.getRange();
  15474. if(rng.collapsed){
  15475. var tmpNode,
  15476. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15477. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15478. if(domUtils.isEmptyBlock(tmpNode)){
  15479. var pre = tmpNode.previousSibling;
  15480. if(pre && pre.nodeName != 'TABLE'){
  15481. domUtils.remove(tmpNode);
  15482. rng.setStartAtLast(pre).setCursor(false,true);
  15483. return;
  15484. }else{
  15485. var next = tmpNode.nextSibling;
  15486. if(next && next.nodeName != 'TABLE'){
  15487. domUtils.remove(tmpNode);
  15488. rng.setStartAtFirst(next).setCursor(false,true);
  15489. return;
  15490. }
  15491. }
  15492. }
  15493. }
  15494. //处理当删除到body时,要重新给p标签展位
  15495. if(domUtils.isBody(rng.startContainer)){
  15496. var tmpNode = domUtils.createElement(me.document,'p',{
  15497. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15498. });
  15499. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15500. }
  15501. }
  15502. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15503. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15504. if(browser.ie){
  15505. var span = rng.document.createElement('span');
  15506. rng.insertNode(span).setStartBefore(span).collapse(true);
  15507. rng.select();
  15508. domUtils.remove(span)
  15509. }else{
  15510. rng.select()
  15511. }
  15512. }
  15513. }
  15514. })
  15515. };
  15516. // plugins/fiximgclick.js
  15517. ///import core
  15518. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15519. ///commandsName FixImgClick
  15520. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15521. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15522. UE.plugins['fiximgclick'] = (function () {
  15523. var elementUpdated = false;
  15524. function Scale() {
  15525. this.editor = null;
  15526. this.resizer = null;
  15527. this.cover = null;
  15528. this.doc = document;
  15529. this.prePos = {x: 0, y: 0};
  15530. this.startPos = {x: 0, y: 0};
  15531. }
  15532. (function () {
  15533. var rect = [
  15534. //[left, top, width, height]
  15535. [0, 0, -1, -1],
  15536. [0, 0, 0, -1],
  15537. [0, 0, 1, -1],
  15538. [0, 0, -1, 0],
  15539. [0, 0, 1, 0],
  15540. [0, 0, -1, 1],
  15541. [0, 0, 0, 1],
  15542. [0, 0, 1, 1]
  15543. ];
  15544. Scale.prototype = {
  15545. init: function (editor) {
  15546. var me = this;
  15547. me.editor = editor;
  15548. me.startPos = this.prePos = {x: 0, y: 0};
  15549. me.dragId = -1;
  15550. var hands = [],
  15551. cover = me.cover = document.createElement('div'),
  15552. resizer = me.resizer = document.createElement('div');
  15553. cover.id = me.editor.ui.id + '_imagescale_cover';
  15554. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15555. domUtils.on(cover, 'mousedown click', function () {
  15556. me.hide();
  15557. });
  15558. for (i = 0; i < 8; i++) {
  15559. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15560. }
  15561. resizer.id = me.editor.ui.id + '_imagescale';
  15562. resizer.className = 'edui-editor-imagescale';
  15563. resizer.innerHTML = hands.join('');
  15564. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15565. me.editor.ui.getDom().appendChild(cover);
  15566. me.editor.ui.getDom().appendChild(resizer);
  15567. me.initStyle();
  15568. me.initEvents();
  15569. },
  15570. initStyle: function () {
  15571. 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;}' +
  15572. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15573. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15574. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15575. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15576. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15577. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15578. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15579. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15580. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15581. },
  15582. initEvents: function () {
  15583. var me = this;
  15584. me.startPos.x = me.startPos.y = 0;
  15585. me.isDraging = false;
  15586. },
  15587. _eventHandler: function (e) {
  15588. var me = this;
  15589. switch (e.type) {
  15590. case 'mousedown':
  15591. var hand = e.target || e.srcElement, hand;
  15592. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15593. me.dragId = hand.className.slice(-1);
  15594. me.startPos.x = me.prePos.x = e.clientX;
  15595. me.startPos.y = me.prePos.y = e.clientY;
  15596. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15597. }
  15598. break;
  15599. case 'mousemove':
  15600. if (me.dragId != -1) {
  15601. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15602. me.prePos.x = e.clientX;
  15603. me.prePos.y = e.clientY;
  15604. elementUpdated = true;
  15605. me.updateTargetElement();
  15606. }
  15607. break;
  15608. case 'mouseup':
  15609. if (me.dragId != -1) {
  15610. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15611. me.updateTargetElement();
  15612. if (me.target.parentNode) me.attachTo(me.target);
  15613. me.dragId = -1;
  15614. }
  15615. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15616. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15617. if(elementUpdated){
  15618. elementUpdated = false;
  15619. me.editor.fireEvent('contentchange');
  15620. }
  15621. break;
  15622. default:
  15623. break;
  15624. }
  15625. },
  15626. updateTargetElement: function () {
  15627. var me = this;
  15628. domUtils.setStyles(me.target, {
  15629. 'width': me.resizer.style.width,
  15630. 'height': me.resizer.style.height
  15631. });
  15632. me.target.width = parseInt(me.resizer.style.width);
  15633. me.target.height = parseInt(me.resizer.style.height);
  15634. me.attachTo(me.target);
  15635. },
  15636. updateContainerStyle: function (dir, offset) {
  15637. var me = this,
  15638. dom = me.resizer, tmp;
  15639. if (rect[dir][0] != 0) {
  15640. tmp = parseInt(dom.style.left) + offset.x;
  15641. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15642. }
  15643. if (rect[dir][1] != 0) {
  15644. tmp = parseInt(dom.style.top) + offset.y;
  15645. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15646. }
  15647. if (rect[dir][2] != 0) {
  15648. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15649. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15650. }
  15651. if (rect[dir][3] != 0) {
  15652. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15653. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15654. }
  15655. },
  15656. _validScaledProp: function (prop, value) {
  15657. var ele = this.resizer,
  15658. wrap = document;
  15659. value = isNaN(value) ? 0 : value;
  15660. switch (prop) {
  15661. case 'left':
  15662. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15663. case 'top':
  15664. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15665. case 'width':
  15666. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15667. case 'height':
  15668. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15669. }
  15670. },
  15671. hideCover: function () {
  15672. this.cover.style.display = 'none';
  15673. },
  15674. showCover: function () {
  15675. var me = this,
  15676. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15677. iframePos = domUtils.getXY(me.editor.iframe);
  15678. domUtils.setStyles(me.cover, {
  15679. 'width': me.editor.iframe.offsetWidth + 'px',
  15680. 'height': me.editor.iframe.offsetHeight + 'px',
  15681. 'top': iframePos.y - editorPos.y + 'px',
  15682. 'left': iframePos.x - editorPos.x + 'px',
  15683. 'position': 'absolute',
  15684. 'display': ''
  15685. })
  15686. },
  15687. show: function (targetObj) {
  15688. var me = this;
  15689. me.resizer.style.display = 'block';
  15690. if(targetObj) me.attachTo(targetObj);
  15691. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15692. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15693. me.showCover();
  15694. me.editor.fireEvent('afterscaleshow', me);
  15695. me.editor.fireEvent('saveScene');
  15696. },
  15697. hide: function () {
  15698. var me = this;
  15699. me.hideCover();
  15700. me.resizer.style.display = 'none';
  15701. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15702. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15703. me.editor.fireEvent('afterscalehide', me);
  15704. },
  15705. proxy: function( fn, context ) {
  15706. return function(e) {
  15707. return fn.apply( context || this, arguments);
  15708. };
  15709. },
  15710. attachTo: function (targetObj) {
  15711. var me = this,
  15712. target = me.target = targetObj,
  15713. resizer = this.resizer,
  15714. imgPos = domUtils.getXY(target),
  15715. iframePos = domUtils.getXY(me.editor.iframe),
  15716. editorPos = domUtils.getXY(resizer.parentNode);
  15717. domUtils.setStyles(resizer, {
  15718. 'width': target.width + 'px',
  15719. 'height': target.height + 'px',
  15720. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15721. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15722. });
  15723. }
  15724. }
  15725. })();
  15726. return function () {
  15727. var me = this,
  15728. imageScale;
  15729. me.setOpt('imageScaleEnabled', true);
  15730. if ( !browser.ie && me.options.imageScaleEnabled) {
  15731. me.addListener('click', function (type, e) {
  15732. var range = me.selection.getRange(),
  15733. img = range.getClosedNode();
  15734. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15735. if (img.className.indexOf("edui-faked-music") != -1 ||
  15736. img.getAttribute("anchorname") ||
  15737. domUtils.hasClass(img, 'loadingclass') ||
  15738. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15739. if (!imageScale) {
  15740. imageScale = new Scale();
  15741. imageScale.init(me);
  15742. me.ui.getDom().appendChild(imageScale.resizer);
  15743. var _keyDownHandler = function (e) {
  15744. imageScale.hide();
  15745. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15746. }, _mouseDownHandler = function (e) {
  15747. var ele = e.target || e.srcElement;
  15748. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15749. _keyDownHandler(e);
  15750. }
  15751. }, timer;
  15752. me.addListener('afterscaleshow', function (e) {
  15753. me.addListener('beforekeydown', _keyDownHandler);
  15754. me.addListener('beforemousedown', _mouseDownHandler);
  15755. domUtils.on(document, 'keydown', _keyDownHandler);
  15756. domUtils.on(document,'mousedown', _mouseDownHandler);
  15757. me.selection.getNative().removeAllRanges();
  15758. });
  15759. me.addListener('afterscalehide', function (e) {
  15760. me.removeListener('beforekeydown', _keyDownHandler);
  15761. me.removeListener('beforemousedown', _mouseDownHandler);
  15762. domUtils.un(document, 'keydown', _keyDownHandler);
  15763. domUtils.un(document,'mousedown', _mouseDownHandler);
  15764. var target = imageScale.target;
  15765. if (target.parentNode) {
  15766. me.selection.getRange().selectNode(target).select();
  15767. }
  15768. });
  15769. //TODO 有iframe的情况,mousedown不能往下传。。
  15770. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15771. me.selection.getNative().removeAllRanges();
  15772. var ele = e.target || e.srcElement;
  15773. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15774. timer = setTimeout(function () {
  15775. imageScale.hide();
  15776. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15777. }, 200);
  15778. }
  15779. });
  15780. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15781. var ele = e.target || e.srcElement;
  15782. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15783. clearTimeout(timer);
  15784. }
  15785. });
  15786. }
  15787. imageScale.show(img);
  15788. } else {
  15789. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15790. }
  15791. });
  15792. }
  15793. if (browser.webkit) {
  15794. me.addListener('click', function (type, e) {
  15795. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15796. var range = new dom.Range(me.document);
  15797. range.selectNode(e.target).select();
  15798. }
  15799. });
  15800. }
  15801. }
  15802. })();
  15803. // plugins/autolink.js
  15804. ///import core
  15805. ///commands 为非ie浏览器自动添加a标签
  15806. ///commandsName AutoLink
  15807. ///commandsTitle 自动增加链接
  15808. /**
  15809. * @description 为非ie浏览器自动添加a标签
  15810. * @author zhanyi
  15811. */
  15812. UE.plugin.register('autolink',function(){
  15813. var cont = 0;
  15814. return !browser.ie ? {
  15815. bindEvents:{
  15816. 'reset' : function(){
  15817. cont = 0;
  15818. },
  15819. 'keydown':function(type, evt) {
  15820. var me = this;
  15821. var keyCode = evt.keyCode || evt.which;
  15822. if (keyCode == 32 || keyCode == 13) {
  15823. var sel = me.selection.getNative(),
  15824. range = sel.getRangeAt(0).cloneRange(),
  15825. offset,
  15826. charCode;
  15827. var start = range.startContainer;
  15828. while (start.nodeType == 1 && range.startOffset > 0) {
  15829. start = range.startContainer.childNodes[range.startOffset - 1];
  15830. if (!start){
  15831. break;
  15832. }
  15833. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15834. range.collapse(true);
  15835. start = range.startContainer;
  15836. }
  15837. do{
  15838. if (range.startOffset == 0) {
  15839. start = range.startContainer.previousSibling;
  15840. while (start && start.nodeType == 1) {
  15841. start = start.lastChild;
  15842. }
  15843. if (!start || domUtils.isFillChar(start)){
  15844. break;
  15845. }
  15846. offset = start.nodeValue.length;
  15847. } else {
  15848. start = range.startContainer;
  15849. offset = range.startOffset;
  15850. }
  15851. range.setStart(start, offset - 1);
  15852. charCode = range.toString().charCodeAt(0);
  15853. } while (charCode != 160 && charCode != 32);
  15854. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15855. while(range.toString().length){
  15856. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15857. break;
  15858. }
  15859. try{
  15860. range.setStart(range.startContainer,range.startOffset+1);
  15861. }catch(e){
  15862. //trace:2121
  15863. var start = range.startContainer;
  15864. while(!(next = start.nextSibling)){
  15865. if(domUtils.isBody(start)){
  15866. return;
  15867. }
  15868. start = start.parentNode;
  15869. }
  15870. range.setStart(next,0);
  15871. }
  15872. }
  15873. //range的开始边界已经在a标签里的不再处理
  15874. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15875. return;
  15876. }
  15877. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15878. me.undoManger && me.undoManger.save();
  15879. a.appendChild(range.extractContents());
  15880. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15881. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15882. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15883. a.setAttribute('_src',utils.html(href));
  15884. a.href = utils.html(href);
  15885. range.insertNode(a);
  15886. a.parentNode.insertBefore(text, a.nextSibling);
  15887. range.setStart(text, 0);
  15888. range.collapse(true);
  15889. sel.removeAllRanges();
  15890. sel.addRange(range);
  15891. me.undoManger && me.undoManger.save();
  15892. }
  15893. }
  15894. }
  15895. }
  15896. }:{}
  15897. },function(){
  15898. var keyCodes = {
  15899. 37:1, 38:1, 39:1, 40:1,
  15900. 13:1,32:1
  15901. };
  15902. function checkIsCludeLink(node){
  15903. if(node.nodeType == 3){
  15904. return null
  15905. }
  15906. if(node.nodeName == 'A'){
  15907. return node;
  15908. }
  15909. var lastChild = node.lastChild;
  15910. while(lastChild){
  15911. if(lastChild.nodeName == 'A'){
  15912. return lastChild;
  15913. }
  15914. if(lastChild.nodeType == 3){
  15915. if(domUtils.isWhitespace(lastChild)){
  15916. lastChild = lastChild.previousSibling;
  15917. continue;
  15918. }
  15919. return null
  15920. }
  15921. lastChild = lastChild.lastChild;
  15922. }
  15923. }
  15924. browser.ie && this.addListener('keyup',function(cmd,evt){
  15925. var me = this,keyCode = evt.keyCode;
  15926. if(keyCodes[keyCode]){
  15927. var rng = me.selection.getRange();
  15928. var start = rng.startContainer;
  15929. if(keyCode == 13){
  15930. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15931. start = start.parentNode;
  15932. }
  15933. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15934. var pre = start.previousSibling;
  15935. if(pre && pre.nodeType == 1){
  15936. var pre = checkIsCludeLink(pre);
  15937. if(pre && !pre.getAttribute('_href')){
  15938. domUtils.remove(pre,true);
  15939. }
  15940. }
  15941. }
  15942. }else if(keyCode == 32 ){
  15943. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15944. start = start.previousSibling;
  15945. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15946. domUtils.remove(start,true);
  15947. }
  15948. }
  15949. }else {
  15950. start = domUtils.findParentByTagName(start,'a',true);
  15951. if(start && !start.getAttribute('_href')){
  15952. var bk = rng.createBookmark();
  15953. domUtils.remove(start,true);
  15954. rng.moveToBookmark(bk).select(true)
  15955. }
  15956. }
  15957. }
  15958. });
  15959. }
  15960. );
  15961. // plugins/autoheight.js
  15962. ///import core
  15963. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  15964. ///commandsName AutoHeight,autoHeightEnabled
  15965. ///commandsTitle 自动增高
  15966. /**
  15967. * @description 自动伸展
  15968. * @author zhanyi
  15969. */
  15970. UE.plugins['autoheight'] = function () {
  15971. var me = this;
  15972. //提供开关,就算加载也可以关闭
  15973. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  15974. if (!me.autoHeightEnabled) {
  15975. return;
  15976. }
  15977. var bakOverflow,
  15978. lastHeight = 0,
  15979. options = me.options,
  15980. currentHeight,
  15981. timer;
  15982. function adjustHeight() {
  15983. var me = this;
  15984. clearTimeout(timer);
  15985. if(isFullscreen)return;
  15986. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  15987. timer = setTimeout(function(){
  15988. var node = me.body.lastChild;
  15989. while(node && node.nodeType != 1){
  15990. node = node.previousSibling;
  15991. }
  15992. if(node && node.nodeType == 1){
  15993. node.style.clear = 'both';
  15994. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  15995. if (currentHeight != lastHeight) {
  15996. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  15997. me.iframe.parentNode.style.height = currentHeight + 'px';
  15998. }
  15999. me.body.style.height = currentHeight + 'px';
  16000. lastHeight = currentHeight;
  16001. }
  16002. domUtils.removeStyle(node,'clear');
  16003. }
  16004. },50)
  16005. }
  16006. }
  16007. var isFullscreen;
  16008. me.addListener('fullscreenchanged',function(cmd,f){
  16009. isFullscreen = f
  16010. });
  16011. me.addListener('destroy', function () {
  16012. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  16013. });
  16014. me.enableAutoHeight = function () {
  16015. var me = this;
  16016. if (!me.autoHeightEnabled) {
  16017. return;
  16018. }
  16019. var doc = me.document;
  16020. me.autoHeightEnabled = true;
  16021. bakOverflow = doc.body.style.overflowY;
  16022. doc.body.style.overflowY = 'hidden';
  16023. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16024. //ff不给事件算得不对
  16025. setTimeout(function () {
  16026. adjustHeight.call(me);
  16027. }, browser.gecko ? 100 : 0);
  16028. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16029. };
  16030. me.disableAutoHeight = function () {
  16031. me.body.style.overflowY = bakOverflow || '';
  16032. me.removeListener('contentchange', adjustHeight);
  16033. me.removeListener('keyup', adjustHeight);
  16034. me.removeListener('mouseup', adjustHeight);
  16035. me.autoHeightEnabled = false;
  16036. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16037. };
  16038. me.on('setHeight',function(){
  16039. me.disableAutoHeight()
  16040. });
  16041. me.addListener('ready', function () {
  16042. me.enableAutoHeight();
  16043. //trace:1764
  16044. var timer;
  16045. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16046. clearTimeout(timer);
  16047. timer = setTimeout(function () {
  16048. //trace:3681
  16049. adjustHeight.call(me);
  16050. }, 100);
  16051. });
  16052. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16053. var lastScrollY;
  16054. window.onscroll = function(){
  16055. if(lastScrollY === null){
  16056. lastScrollY = this.scrollY
  16057. }else if(this.scrollY == 0 && lastScrollY != 0){
  16058. me.window.scrollTo(0,0);
  16059. lastScrollY = null;
  16060. }
  16061. }
  16062. });
  16063. };
  16064. // plugins/autofloat.js
  16065. ///import core
  16066. ///commands 悬浮工具栏
  16067. ///commandsName AutoFloat,autoFloatEnabled
  16068. ///commandsTitle 悬浮工具栏
  16069. /**
  16070. * modified by chengchao01
  16071. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16072. */
  16073. UE.plugins['autofloat'] = function() {
  16074. var me = this,
  16075. lang = me.getLang();
  16076. me.setOpt({
  16077. topOffset:0
  16078. });
  16079. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16080. topOffset = me.options.topOffset;
  16081. //如果不固定toolbar的位置,则直接退出
  16082. if(!optsAutoFloatEnabled){
  16083. return;
  16084. }
  16085. var uiUtils = UE.ui.uiUtils,
  16086. LteIE6 = browser.ie && browser.version <= 6,
  16087. quirks = browser.quirks;
  16088. function checkHasUI(){
  16089. if(!UE.ui){
  16090. alert(lang.autofloatMsg);
  16091. return 0;
  16092. }
  16093. return 1;
  16094. }
  16095. function fixIE6FixedPos(){
  16096. var docStyle = document.body.style;
  16097. docStyle.backgroundImage = 'url("about:blank")';
  16098. docStyle.backgroundAttachment = 'fixed';
  16099. }
  16100. var bakCssText,
  16101. placeHolder = document.createElement('div'),
  16102. toolbarBox,orgTop,
  16103. getPosition,
  16104. flag =true; //ie7模式下需要偏移
  16105. function setFloating(){
  16106. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16107. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16108. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16109. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16110. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16111. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16112. if (LteIE6 || (quirks && browser.ie)) {
  16113. if(toolbarBox.style.position != 'absolute'){
  16114. toolbarBox.style.position = 'absolute';
  16115. }
  16116. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16117. } else {
  16118. if (browser.ie7Compat && flag) {
  16119. flag = false;
  16120. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16121. }
  16122. if(toolbarBox.style.position != 'fixed'){
  16123. toolbarBox.style.position = 'fixed';
  16124. toolbarBox.style.top = topOffset +"px";
  16125. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16126. }
  16127. }
  16128. }
  16129. function unsetFloating(){
  16130. flag = true;
  16131. if(placeHolder.parentNode){
  16132. placeHolder.parentNode.removeChild(placeHolder);
  16133. }
  16134. toolbarBox.style.cssText = bakCssText;
  16135. }
  16136. function updateFloating(){
  16137. var rect3 = getPosition(me.container);
  16138. var offset=me.options.toolbarTopOffset||0;
  16139. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16140. setFloating();
  16141. }else{
  16142. unsetFloating();
  16143. }
  16144. }
  16145. var defer_updateFloating = utils.defer(function(){
  16146. updateFloating();
  16147. },browser.ie ? 200 : 100,true);
  16148. me.addListener('destroy',function(){
  16149. domUtils.un(window, ['scroll','resize'], updateFloating);
  16150. me.removeListener('keydown', defer_updateFloating);
  16151. });
  16152. me.addListener('ready', function(){
  16153. if(checkHasUI(me)){
  16154. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16155. if(!me.ui){
  16156. return;
  16157. }
  16158. getPosition = uiUtils.getClientRect;
  16159. toolbarBox = me.ui.getDom('toolbarbox');
  16160. orgTop = getPosition(toolbarBox).top;
  16161. bakCssText = toolbarBox.style.cssText;
  16162. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16163. if(LteIE6){
  16164. fixIE6FixedPos();
  16165. }
  16166. domUtils.on(window, ['scroll','resize'], updateFloating);
  16167. me.addListener('keydown', defer_updateFloating);
  16168. me.addListener('beforefullscreenchange', function (t, enabled){
  16169. if (enabled) {
  16170. unsetFloating();
  16171. }
  16172. });
  16173. me.addListener('fullscreenchanged', function (t, enabled){
  16174. if (!enabled) {
  16175. updateFloating();
  16176. }
  16177. });
  16178. me.addListener('sourcemodechanged', function (t, enabled){
  16179. setTimeout(function (){
  16180. updateFloating();
  16181. },0);
  16182. });
  16183. me.addListener("clearDoc",function(){
  16184. setTimeout(function(){
  16185. updateFloating();
  16186. },0);
  16187. })
  16188. }
  16189. });
  16190. };
  16191. // plugins/video.js
  16192. /**
  16193. * video插件, 为UEditor提供视频插入支持
  16194. * @file
  16195. * @since 1.2.6.1
  16196. */
  16197. UE.plugins['video'] = function (){
  16198. var me =this;
  16199. /**
  16200. * 创建插入视频字符窜
  16201. * @param url 视频地址
  16202. * @param width 视频宽度
  16203. * @param height 视频高度
  16204. * @param align 视频对齐
  16205. * @param toEmbed 是否以flash代替显示
  16206. * @param addParagraph 是否需要添加P 标签
  16207. */
  16208. function creatInsertStr(url,width,height,id,align,classname,type,poster){
  16209. var str;
  16210. switch (type){
  16211. case 'image':
  16212. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16213. ' 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 + ';': '')+'" />'
  16214. break;
  16215. case 'embed':
  16216. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16217. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16218. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16219. break;
  16220. case 'video':
  16221. var ext = url.substr(url.lastIndexOf('.') + 1);
  16222. if(ext == 'ogv') ext = 'ogg';
  16223. str = '<video' + (id ? ' id="' + id + '"' : '') + ' poster="'+poster+'" class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16224. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16225. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16226. break;
  16227. }
  16228. return str;
  16229. }
  16230. function switchImgAndVideo(root,img2video){
  16231. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16232. var className = node.getAttr('class');
  16233. if(className && className.indexOf('edui-faked-video') != -1){
  16234. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16235. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16236. }
  16237. if(className && className.indexOf('edui-upload-video') != -1){
  16238. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16239. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16240. }
  16241. })
  16242. }
  16243. me.addOutputRule(function(root){
  16244. //switchImgAndVideo(root,true)
  16245. });
  16246. me.addInputRule(function(root){
  16247. // switchImgAndVideo(root)
  16248. });
  16249. /**
  16250. * 插入视频
  16251. * @command insertvideo
  16252. * @method execCommand
  16253. * @param { String } cmd 命令字符串
  16254. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16255. * @example
  16256. * ```javascript
  16257. *
  16258. * var videoAttr = {
  16259. * //视频地址
  16260. * url: 'http://www.youku.com/xxx',
  16261. * //视频宽高值, 单位px
  16262. * width: 200,
  16263. * height: 100
  16264. * };
  16265. *
  16266. * //editor 是编辑器实例
  16267. * //向编辑器插入单个视频
  16268. * editor.execCommand( 'insertvideo', videoAttr );
  16269. * ```
  16270. */
  16271. /**
  16272. * 插入视频
  16273. * @command insertvideo
  16274. * @method execCommand
  16275. * @param { String } cmd 命令字符串
  16276. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16277. * @example
  16278. * ```javascript
  16279. *
  16280. * var videoAttr1 = {
  16281. * //视频地址
  16282. * url: 'http://www.youku.com/xxx',
  16283. * //视频宽高值, 单位px
  16284. * width: 200,
  16285. * height: 100
  16286. * },
  16287. * videoAttr2 = {
  16288. * //视频地址
  16289. * url: 'http://www.youku.com/xxx',
  16290. * //视频宽高值, 单位px
  16291. * width: 200,
  16292. * height: 100
  16293. * }
  16294. *
  16295. * //editor 是编辑器实例
  16296. * //该方法将会向编辑器内插入两个视频
  16297. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16298. * ```
  16299. */
  16300. /**
  16301. * 查询当前光标所在处是否是一个视频
  16302. * @command insertvideo
  16303. * @method queryCommandState
  16304. * @param { String } cmd 需要查询的命令字符串
  16305. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16306. * @example
  16307. * ```javascript
  16308. *
  16309. * //editor 是编辑器实例
  16310. * editor.queryCommandState( 'insertvideo' );
  16311. * ```
  16312. */
  16313. me.commands["insertvideo"] = {
  16314. execCommand: function (cmd, videoObjs, type){
  16315. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16316. var html = [],id = 'tmpVedio', cl;
  16317. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16318. vi = videoObjs[i];
  16319. //console.log(vi);
  16320. //console.log($("#titlepicurl").val());
  16321. $("#titlepicurl").val(vi.urlImg);
  16322. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16323. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'video',vi.urlImg));
  16324. }
  16325. me.execCommand("inserthtml",html.join(""),true);
  16326. var rng = this.selection.getRange();
  16327. for(var i= 0,len=videoObjs.length;i<len;i++){
  16328. var img = this.document.getElementById('tmpVedio'+i);
  16329. domUtils.removeAttributes(img,'id');
  16330. rng.selectNode(img).select();
  16331. me.execCommand('imagefloat',videoObjs[i].align)
  16332. }
  16333. },
  16334. queryCommandState : function(){
  16335. var img = me.selection.getRange().getClosedNode(),
  16336. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16337. return flag ? 1 : 0;
  16338. }
  16339. };
  16340. };
  16341. // plugins/table.core.js
  16342. /**
  16343. * Created with JetBrains WebStorm.
  16344. * User: taoqili
  16345. * Date: 13-1-18
  16346. * Time: 上午11:09
  16347. * To change this template use File | Settings | File Templates.
  16348. */
  16349. /**
  16350. * UE表格操作类
  16351. * @param table
  16352. * @constructor
  16353. */
  16354. (function () {
  16355. var UETable = UE.UETable = function (table) {
  16356. this.table = table;
  16357. this.indexTable = [];
  16358. this.selectedTds = [];
  16359. this.cellsRange = {};
  16360. this.update(table);
  16361. };
  16362. //===以下为静态工具方法===
  16363. UETable.removeSelectedClass = function (cells) {
  16364. utils.each(cells, function (cell) {
  16365. domUtils.removeClasses(cell, "selectTdClass");
  16366. })
  16367. };
  16368. UETable.addSelectedClass = function (cells) {
  16369. utils.each(cells, function (cell) {
  16370. domUtils.addClass(cell, "selectTdClass");
  16371. })
  16372. };
  16373. UETable.isEmptyBlock = function (node) {
  16374. var reg = new RegExp(domUtils.fillChar, 'g');
  16375. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16376. return 0;
  16377. }
  16378. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16379. if (node.getElementsByTagName(i).length) {
  16380. return 0;
  16381. }
  16382. }
  16383. return 1;
  16384. };
  16385. UETable.getWidth = function (cell) {
  16386. if (!cell)return 0;
  16387. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16388. };
  16389. /**
  16390. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16391. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16392. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16393. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16394. */
  16395. UETable.getTableCellAlignState = function ( cells ) {
  16396. !utils.isArray( cells ) && ( cells = [cells] );
  16397. var result = {},
  16398. status = ['align', 'valign'],
  16399. tempStatus = null,
  16400. isSame = true;//状态是否相同
  16401. utils.each( cells, function( cellNode ){
  16402. utils.each( status, function( currentState ){
  16403. tempStatus = cellNode.getAttribute( currentState );
  16404. if( !result[ currentState ] && tempStatus ) {
  16405. result[ currentState ] = tempStatus;
  16406. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16407. isSame = false;
  16408. return false;
  16409. }
  16410. } );
  16411. return isSame;
  16412. });
  16413. return isSame ? result : null;
  16414. };
  16415. /**
  16416. * 根据当前选区获取相关的table信息
  16417. * @return {Object}
  16418. */
  16419. UETable.getTableItemsByRange = function (editor) {
  16420. var start = editor.selection.getStart();
  16421. //ff下会选中bookmark
  16422. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16423. start = start.nextSibling;
  16424. }
  16425. //在table或者td边缘有可能存在选中tr的情况
  16426. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16427. tr = cell && cell.parentNode,
  16428. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16429. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16430. return {
  16431. cell:cell,
  16432. tr:tr,
  16433. table:table,
  16434. caption:caption
  16435. }
  16436. };
  16437. UETable.getUETableBySelected = function (editor) {
  16438. var table = UETable.getTableItemsByRange(editor).table;
  16439. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16440. return table.ueTable;
  16441. }
  16442. return null;
  16443. };
  16444. UETable.getDefaultValue = function (editor, table) {
  16445. var borderMap = {
  16446. thin:'0px',
  16447. medium:'1px',
  16448. thick:'2px'
  16449. },
  16450. tableBorder, tdPadding, tdBorder, tmpValue;
  16451. if (!table) {
  16452. table = editor.document.createElement('table');
  16453. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16454. editor.body.appendChild(table);
  16455. var td = table.getElementsByTagName('td')[0];
  16456. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16457. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16458. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16459. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16460. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16461. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16462. domUtils.remove(table);
  16463. return {
  16464. tableBorder:tableBorder,
  16465. tdPadding:tdPadding,
  16466. tdBorder:tdBorder
  16467. };
  16468. } else {
  16469. td = table.getElementsByTagName('td')[0];
  16470. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16471. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16472. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16473. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16474. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16475. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16476. return {
  16477. tableBorder:tableBorder,
  16478. tdPadding:tdPadding,
  16479. tdBorder:tdBorder
  16480. };
  16481. }
  16482. };
  16483. /**
  16484. * 根据当前点击的td或者table获取索引对象
  16485. * @param tdOrTable
  16486. */
  16487. UETable.getUETable = function (tdOrTable) {
  16488. var tag = tdOrTable.tagName.toLowerCase();
  16489. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16490. if (!tdOrTable.ueTable) {
  16491. tdOrTable.ueTable = new UETable(tdOrTable);
  16492. }
  16493. return tdOrTable.ueTable;
  16494. };
  16495. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16496. if (!cell || utils.isString(cell)) {
  16497. return this.table.ownerDocument.createElement(cell || 'td');
  16498. }
  16499. var flag = domUtils.hasClass(cell, "selectTdClass");
  16500. flag && domUtils.removeClasses(cell, "selectTdClass");
  16501. var tmpCell = cell.cloneNode(true);
  16502. if (ignoreMerge) {
  16503. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16504. }
  16505. //去掉宽高
  16506. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16507. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16508. tmpCell.style.borderLeftStyle = "";
  16509. tmpCell.style.borderTopStyle = "";
  16510. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16511. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16512. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16513. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16514. flag && domUtils.addClass(cell, "selectTdClass");
  16515. return tmpCell;
  16516. }
  16517. UETable.prototype = {
  16518. getMaxRows:function () {
  16519. var rows = this.table.rows, maxLen = 1;
  16520. for (var i = 0, row; row = rows[i]; i++) {
  16521. var currentMax = 1;
  16522. for (var j = 0, cj; cj = row.cells[j++];) {
  16523. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16524. }
  16525. maxLen = Math.max(currentMax + i, maxLen);
  16526. }
  16527. return maxLen;
  16528. },
  16529. /**
  16530. * 获取当前表格的最大列数
  16531. */
  16532. getMaxCols:function () {
  16533. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16534. for (var i = 0, row; row = rows[i]; i++) {
  16535. var cellsNum = 0;
  16536. for (var j = 0, cj; cj = row.cells[j++];) {
  16537. cellsNum += (cj.colSpan || 1);
  16538. if (cj.rowSpan && cj.rowSpan > 1) {
  16539. for (var k = 1; k < cj.rowSpan; k++) {
  16540. if (!cellRows['row_' + (i + k)]) {
  16541. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16542. } else {
  16543. cellRows['row_' + (i + k)]++
  16544. }
  16545. }
  16546. }
  16547. }
  16548. cellsNum += cellRows['row_' + i] || 0;
  16549. maxLen = Math.max(cellsNum, maxLen);
  16550. }
  16551. return maxLen;
  16552. },
  16553. getCellColIndex:function (cell) {
  16554. },
  16555. /**
  16556. * 获取当前cell旁边的单元格,
  16557. * @param cell
  16558. * @param right
  16559. */
  16560. getHSideCell:function (cell, right) {
  16561. try {
  16562. var cellInfo = this.getCellInfo(cell),
  16563. previewRowIndex, previewColIndex;
  16564. var len = this.selectedTds.length,
  16565. range = this.cellsRange;
  16566. //首行或者首列没有前置单元格
  16567. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16568. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16569. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16570. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16571. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16572. } catch (e) {
  16573. showError(e);
  16574. }
  16575. },
  16576. getTabNextCell:function (cell, preRowIndex) {
  16577. var cellInfo = this.getCellInfo(cell),
  16578. rowIndex = preRowIndex || cellInfo.rowIndex,
  16579. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16580. nextCell;
  16581. try {
  16582. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16583. } catch (e) {
  16584. try {
  16585. rowIndex = rowIndex * 1 + 1;
  16586. colIndex = 0;
  16587. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16588. } catch (e) {
  16589. }
  16590. }
  16591. return nextCell;
  16592. },
  16593. /**
  16594. * 获取视觉上的后置单元格
  16595. * @param cell
  16596. * @param bottom
  16597. */
  16598. getVSideCell:function (cell, bottom, ignoreRange) {
  16599. try {
  16600. var cellInfo = this.getCellInfo(cell),
  16601. nextRowIndex, nextColIndex;
  16602. var len = this.selectedTds.length && !ignoreRange,
  16603. range = this.cellsRange;
  16604. //末行或者末列没有后置单元格
  16605. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16606. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16607. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16608. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16609. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16610. } catch (e) {
  16611. showError(e);
  16612. }
  16613. },
  16614. /**
  16615. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16616. */
  16617. getSameEndPosCells:function (cell, xOrY) {
  16618. try {
  16619. var flag = (xOrY.toLowerCase() === "x"),
  16620. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16621. rows = this.table.rows,
  16622. cells = null, returns = [];
  16623. for (var i = 0; i < this.rowsNum; i++) {
  16624. cells = rows[i].cells;
  16625. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16626. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16627. //对应行的td已经被上面行rowSpan了
  16628. if (tmpEnd > end && flag) break;
  16629. if (cell == tmpCell || end == tmpEnd) {
  16630. //只获取单一的单元格
  16631. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16632. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16633. returns.push(tmpCell);
  16634. }
  16635. if (flag) break;
  16636. }
  16637. }
  16638. }
  16639. return returns;
  16640. } catch (e) {
  16641. showError(e);
  16642. }
  16643. },
  16644. setCellContent:function (cell, content) {
  16645. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16646. },
  16647. cloneCell:UETable.cloneCell,
  16648. /**
  16649. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16650. */
  16651. getSameStartPosXCells:function (cell) {
  16652. try {
  16653. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16654. rows = this.table.rows, cells , returns = [];
  16655. for (var i = 0; i < this.rowsNum; i++) {
  16656. cells = rows[i].cells;
  16657. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16658. var tmpStart = domUtils.getXY(tmpCell).x;
  16659. if (tmpStart > start) break;
  16660. if (tmpStart == start && tmpCell.colSpan == 1) {
  16661. returns.push(tmpCell);
  16662. break;
  16663. }
  16664. }
  16665. }
  16666. return returns;
  16667. } catch (e) {
  16668. showError(e);
  16669. }
  16670. },
  16671. /**
  16672. * 更新table对应的索引表
  16673. */
  16674. update:function (table) {
  16675. this.table = table || this.table;
  16676. this.selectedTds = [];
  16677. this.cellsRange = {};
  16678. this.indexTable = [];
  16679. var rows = this.table.rows,
  16680. rowsNum = this.getMaxRows(),
  16681. dNum = rowsNum - rows.length,
  16682. colsNum = this.getMaxCols();
  16683. while (dNum--) {
  16684. this.table.insertRow(rows.length);
  16685. }
  16686. this.rowsNum = rowsNum;
  16687. this.colsNum = colsNum;
  16688. for (var i = 0, len = rows.length; i < len; i++) {
  16689. this.indexTable[i] = new Array(colsNum);
  16690. }
  16691. //填充索引表
  16692. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16693. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16694. //修正整行被rowSpan时导致的行数计算错误
  16695. if (cell.rowSpan > rowsNum) {
  16696. cell.rowSpan = rowsNum;
  16697. }
  16698. var colIndex = cellIndex,
  16699. rowSpan = cell.rowSpan || 1,
  16700. colSpan = cell.colSpan || 1;
  16701. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16702. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16703. for (var j = 0; j < rowSpan; j++) {
  16704. for (var k = 0; k < colSpan; k++) {
  16705. this.indexTable[rowIndex + j][colIndex + k] = {
  16706. rowIndex:rowIndex,
  16707. cellIndex:cellIndex,
  16708. colIndex:colIndex,
  16709. rowSpan:rowSpan,
  16710. colSpan:colSpan
  16711. }
  16712. }
  16713. }
  16714. }
  16715. }
  16716. //修复残缺td
  16717. for (j = 0; j < rowsNum; j++) {
  16718. for (k = 0; k < colsNum; k++) {
  16719. if (this.indexTable[j][k] === undefined) {
  16720. row = rows[j];
  16721. cell = row.cells[row.cells.length - 1];
  16722. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16723. this.setCellContent(cell);
  16724. if (cell.colSpan !== 1)cell.colSpan = 1;
  16725. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16726. row.appendChild(cell);
  16727. this.indexTable[j][k] = {
  16728. rowIndex:j,
  16729. cellIndex:cell.cellIndex,
  16730. colIndex:k,
  16731. rowSpan:1,
  16732. colSpan:1
  16733. }
  16734. }
  16735. }
  16736. }
  16737. //当框选后删除行或者列后撤销,需要重建选区。
  16738. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16739. selectTds = [];
  16740. utils.each(tds, function (td) {
  16741. if (domUtils.hasClass(td, "selectTdClass")) {
  16742. selectTds.push(td);
  16743. }
  16744. });
  16745. if (selectTds.length) {
  16746. var start = selectTds[0],
  16747. end = selectTds[selectTds.length - 1],
  16748. startInfo = this.getCellInfo(start),
  16749. endInfo = this.getCellInfo(end);
  16750. this.selectedTds = selectTds;
  16751. this.cellsRange = {
  16752. beginRowIndex:startInfo.rowIndex,
  16753. beginColIndex:startInfo.colIndex,
  16754. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16755. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16756. };
  16757. }
  16758. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16759. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16760. domUtils.addClass(this.table.rows[0], "firstRow");
  16761. for(var i = 1; i< this.table.rows.length; i++) {
  16762. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16763. }
  16764. }
  16765. },
  16766. /**
  16767. * 获取单元格的索引信息
  16768. */
  16769. getCellInfo:function (cell) {
  16770. if (!cell) return;
  16771. var cellIndex = cell.cellIndex,
  16772. rowIndex = cell.parentNode.rowIndex,
  16773. rowInfo = this.indexTable[rowIndex],
  16774. numCols = this.colsNum;
  16775. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16776. var cellInfo = rowInfo[colIndex];
  16777. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16778. return cellInfo;
  16779. }
  16780. }
  16781. },
  16782. /**
  16783. * 根据行列号获取单元格
  16784. */
  16785. getCell:function (rowIndex, cellIndex) {
  16786. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16787. },
  16788. /**
  16789. * 删除单元格
  16790. */
  16791. deleteCell:function (cell, rowIndex) {
  16792. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16793. var row = this.table.rows[rowIndex];
  16794. row.deleteCell(cell.cellIndex);
  16795. },
  16796. /**
  16797. * 根据始末两个单元格获取被框选的所有单元格范围
  16798. */
  16799. getCellsRange:function (cellA, cellB) {
  16800. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16801. var tmpBeginRowIndex = beginRowIndex,
  16802. tmpBeginColIndex = beginColIndex,
  16803. tmpEndRowIndex = endRowIndex,
  16804. tmpEndColIndex = endColIndex,
  16805. cellInfo, colIndex, rowIndex;
  16806. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16807. if (beginRowIndex > 0) {
  16808. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16809. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16810. rowIndex = cellInfo.rowIndex;
  16811. if (rowIndex < beginRowIndex) {
  16812. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16813. }
  16814. }
  16815. }
  16816. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16817. if (endColIndex < me.colsNum) {
  16818. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16819. cellInfo = me.indexTable[rowIndex][endColIndex];
  16820. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16821. if (colIndex > endColIndex) {
  16822. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16823. }
  16824. }
  16825. }
  16826. // 检查是否有超出TableRange下边界的情况
  16827. if (endRowIndex < me.rowsNum) {
  16828. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16829. cellInfo = me.indexTable[endRowIndex][colIndex];
  16830. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16831. if (rowIndex > endRowIndex) {
  16832. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16833. }
  16834. }
  16835. }
  16836. // 检查是否有超出TableRange左边界的情况
  16837. if (beginColIndex > 0) {
  16838. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16839. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16840. colIndex = cellInfo.colIndex;
  16841. if (colIndex < beginColIndex) {
  16842. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16843. }
  16844. }
  16845. }
  16846. //递归调用直至所有完成所有框选单元格的扩展
  16847. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16848. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16849. } else {
  16850. // 不需要扩展TableRange的情况
  16851. return {
  16852. beginRowIndex:beginRowIndex,
  16853. beginColIndex:beginColIndex,
  16854. endRowIndex:endRowIndex,
  16855. endColIndex:endColIndex
  16856. };
  16857. }
  16858. }
  16859. try {
  16860. var me = this,
  16861. cellAInfo = me.getCellInfo(cellA);
  16862. if (cellA === cellB) {
  16863. return {
  16864. beginRowIndex:cellAInfo.rowIndex,
  16865. beginColIndex:cellAInfo.colIndex,
  16866. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16867. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16868. };
  16869. }
  16870. var cellBInfo = me.getCellInfo(cellB);
  16871. // 计算TableRange的四个边
  16872. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16873. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16874. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16875. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16876. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16877. } catch (e) {
  16878. //throw e;
  16879. }
  16880. },
  16881. /**
  16882. * 依据cellsRange获取对应的单元格集合
  16883. */
  16884. getCells:function (range) {
  16885. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16886. this.clearSelected();
  16887. var beginRowIndex = range.beginRowIndex,
  16888. beginColIndex = range.beginColIndex,
  16889. endRowIndex = range.endRowIndex,
  16890. endColIndex = range.endColIndex,
  16891. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16892. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16893. for (var j = beginColIndex; j <= endColIndex; j++) {
  16894. cellInfo = this.indexTable[i][j];
  16895. rowIndex = cellInfo.rowIndex;
  16896. colIndex = cellInfo.colIndex;
  16897. // 如果Cells里已经包含了此Cell则跳过
  16898. var key = rowIndex + '|' + colIndex;
  16899. if (tdHash[key]) continue;
  16900. tdHash[key] = 1;
  16901. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16902. return null;
  16903. }
  16904. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16905. }
  16906. }
  16907. return returnTds;
  16908. },
  16909. /**
  16910. * 清理已经选中的单元格
  16911. */
  16912. clearSelected:function () {
  16913. UETable.removeSelectedClass(this.selectedTds);
  16914. this.selectedTds = [];
  16915. this.cellsRange = {};
  16916. },
  16917. /**
  16918. * 根据range设置已经选中的单元格
  16919. */
  16920. setSelected:function (range) {
  16921. var cells = this.getCells(range);
  16922. UETable.addSelectedClass(cells);
  16923. this.selectedTds = cells;
  16924. this.cellsRange = range;
  16925. },
  16926. isFullRow:function () {
  16927. var range = this.cellsRange;
  16928. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16929. },
  16930. isFullCol:function () {
  16931. var range = this.cellsRange,
  16932. table = this.table,
  16933. ths = table.getElementsByTagName("th"),
  16934. rows = range.endRowIndex - range.beginRowIndex + 1;
  16935. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16936. },
  16937. /**
  16938. * 获取视觉上的前置单元格,默认是左边,top传入时
  16939. * @param cell
  16940. * @param top
  16941. */
  16942. getNextCell:function (cell, bottom, ignoreRange) {
  16943. try {
  16944. var cellInfo = this.getCellInfo(cell),
  16945. nextRowIndex, nextColIndex;
  16946. var len = this.selectedTds.length && !ignoreRange,
  16947. range = this.cellsRange;
  16948. //末行或者末列没有后置单元格
  16949. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16950. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16951. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16952. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16953. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16954. } catch (e) {
  16955. showError(e);
  16956. }
  16957. },
  16958. getPreviewCell:function (cell, top) {
  16959. try {
  16960. var cellInfo = this.getCellInfo(cell),
  16961. previewRowIndex, previewColIndex;
  16962. var len = this.selectedTds.length,
  16963. range = this.cellsRange;
  16964. //首行或者首列没有前置单元格
  16965. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16966. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  16967. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  16968. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16969. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  16970. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16971. } catch (e) {
  16972. showError(e);
  16973. }
  16974. },
  16975. /**
  16976. * 移动单元格中的内容
  16977. */
  16978. moveContent:function (cellTo, cellFrom) {
  16979. if (UETable.isEmptyBlock(cellFrom)) return;
  16980. if (UETable.isEmptyBlock(cellTo)) {
  16981. cellTo.innerHTML = cellFrom.innerHTML;
  16982. return;
  16983. }
  16984. var child = cellTo.lastChild;
  16985. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  16986. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  16987. }
  16988. while (child = cellFrom.firstChild) {
  16989. cellTo.appendChild(child);
  16990. }
  16991. },
  16992. /**
  16993. * 向右合并单元格
  16994. */
  16995. mergeRight:function (cell) {
  16996. var cellInfo = this.getCellInfo(cell),
  16997. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  16998. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  16999. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17000. //合并
  17001. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17002. //被合并的单元格不应存在宽度属性
  17003. cell.removeAttribute("width");
  17004. //移动内容
  17005. this.moveContent(cell, rightCell);
  17006. //删掉被合并的Cell
  17007. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17008. this.update();
  17009. },
  17010. /**
  17011. * 向下合并单元格
  17012. */
  17013. mergeDown:function (cell) {
  17014. var cellInfo = this.getCellInfo(cell),
  17015. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17016. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17017. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17018. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17019. cell.removeAttribute("height");
  17020. this.moveContent(cell, downCell);
  17021. this.deleteCell(downCell, downCellInfo.rowIndex);
  17022. this.update();
  17023. },
  17024. /**
  17025. * 合并整个range中的内容
  17026. */
  17027. mergeRange:function () {
  17028. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17029. var range = this.cellsRange,
  17030. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17031. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17032. var index = this.indexTable,
  17033. info = this.getCellInfo(leftTopCell);
  17034. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17035. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17036. }
  17037. // 删除剩余的Cells
  17038. var cells = this.getCells(range);
  17039. for(var i= 0,ci;ci=cells[i++];){
  17040. if (ci !== leftTopCell) {
  17041. this.moveContent(leftTopCell, ci);
  17042. this.deleteCell(ci);
  17043. }
  17044. }
  17045. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17046. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17047. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17048. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17049. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17050. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17051. leftTopCell.colSpan = 1;
  17052. }
  17053. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17054. var rowIndex = leftTopCell.parentNode.rowIndex;
  17055. //解决IE下的表格操作问题
  17056. if( this.table.deleteRow ) {
  17057. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17058. this.table.deleteRow(curIndex);
  17059. }
  17060. } else {
  17061. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17062. var row = this.table.rows[rowIndex + 1];
  17063. row.parentNode.removeChild(row);
  17064. }
  17065. }
  17066. leftTopCell.rowSpan = 1;
  17067. }
  17068. this.update();
  17069. },
  17070. /**
  17071. * 插入一行单元格
  17072. */
  17073. insertRow:function (rowIndex, sourceCell) {
  17074. var numCols = this.colsNum,
  17075. table = this.table,
  17076. row = table.insertRow(rowIndex), cell,
  17077. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17078. function replaceTdToTh(colIndex, cell, tableRow) {
  17079. if (colIndex == 0) {
  17080. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17081. th = tr.cells[colIndex];
  17082. if (th.tagName == 'TH') {
  17083. th = cell.ownerDocument.createElement("th");
  17084. th.appendChild(cell.firstChild);
  17085. tableRow.insertBefore(th, cell);
  17086. domUtils.remove(cell)
  17087. }
  17088. }else{
  17089. if (cell.tagName == 'TH') {
  17090. var td = cell.ownerDocument.createElement("td");
  17091. td.appendChild(cell.firstChild);
  17092. tableRow.insertBefore(td, cell);
  17093. domUtils.remove(cell)
  17094. }
  17095. }
  17096. }
  17097. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17098. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17099. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17100. cell = this.cloneCell(sourceCell, true);
  17101. this.setCellContent(cell);
  17102. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17103. row.appendChild(cell);
  17104. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17105. }
  17106. } else {
  17107. var infoRow = this.indexTable[rowIndex],
  17108. cellIndex = 0;
  17109. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17110. var cellInfo = infoRow[colIndex];
  17111. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17112. if (cellInfo.rowIndex < rowIndex) {
  17113. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17114. cell.rowSpan = cellInfo.rowSpan + 1;
  17115. } else {
  17116. cell = this.cloneCell(sourceCell, true);
  17117. this.setCellContent(cell);
  17118. row.appendChild(cell);
  17119. }
  17120. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17121. }
  17122. }
  17123. //框选时插入不触发contentchange,需要手动更新索引。
  17124. this.update();
  17125. return row;
  17126. },
  17127. /**
  17128. * 删除一行单元格
  17129. * @param rowIndex
  17130. */
  17131. deleteRow:function (rowIndex) {
  17132. var row = this.table.rows[rowIndex],
  17133. infoRow = this.indexTable[rowIndex],
  17134. colsNum = this.colsNum,
  17135. count = 0; //处理计数
  17136. for (var colIndex = 0; colIndex < colsNum;) {
  17137. var cellInfo = infoRow[colIndex],
  17138. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17139. if (cell.rowSpan > 1) {
  17140. if (cellInfo.rowIndex == rowIndex) {
  17141. var clone = cell.cloneNode(true);
  17142. clone.rowSpan = cell.rowSpan - 1;
  17143. clone.innerHTML = "";
  17144. cell.rowSpan = 1;
  17145. var nextRowIndex = rowIndex + 1,
  17146. nextRow = this.table.rows[nextRowIndex],
  17147. insertCellIndex,
  17148. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17149. if (preMerged < colIndex) {
  17150. insertCellIndex = colIndex - preMerged - 1;
  17151. //nextRow.insertCell(insertCellIndex);
  17152. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17153. } else {
  17154. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17155. }
  17156. count += 1;
  17157. //cell.parentNode.removeChild(cell);
  17158. }
  17159. }
  17160. colIndex += cell.colSpan || 1;
  17161. }
  17162. var deleteTds = [], cacheMap = {};
  17163. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17164. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17165. tmpCellIndex = infoRow[colIndex].cellIndex,
  17166. key = tmpRowIndex + "_" + tmpCellIndex;
  17167. if (cacheMap[key])continue;
  17168. cacheMap[key] = 1;
  17169. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17170. deleteTds.push(cell);
  17171. }
  17172. var mergeTds = [];
  17173. utils.each(deleteTds, function (td) {
  17174. if (td.rowSpan == 1) {
  17175. td.parentNode.removeChild(td);
  17176. } else {
  17177. mergeTds.push(td);
  17178. }
  17179. });
  17180. utils.each(mergeTds, function (td) {
  17181. td.rowSpan--;
  17182. });
  17183. row.parentNode.removeChild(row);
  17184. //浏览器方法本身存在bug,采用自定义方法删除
  17185. //this.table.deleteRow(rowIndex);
  17186. this.update();
  17187. },
  17188. insertCol:function (colIndex, sourceCell, defaultValue) {
  17189. var rowsNum = this.rowsNum,
  17190. rowIndex = 0,
  17191. tableRow, cell,
  17192. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17193. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17194. function replaceTdToTh(rowIndex, cell, tableRow) {
  17195. if (rowIndex == 0) {
  17196. var th = cell.nextSibling || cell.previousSibling;
  17197. if (th.tagName == 'TH') {
  17198. th = cell.ownerDocument.createElement("th");
  17199. th.appendChild(cell.firstChild);
  17200. tableRow.insertBefore(th, cell);
  17201. domUtils.remove(cell)
  17202. }
  17203. }else{
  17204. if (cell.tagName == 'TH') {
  17205. var td = cell.ownerDocument.createElement("td");
  17206. td.appendChild(cell.firstChild);
  17207. tableRow.insertBefore(td, cell);
  17208. domUtils.remove(cell)
  17209. }
  17210. }
  17211. }
  17212. var preCell;
  17213. if (colIndex == 0 || colIndex == this.colsNum) {
  17214. for (; rowIndex < rowsNum; rowIndex++) {
  17215. tableRow = this.table.rows[rowIndex];
  17216. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17217. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17218. this.setCellContent(cell);
  17219. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17220. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17221. if (!colIndex) {
  17222. tableRow.insertBefore(cell, tableRow.cells[0]);
  17223. } else {
  17224. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17225. }
  17226. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17227. }
  17228. } else {
  17229. for (; rowIndex < rowsNum; rowIndex++) {
  17230. var cellInfo = this.indexTable[rowIndex][colIndex];
  17231. if (cellInfo.colIndex < colIndex) {
  17232. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17233. cell.colSpan = cellInfo.colSpan + 1;
  17234. } else {
  17235. tableRow = this.table.rows[rowIndex];
  17236. preCell = tableRow.cells[cellInfo.cellIndex];
  17237. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17238. this.setCellContent(cell);
  17239. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17240. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17241. //防止IE下报错
  17242. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17243. }
  17244. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17245. }
  17246. }
  17247. //框选时插入不触发contentchange,需要手动更新索引
  17248. this.update();
  17249. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17250. },
  17251. updateWidth:function (width, defaultValue) {
  17252. var table = this.table,
  17253. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17254. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17255. table.setAttribute("width", tmpWidth);
  17256. return;
  17257. }
  17258. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17259. utils.each(tds, function (td) {
  17260. td.setAttribute("width", width);
  17261. })
  17262. },
  17263. deleteCol:function (colIndex) {
  17264. var indexTable = this.indexTable,
  17265. tableRows = this.table.rows,
  17266. backTableWidth = this.table.getAttribute("width"),
  17267. backTdWidth = 0,
  17268. rowsNum = this.rowsNum,
  17269. cacheMap = {};
  17270. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17271. var infoRow = indexTable[rowIndex],
  17272. cellInfo = infoRow[colIndex],
  17273. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17274. // 跳过已经处理过的Cell
  17275. if (cacheMap[key])continue;
  17276. cacheMap[key] = 1;
  17277. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17278. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17279. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17280. if (cell.colSpan > 1) {
  17281. cell.colSpan--;
  17282. } else {
  17283. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17284. }
  17285. rowIndex += cellInfo.rowSpan || 1;
  17286. }
  17287. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17288. this.update();
  17289. },
  17290. splitToCells:function (cell) {
  17291. var me = this,
  17292. cells = this.splitToRows(cell);
  17293. utils.each(cells, function (cell) {
  17294. me.splitToCols(cell);
  17295. })
  17296. },
  17297. splitToRows:function (cell) {
  17298. var cellInfo = this.getCellInfo(cell),
  17299. rowIndex = cellInfo.rowIndex,
  17300. colIndex = cellInfo.colIndex,
  17301. results = [];
  17302. // 修改Cell的rowSpan
  17303. cell.rowSpan = 1;
  17304. results.push(cell);
  17305. // 补齐单元格
  17306. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17307. if (i == rowIndex)continue;
  17308. var tableRow = this.table.rows[i],
  17309. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17310. tmpCell.colSpan = cellInfo.colSpan;
  17311. this.setCellContent(tmpCell);
  17312. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17313. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17314. if (cell.style.cssText) {
  17315. tmpCell.style.cssText = cell.style.cssText;
  17316. }
  17317. results.push(tmpCell);
  17318. }
  17319. this.update();
  17320. return results;
  17321. },
  17322. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17323. var indexRow = this.indexTable[rowIndex],
  17324. num = 0;
  17325. for (var i = 0; i < colIndex;) {
  17326. var colSpan = indexRow[i].colSpan,
  17327. tmpRowIndex = indexRow[i].rowIndex;
  17328. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17329. i += colSpan;
  17330. }
  17331. return num;
  17332. },
  17333. splitToCols:function (cell) {
  17334. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17335. cellInfo = this.getCellInfo(cell),
  17336. rowIndex = cellInfo.rowIndex,
  17337. colIndex = cellInfo.colIndex,
  17338. results = [];
  17339. // 修改Cell的rowSpan
  17340. cell.colSpan = 1;
  17341. cell.setAttribute("width", backWidth);
  17342. results.push(cell);
  17343. // 补齐单元格
  17344. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17345. if (j == colIndex)continue;
  17346. var tableRow = this.table.rows[rowIndex],
  17347. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17348. tmpCell.rowSpan = cellInfo.rowSpan;
  17349. this.setCellContent(tmpCell);
  17350. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17351. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17352. tmpCell.setAttribute('width', backWidth);
  17353. if (cell.style.cssText) {
  17354. tmpCell.style.cssText = cell.style.cssText;
  17355. }
  17356. //处理th的情况
  17357. if (cell.tagName == 'TH') {
  17358. var th = cell.ownerDocument.createElement('th');
  17359. th.appendChild(tmpCell.firstChild);
  17360. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17361. th.rowSpan = tmpCell.rowSpan;
  17362. tableRow.insertBefore(th, tmpCell);
  17363. domUtils.remove(tmpCell);
  17364. }
  17365. results.push(tmpCell);
  17366. }
  17367. this.update();
  17368. return results;
  17369. },
  17370. isLastCell:function (cell, rowsNum, colsNum) {
  17371. rowsNum = rowsNum || this.rowsNum;
  17372. colsNum = colsNum || this.colsNum;
  17373. var cellInfo = this.getCellInfo(cell);
  17374. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17375. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17376. },
  17377. getLastCell:function (cells) {
  17378. cells = cells || this.table.getElementsByTagName("td");
  17379. var firstInfo = this.getCellInfo(cells[0]);
  17380. var me = this, last = cells[0],
  17381. tr = last.parentNode,
  17382. cellsNum = 0, cols = 0, rows;
  17383. utils.each(cells, function (cell) {
  17384. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17385. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17386. });
  17387. rows = cellsNum / cols;
  17388. utils.each(cells, function (cell) {
  17389. if (me.isLastCell(cell, rows, cols)) {
  17390. last = cell;
  17391. return false;
  17392. }
  17393. });
  17394. return last;
  17395. },
  17396. selectRow:function (rowIndex) {
  17397. var indexRow = this.indexTable[rowIndex],
  17398. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17399. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17400. range = this.getCellsRange(start, end);
  17401. this.setSelected(range);
  17402. },
  17403. selectTable:function () {
  17404. var tds = this.table.getElementsByTagName("td"),
  17405. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17406. this.setSelected(range);
  17407. },
  17408. setBackground:function (cells, value) {
  17409. if (typeof value === "string") {
  17410. utils.each(cells, function (cell) {
  17411. cell.style.backgroundColor = value;
  17412. })
  17413. } else if (typeof value === "object") {
  17414. value = utils.extend({
  17415. repeat:true,
  17416. colorList:["#ddd", "#fff"]
  17417. }, value);
  17418. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17419. count = 0,
  17420. colors = value.colorList,
  17421. getColor = function (list, index, repeat) {
  17422. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17423. };
  17424. for (var i = 0, cell; cell = cells[i++];) {
  17425. var cellInfo = this.getCellInfo(cell);
  17426. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17427. }
  17428. }
  17429. },
  17430. removeBackground:function (cells) {
  17431. utils.each(cells, function (cell) {
  17432. cell.style.backgroundColor = "";
  17433. })
  17434. }
  17435. };
  17436. function showError(e) {
  17437. }
  17438. })();
  17439. // plugins/table.cmds.js
  17440. /**
  17441. * Created with JetBrains PhpStorm.
  17442. * User: taoqili
  17443. * Date: 13-2-20
  17444. * Time: 下午6:25
  17445. * To change this template use File | Settings | File Templates.
  17446. */
  17447. ;
  17448. (function () {
  17449. var UT = UE.UETable,
  17450. getTableItemsByRange = function (editor) {
  17451. return UT.getTableItemsByRange(editor);
  17452. },
  17453. getUETableBySelected = function (editor) {
  17454. return UT.getUETableBySelected(editor)
  17455. },
  17456. getDefaultValue = function (editor, table) {
  17457. return UT.getDefaultValue(editor, table);
  17458. },
  17459. getUETable = function (tdOrTable) {
  17460. return UT.getUETable(tdOrTable);
  17461. };
  17462. UE.commands['inserttable'] = {
  17463. queryCommandState: function () {
  17464. return getTableItemsByRange(this).table ? -1 : 0;
  17465. },
  17466. execCommand: function (cmd, opt) {
  17467. function createTable(opt, tdWidth) {
  17468. var html = [],
  17469. rowsNum = opt.numRows,
  17470. colsNum = opt.numCols;
  17471. for (var r = 0; r < rowsNum; r++) {
  17472. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17473. for (var c = 0; c < colsNum; c++) {
  17474. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17475. }
  17476. html.push('</tr>')
  17477. }
  17478. //禁止指定table-width
  17479. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17480. }
  17481. if (!opt) {
  17482. opt = utils.extend({}, {
  17483. numCols: this.options.defaultCols,
  17484. numRows: this.options.defaultRows,
  17485. tdvalign: this.options.tdvalign
  17486. })
  17487. }
  17488. var me = this;
  17489. var range = this.selection.getRange(),
  17490. start = range.startContainer,
  17491. firstParentBlock = domUtils.findParent(start, function (node) {
  17492. return domUtils.isBlockElm(node);
  17493. }, true) || me.body;
  17494. var defaultValue = getDefaultValue(me),
  17495. tableWidth = firstParentBlock.offsetWidth,
  17496. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17497. //todo其他属性
  17498. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17499. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17500. }
  17501. };
  17502. UE.commands['insertparagraphbeforetable'] = {
  17503. queryCommandState: function () {
  17504. return getTableItemsByRange(this).cell ? 0 : -1;
  17505. },
  17506. execCommand: function () {
  17507. var table = getTableItemsByRange(this).table;
  17508. if (table) {
  17509. var p = this.document.createElement("p");
  17510. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17511. table.parentNode.insertBefore(p, table);
  17512. this.selection.getRange().setStart(p, 0).setCursor();
  17513. }
  17514. }
  17515. };
  17516. UE.commands['deletetable'] = {
  17517. queryCommandState: function () {
  17518. var rng = this.selection.getRange();
  17519. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17520. },
  17521. execCommand: function (cmd, table) {
  17522. var rng = this.selection.getRange();
  17523. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17524. if (table) {
  17525. var next = table.nextSibling;
  17526. if (!next) {
  17527. next = domUtils.createElement(this.document, 'p', {
  17528. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17529. });
  17530. table.parentNode.insertBefore(next, table);
  17531. }
  17532. domUtils.remove(table);
  17533. rng = this.selection.getRange();
  17534. if (next.nodeType == 3) {
  17535. rng.setStartBefore(next)
  17536. } else {
  17537. rng.setStart(next, 0)
  17538. }
  17539. rng.setCursor(false, true)
  17540. this.fireEvent("tablehasdeleted")
  17541. }
  17542. }
  17543. };
  17544. UE.commands['cellalign'] = {
  17545. queryCommandState: function () {
  17546. return getSelectedArr(this).length ? 0 : -1
  17547. },
  17548. execCommand: function (cmd, align) {
  17549. var selectedTds = getSelectedArr(this);
  17550. if (selectedTds.length) {
  17551. for (var i = 0, ci; ci = selectedTds[i++];) {
  17552. ci.setAttribute('align', align);
  17553. }
  17554. }
  17555. }
  17556. };
  17557. UE.commands['cellvalign'] = {
  17558. queryCommandState: function () {
  17559. return getSelectedArr(this).length ? 0 : -1;
  17560. },
  17561. execCommand: function (cmd, valign) {
  17562. var selectedTds = getSelectedArr(this);
  17563. if (selectedTds.length) {
  17564. for (var i = 0, ci; ci = selectedTds[i++];) {
  17565. ci.setAttribute('vAlign', valign);
  17566. }
  17567. }
  17568. }
  17569. };
  17570. UE.commands['insertcaption'] = {
  17571. queryCommandState: function () {
  17572. var table = getTableItemsByRange(this).table;
  17573. if (table) {
  17574. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17575. }
  17576. return -1;
  17577. },
  17578. execCommand: function () {
  17579. var table = getTableItemsByRange(this).table;
  17580. if (table) {
  17581. var caption = this.document.createElement('caption');
  17582. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17583. table.insertBefore(caption, table.firstChild);
  17584. var range = this.selection.getRange();
  17585. range.setStart(caption, 0).setCursor();
  17586. }
  17587. }
  17588. };
  17589. UE.commands['deletecaption'] = {
  17590. queryCommandState: function () {
  17591. var rng = this.selection.getRange(),
  17592. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17593. if (table) {
  17594. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17595. }
  17596. return -1;
  17597. },
  17598. execCommand: function () {
  17599. var rng = this.selection.getRange(),
  17600. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17601. if (table) {
  17602. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17603. var range = this.selection.getRange();
  17604. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17605. }
  17606. }
  17607. };
  17608. UE.commands['inserttitle'] = {
  17609. queryCommandState: function () {
  17610. var table = getTableItemsByRange(this).table;
  17611. if (table) {
  17612. var firstRow = table.rows[0];
  17613. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17614. }
  17615. return -1;
  17616. },
  17617. execCommand: function () {
  17618. var table = getTableItemsByRange(this).table;
  17619. if (table) {
  17620. getUETable(table).insertRow(0, 'th');
  17621. }
  17622. var th = table.getElementsByTagName('th')[0];
  17623. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17624. }
  17625. };
  17626. UE.commands['deletetitle'] = {
  17627. queryCommandState: function () {
  17628. var table = getTableItemsByRange(this).table;
  17629. if (table) {
  17630. var firstRow = table.rows[0];
  17631. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17632. }
  17633. return -1;
  17634. },
  17635. execCommand: function () {
  17636. var table = getTableItemsByRange(this).table;
  17637. if (table) {
  17638. domUtils.remove(table.rows[0])
  17639. }
  17640. var td = table.getElementsByTagName('td')[0];
  17641. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17642. }
  17643. };
  17644. UE.commands['inserttitlecol'] = {
  17645. queryCommandState: function () {
  17646. var table = getTableItemsByRange(this).table;
  17647. if (table) {
  17648. var lastRow = table.rows[table.rows.length-1];
  17649. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17650. }
  17651. return -1;
  17652. },
  17653. execCommand: function (cmd) {
  17654. var table = getTableItemsByRange(this).table;
  17655. if (table) {
  17656. getUETable(table).insertCol(0, 'th');
  17657. }
  17658. resetTdWidth(table, this);
  17659. var th = table.getElementsByTagName('th')[0];
  17660. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17661. }
  17662. };
  17663. UE.commands['deletetitlecol'] = {
  17664. queryCommandState: function () {
  17665. var table = getTableItemsByRange(this).table;
  17666. if (table) {
  17667. var lastRow = table.rows[table.rows.length-1];
  17668. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17669. }
  17670. return -1;
  17671. },
  17672. execCommand: function () {
  17673. var table = getTableItemsByRange(this).table;
  17674. if (table) {
  17675. for(var i = 0; i< table.rows.length; i++ ){
  17676. domUtils.remove(table.rows[i].children[0])
  17677. }
  17678. }
  17679. resetTdWidth(table, this);
  17680. var td = table.getElementsByTagName('td')[0];
  17681. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17682. }
  17683. };
  17684. UE.commands["mergeright"] = {
  17685. queryCommandState: function (cmd) {
  17686. var tableItems = getTableItemsByRange(this),
  17687. table = tableItems.table,
  17688. cell = tableItems.cell;
  17689. if (!table || !cell) return -1;
  17690. var ut = getUETable(table);
  17691. if (ut.selectedTds.length) return -1;
  17692. var cellInfo = ut.getCellInfo(cell),
  17693. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17694. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17695. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17696. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17697. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17698. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17699. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17700. },
  17701. execCommand: function (cmd) {
  17702. var rng = this.selection.getRange(),
  17703. bk = rng.createBookmark(true);
  17704. var cell = getTableItemsByRange(this).cell,
  17705. ut = getUETable(cell);
  17706. ut.mergeRight(cell);
  17707. rng.moveToBookmark(bk).select();
  17708. }
  17709. };
  17710. UE.commands["mergedown"] = {
  17711. queryCommandState: function (cmd) {
  17712. var tableItems = getTableItemsByRange(this),
  17713. table = tableItems.table,
  17714. cell = tableItems.cell;
  17715. if (!table || !cell) return -1;
  17716. var ut = getUETable(table);
  17717. if (ut.selectedTds.length)return -1;
  17718. var cellInfo = ut.getCellInfo(cell),
  17719. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17720. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17721. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17722. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17723. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17724. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17725. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17726. },
  17727. execCommand: function () {
  17728. var rng = this.selection.getRange(),
  17729. bk = rng.createBookmark(true);
  17730. var cell = getTableItemsByRange(this).cell,
  17731. ut = getUETable(cell);
  17732. ut.mergeDown(cell);
  17733. rng.moveToBookmark(bk).select();
  17734. }
  17735. };
  17736. UE.commands["mergecells"] = {
  17737. queryCommandState: function () {
  17738. return getUETableBySelected(this) ? 0 : -1;
  17739. },
  17740. execCommand: function () {
  17741. var ut = getUETableBySelected(this);
  17742. if (ut && ut.selectedTds.length) {
  17743. var cell = ut.selectedTds[0];
  17744. ut.mergeRange();
  17745. var rng = this.selection.getRange();
  17746. if (domUtils.isEmptyBlock(cell)) {
  17747. rng.setStart(cell, 0).collapse(true)
  17748. } else {
  17749. rng.selectNodeContents(cell)
  17750. }
  17751. rng.select();
  17752. }
  17753. }
  17754. };
  17755. UE.commands["insertrow"] = {
  17756. queryCommandState: function () {
  17757. var tableItems = getTableItemsByRange(this),
  17758. cell = tableItems.cell;
  17759. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17760. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17761. },
  17762. execCommand: function () {
  17763. var rng = this.selection.getRange(),
  17764. bk = rng.createBookmark(true);
  17765. var tableItems = getTableItemsByRange(this),
  17766. cell = tableItems.cell,
  17767. table = tableItems.table,
  17768. ut = getUETable(table),
  17769. cellInfo = ut.getCellInfo(cell);
  17770. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17771. if (!ut.selectedTds.length) {
  17772. ut.insertRow(cellInfo.rowIndex, cell);
  17773. } else {
  17774. var range = ut.cellsRange;
  17775. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17776. ut.insertRow(range.beginRowIndex, cell);
  17777. }
  17778. }
  17779. rng.moveToBookmark(bk).select();
  17780. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17781. }
  17782. };
  17783. //后插入行
  17784. UE.commands["insertrownext"] = {
  17785. queryCommandState: function () {
  17786. var tableItems = getTableItemsByRange(this),
  17787. cell = tableItems.cell;
  17788. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17789. },
  17790. execCommand: function () {
  17791. var rng = this.selection.getRange(),
  17792. bk = rng.createBookmark(true);
  17793. var tableItems = getTableItemsByRange(this),
  17794. cell = tableItems.cell,
  17795. table = tableItems.table,
  17796. ut = getUETable(table),
  17797. cellInfo = ut.getCellInfo(cell);
  17798. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17799. if (!ut.selectedTds.length) {
  17800. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17801. } else {
  17802. var range = ut.cellsRange;
  17803. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17804. ut.insertRow(range.endRowIndex + 1, cell);
  17805. }
  17806. }
  17807. rng.moveToBookmark(bk).select();
  17808. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17809. }
  17810. };
  17811. UE.commands["deleterow"] = {
  17812. queryCommandState: function () {
  17813. var tableItems = getTableItemsByRange(this);
  17814. return tableItems.cell ? 0 : -1;
  17815. },
  17816. execCommand: function () {
  17817. var cell = getTableItemsByRange(this).cell,
  17818. ut = getUETable(cell),
  17819. cellsRange = ut.cellsRange,
  17820. cellInfo = ut.getCellInfo(cell),
  17821. preCell = ut.getVSideCell(cell),
  17822. nextCell = ut.getVSideCell(cell, true),
  17823. rng = this.selection.getRange();
  17824. if (utils.isEmptyObject(cellsRange)) {
  17825. ut.deleteRow(cellInfo.rowIndex);
  17826. } else {
  17827. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17828. ut.deleteRow(cellsRange.beginRowIndex);
  17829. }
  17830. }
  17831. var table = ut.table;
  17832. if (!table.getElementsByTagName('td').length) {
  17833. var nextSibling = table.nextSibling;
  17834. domUtils.remove(table);
  17835. if (nextSibling) {
  17836. rng.setStart(nextSibling, 0).setCursor(false, true);
  17837. }
  17838. } else {
  17839. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17840. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17841. } else {
  17842. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17843. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17844. }
  17845. }
  17846. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17847. }
  17848. };
  17849. UE.commands["insertcol"] = {
  17850. queryCommandState: function (cmd) {
  17851. var tableItems = getTableItemsByRange(this),
  17852. cell = tableItems.cell;
  17853. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17854. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17855. },
  17856. execCommand: function (cmd) {
  17857. var rng = this.selection.getRange(),
  17858. bk = rng.createBookmark(true);
  17859. if (this.queryCommandState(cmd) == -1)return;
  17860. var cell = getTableItemsByRange(this).cell,
  17861. ut = getUETable(cell),
  17862. cellInfo = ut.getCellInfo(cell);
  17863. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17864. if (!ut.selectedTds.length) {
  17865. ut.insertCol(cellInfo.colIndex, cell);
  17866. } else {
  17867. var range = ut.cellsRange;
  17868. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17869. ut.insertCol(range.beginColIndex, cell);
  17870. }
  17871. }
  17872. rng.moveToBookmark(bk).select(true);
  17873. }
  17874. };
  17875. UE.commands["insertcolnext"] = {
  17876. queryCommandState: function () {
  17877. var tableItems = getTableItemsByRange(this),
  17878. cell = tableItems.cell;
  17879. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17880. },
  17881. execCommand: function () {
  17882. var rng = this.selection.getRange(),
  17883. bk = rng.createBookmark(true);
  17884. var cell = getTableItemsByRange(this).cell,
  17885. ut = getUETable(cell),
  17886. cellInfo = ut.getCellInfo(cell);
  17887. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17888. if (!ut.selectedTds.length) {
  17889. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17890. } else {
  17891. var range = ut.cellsRange;
  17892. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17893. ut.insertCol(range.endColIndex + 1, cell);
  17894. }
  17895. }
  17896. rng.moveToBookmark(bk).select();
  17897. }
  17898. };
  17899. UE.commands["deletecol"] = {
  17900. queryCommandState: function () {
  17901. var tableItems = getTableItemsByRange(this);
  17902. return tableItems.cell ? 0 : -1;
  17903. },
  17904. execCommand: function () {
  17905. var cell = getTableItemsByRange(this).cell,
  17906. ut = getUETable(cell),
  17907. range = ut.cellsRange,
  17908. cellInfo = ut.getCellInfo(cell),
  17909. preCell = ut.getHSideCell(cell),
  17910. nextCell = ut.getHSideCell(cell, true);
  17911. if (utils.isEmptyObject(range)) {
  17912. ut.deleteCol(cellInfo.colIndex);
  17913. } else {
  17914. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17915. ut.deleteCol(range.beginColIndex);
  17916. }
  17917. }
  17918. var table = ut.table,
  17919. rng = this.selection.getRange();
  17920. if (!table.getElementsByTagName('td').length) {
  17921. var nextSibling = table.nextSibling;
  17922. domUtils.remove(table);
  17923. if (nextSibling) {
  17924. rng.setStart(nextSibling, 0).setCursor(false, true);
  17925. }
  17926. } else {
  17927. if (domUtils.inDoc(cell, this.document)) {
  17928. rng.setStart(cell, 0).setCursor(false, true);
  17929. } else {
  17930. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17931. rng.selectNodeContents(nextCell).setCursor(false, true);
  17932. } else {
  17933. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17934. rng.selectNodeContents(preCell).setCursor(true, true);
  17935. }
  17936. }
  17937. }
  17938. }
  17939. }
  17940. };
  17941. UE.commands["splittocells"] = {
  17942. queryCommandState: function () {
  17943. var tableItems = getTableItemsByRange(this),
  17944. cell = tableItems.cell;
  17945. if (!cell) return -1;
  17946. var ut = getUETable(tableItems.table);
  17947. if (ut.selectedTds.length > 0) return -1;
  17948. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17949. },
  17950. execCommand: function () {
  17951. var rng = this.selection.getRange(),
  17952. bk = rng.createBookmark(true);
  17953. var cell = getTableItemsByRange(this).cell,
  17954. ut = getUETable(cell);
  17955. ut.splitToCells(cell);
  17956. rng.moveToBookmark(bk).select();
  17957. }
  17958. };
  17959. UE.commands["splittorows"] = {
  17960. queryCommandState: function () {
  17961. var tableItems = getTableItemsByRange(this),
  17962. cell = tableItems.cell;
  17963. if (!cell) return -1;
  17964. var ut = getUETable(tableItems.table);
  17965. if (ut.selectedTds.length > 0) return -1;
  17966. return cell && cell.rowSpan > 1 ? 0 : -1;
  17967. },
  17968. execCommand: function () {
  17969. var rng = this.selection.getRange(),
  17970. bk = rng.createBookmark(true);
  17971. var cell = getTableItemsByRange(this).cell,
  17972. ut = getUETable(cell);
  17973. ut.splitToRows(cell);
  17974. rng.moveToBookmark(bk).select();
  17975. }
  17976. };
  17977. UE.commands["splittocols"] = {
  17978. queryCommandState: function () {
  17979. var tableItems = getTableItemsByRange(this),
  17980. cell = tableItems.cell;
  17981. if (!cell) return -1;
  17982. var ut = getUETable(tableItems.table);
  17983. if (ut.selectedTds.length > 0) return -1;
  17984. return cell && cell.colSpan > 1 ? 0 : -1;
  17985. },
  17986. execCommand: function () {
  17987. var rng = this.selection.getRange(),
  17988. bk = rng.createBookmark(true);
  17989. var cell = getTableItemsByRange(this).cell,
  17990. ut = getUETable(cell);
  17991. ut.splitToCols(cell);
  17992. rng.moveToBookmark(bk).select();
  17993. }
  17994. };
  17995. UE.commands["adaptbytext"] =
  17996. UE.commands["adaptbywindow"] = {
  17997. queryCommandState: function () {
  17998. return getTableItemsByRange(this).table ? 0 : -1
  17999. },
  18000. execCommand: function (cmd) {
  18001. var tableItems = getTableItemsByRange(this),
  18002. table = tableItems.table;
  18003. if (table) {
  18004. if (cmd == 'adaptbywindow') {
  18005. resetTdWidth(table, this);
  18006. } else {
  18007. var cells = domUtils.getElementsByTagName(table, "td th");
  18008. utils.each(cells, function (cell) {
  18009. cell.removeAttribute("width");
  18010. });
  18011. table.removeAttribute("width");
  18012. }
  18013. }
  18014. }
  18015. };
  18016. //平均分配各列
  18017. UE.commands['averagedistributecol'] = {
  18018. queryCommandState: function () {
  18019. var ut = getUETableBySelected(this);
  18020. if (!ut) return -1;
  18021. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18022. },
  18023. execCommand: function (cmd) {
  18024. var me = this,
  18025. ut = getUETableBySelected(me);
  18026. function getAverageWidth() {
  18027. var tb = ut.table,
  18028. averageWidth, sumWidth = 0, colsNum = 0,
  18029. tbAttr = getDefaultValue(me, tb);
  18030. if (ut.isFullRow()) {
  18031. sumWidth = tb.offsetWidth;
  18032. colsNum = ut.colsNum;
  18033. } else {
  18034. var begin = ut.cellsRange.beginColIndex,
  18035. end = ut.cellsRange.endColIndex,
  18036. node;
  18037. for (var i = begin; i <= end;) {
  18038. node = ut.selectedTds[i];
  18039. sumWidth += node.offsetWidth;
  18040. i += node.colSpan;
  18041. colsNum += 1;
  18042. }
  18043. }
  18044. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18045. return averageWidth;
  18046. }
  18047. function setAverageWidth(averageWidth) {
  18048. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18049. node.setAttribute("width", "");
  18050. });
  18051. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18052. utils.each(cells, function (node) {
  18053. if (node.colSpan == 1) {
  18054. node.setAttribute("width", averageWidth);
  18055. }
  18056. });
  18057. }
  18058. if (ut && ut.selectedTds.length) {
  18059. setAverageWidth(getAverageWidth());
  18060. }
  18061. }
  18062. };
  18063. //平均分配各行
  18064. UE.commands['averagedistributerow'] = {
  18065. queryCommandState: function () {
  18066. var ut = getUETableBySelected(this);
  18067. if (!ut) return -1;
  18068. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18069. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18070. },
  18071. execCommand: function (cmd) {
  18072. var me = this,
  18073. ut = getUETableBySelected(me);
  18074. function getAverageHeight() {
  18075. var averageHeight, rowNum, sumHeight = 0,
  18076. tb = ut.table,
  18077. tbAttr = getDefaultValue(me, tb),
  18078. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18079. if (ut.isFullCol()) {
  18080. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18081. thArr = domUtils.getElementsByTagName(tb, "th"),
  18082. captionHeight, thHeight;
  18083. if (captionArr.length > 0) {
  18084. captionHeight = captionArr[0].offsetHeight;
  18085. }
  18086. if (thArr.length > 0) {
  18087. thHeight = thArr[0].offsetHeight;
  18088. }
  18089. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18090. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18091. } else {
  18092. var begin = ut.cellsRange.beginRowIndex,
  18093. end = ut.cellsRange.endRowIndex,
  18094. count = 0,
  18095. trs = domUtils.getElementsByTagName(tb, "tr");
  18096. for (var i = begin; i <= end; i++) {
  18097. sumHeight += trs[i].offsetHeight;
  18098. count += 1;
  18099. }
  18100. rowNum = count;
  18101. }
  18102. //ie8下是混杂模式
  18103. if (browser.ie && browser.version < 9) {
  18104. averageHeight = Math.ceil(sumHeight / rowNum);
  18105. } else {
  18106. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18107. }
  18108. return averageHeight;
  18109. }
  18110. function setAverageHeight(averageHeight) {
  18111. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18112. utils.each(cells, function (node) {
  18113. if (node.rowSpan == 1) {
  18114. node.setAttribute("height", averageHeight);
  18115. }
  18116. });
  18117. }
  18118. if (ut && ut.selectedTds.length) {
  18119. setAverageHeight(getAverageHeight());
  18120. }
  18121. }
  18122. };
  18123. //单元格对齐方式
  18124. UE.commands['cellalignment'] = {
  18125. queryCommandState: function () {
  18126. return getTableItemsByRange(this).table ? 0 : -1
  18127. },
  18128. execCommand: function (cmd, data) {
  18129. var me = this,
  18130. ut = getUETableBySelected(me);
  18131. if (!ut) {
  18132. var start = me.selection.getStart(),
  18133. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18134. if (!/caption/ig.test(cell.tagName)) {
  18135. domUtils.setAttributes(cell, data);
  18136. } else {
  18137. cell.style.textAlign = data.align;
  18138. cell.style.verticalAlign = data.vAlign;
  18139. }
  18140. me.selection.getRange().setCursor(true);
  18141. } else {
  18142. utils.each(ut.selectedTds, function (cell) {
  18143. domUtils.setAttributes(cell, data);
  18144. });
  18145. }
  18146. },
  18147. /**
  18148. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18149. * @see UE.UETable.getTableCellAlignState
  18150. */
  18151. queryCommandValue: function (cmd) {
  18152. var activeMenuCell = getTableItemsByRange( this).cell;
  18153. if( !activeMenuCell ) {
  18154. activeMenuCell = getSelectedArr(this)[0];
  18155. }
  18156. if (!activeMenuCell) {
  18157. return null;
  18158. } else {
  18159. //获取同时选中的其他单元格
  18160. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18161. !cells.length && ( cells = activeMenuCell );
  18162. return UE.UETable.getTableCellAlignState(cells);
  18163. }
  18164. }
  18165. };
  18166. //表格对齐方式
  18167. UE.commands['tablealignment'] = {
  18168. queryCommandState: function () {
  18169. if (browser.ie && browser.version < 8) {
  18170. return -1;
  18171. }
  18172. return getTableItemsByRange(this).table ? 0 : -1
  18173. },
  18174. execCommand: function (cmd, value) {
  18175. var me = this,
  18176. start = me.selection.getStart(),
  18177. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18178. if (table) {
  18179. table.setAttribute("align",value);
  18180. }
  18181. }
  18182. };
  18183. //表格属性
  18184. UE.commands['edittable'] = {
  18185. queryCommandState: function () {
  18186. return getTableItemsByRange(this).table ? 0 : -1
  18187. },
  18188. execCommand: function (cmd, color) {
  18189. var rng = this.selection.getRange(),
  18190. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18191. if (table) {
  18192. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18193. domUtils.getElementsByTagName(table, "th"),
  18194. domUtils.getElementsByTagName(table, "caption")
  18195. );
  18196. utils.each(arr, function (node) {
  18197. node.style.borderColor = color;
  18198. });
  18199. }
  18200. }
  18201. };
  18202. //单元格属性
  18203. UE.commands['edittd'] = {
  18204. queryCommandState: function () {
  18205. return getTableItemsByRange(this).table ? 0 : -1
  18206. },
  18207. execCommand: function (cmd, bkColor) {
  18208. var me = this,
  18209. ut = getUETableBySelected(me);
  18210. if (!ut) {
  18211. var start = me.selection.getStart(),
  18212. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18213. if (cell) {
  18214. cell.style.backgroundColor = bkColor;
  18215. }
  18216. } else {
  18217. utils.each(ut.selectedTds, function (cell) {
  18218. cell.style.backgroundColor = bkColor;
  18219. });
  18220. }
  18221. }
  18222. };
  18223. UE.commands["settablebackground"] = {
  18224. queryCommandState: function () {
  18225. return getSelectedArr(this).length > 1 ? 0 : -1;
  18226. },
  18227. execCommand: function (cmd, value) {
  18228. var cells, ut;
  18229. cells = getSelectedArr(this);
  18230. ut = getUETable(cells[0]);
  18231. ut.setBackground(cells, value);
  18232. }
  18233. };
  18234. UE.commands["cleartablebackground"] = {
  18235. queryCommandState: function () {
  18236. var cells = getSelectedArr(this);
  18237. if (!cells.length)return -1;
  18238. for (var i = 0, cell; cell = cells[i++];) {
  18239. if (cell.style.backgroundColor !== "") return 0;
  18240. }
  18241. return -1;
  18242. },
  18243. execCommand: function () {
  18244. var cells = getSelectedArr(this),
  18245. ut = getUETable(cells[0]);
  18246. ut.removeBackground(cells);
  18247. }
  18248. };
  18249. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18250. queryCommandState: function (cmd) {
  18251. var table = getTableItemsByRange(this).table;
  18252. if (!table) return -1;
  18253. var interlaced = table.getAttribute("interlaced");
  18254. if (cmd == "interlacetable") {
  18255. //TODO 待定
  18256. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18257. return (interlaced === "enabled") ? -1 : 0;
  18258. } else {
  18259. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18260. }
  18261. },
  18262. execCommand: function (cmd, classList) {
  18263. var table = getTableItemsByRange(this).table;
  18264. if (cmd == "interlacetable") {
  18265. table.setAttribute("interlaced", "enabled");
  18266. this.fireEvent("interlacetable", table, classList);
  18267. } else {
  18268. table.setAttribute("interlaced", "disabled");
  18269. this.fireEvent("uninterlacetable", table);
  18270. }
  18271. }
  18272. };
  18273. UE.commands["setbordervisible"] = {
  18274. queryCommandState: function (cmd) {
  18275. var table = getTableItemsByRange(this).table;
  18276. if (!table) return -1;
  18277. return 0;
  18278. },
  18279. execCommand: function () {
  18280. var table = getTableItemsByRange(this).table;
  18281. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18282. td.style.borderWidth = '1px';
  18283. td.style.borderStyle = 'solid';
  18284. })
  18285. }
  18286. };
  18287. function resetTdWidth(table, editor) {
  18288. var tds = domUtils.getElementsByTagName(table,'td th');
  18289. utils.each(tds, function (td) {
  18290. td.removeAttribute("width");
  18291. });
  18292. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18293. var tdsWidths = [];
  18294. setTimeout(function () {
  18295. utils.each(tds, function (td) {
  18296. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18297. })
  18298. utils.each(tds, function (td,i) {
  18299. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18300. })
  18301. }, 0);
  18302. }
  18303. function getTableWidth(editor, needIEHack, defaultValue) {
  18304. var body = editor.body;
  18305. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18306. }
  18307. function getSelectedArr(editor) {
  18308. var cell = getTableItemsByRange(editor).cell;
  18309. if (cell) {
  18310. var ut = getUETable(cell);
  18311. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18312. } else {
  18313. return [];
  18314. }
  18315. }
  18316. })();
  18317. // plugins/table.action.js
  18318. /**
  18319. * Created with JetBrains PhpStorm.
  18320. * User: taoqili
  18321. * Date: 12-10-12
  18322. * Time: 上午10:05
  18323. * To change this template use File | Settings | File Templates.
  18324. */
  18325. UE.plugins['table'] = function () {
  18326. var me = this,
  18327. tabTimer = null,
  18328. //拖动计时器
  18329. tableDragTimer = null,
  18330. //双击计时器
  18331. tableResizeTimer = null,
  18332. //单元格最小宽度
  18333. cellMinWidth = 5,
  18334. isInResizeBuffer = false,
  18335. //单元格边框大小
  18336. cellBorderWidth = 5,
  18337. //鼠标偏移距离
  18338. offsetOfTableCell = 10,
  18339. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18340. singleClickState = 0,
  18341. userActionStatus = null,
  18342. //双击允许的时间范围
  18343. dblclickTime = 360,
  18344. UT = UE.UETable,
  18345. getUETable = function (tdOrTable) {
  18346. return UT.getUETable(tdOrTable);
  18347. },
  18348. getUETableBySelected = function (editor) {
  18349. return UT.getUETableBySelected(editor);
  18350. },
  18351. getDefaultValue = function (editor, table) {
  18352. return UT.getDefaultValue(editor, table);
  18353. },
  18354. removeSelectedClass = function (cells) {
  18355. return UT.removeSelectedClass(cells);
  18356. };
  18357. function showError(e) {
  18358. // throw e;
  18359. }
  18360. me.ready(function(){
  18361. var me = this;
  18362. var orgGetText = me.selection.getText;
  18363. me.selection.getText = function(){
  18364. var table = getUETableBySelected(me);
  18365. if(table){
  18366. var str = '';
  18367. utils.each(table.selectedTds,function(td){
  18368. str += td[browser.ie?'innerText':'textContent'];
  18369. })
  18370. return str;
  18371. }else{
  18372. return orgGetText.call(me.selection)
  18373. }
  18374. }
  18375. })
  18376. //处理拖动及框选相关方法
  18377. var startTd = null, //鼠标按下时的锚点td
  18378. currentTd = null, //当前鼠标经过时的td
  18379. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18380. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18381. dragButton = null,
  18382. dragOver = false,
  18383. dragLine = null, //模拟的拖动线
  18384. dragTd = null; //发生拖动的目标td
  18385. var mousedown = false,
  18386. //todo 判断混乱模式
  18387. needIEHack = true;
  18388. me.setOpt({
  18389. 'maxColNum':20,
  18390. 'maxRowNum':100,
  18391. 'defaultCols':5,
  18392. 'defaultRows':5,
  18393. 'tdvalign':'top',
  18394. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18395. 'tableDragable':false,
  18396. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18397. });
  18398. me.getUETable = getUETable;
  18399. var commands = {
  18400. 'deletetable':1,
  18401. 'inserttable':1,
  18402. 'cellvalign':1,
  18403. 'insertcaption':1,
  18404. 'deletecaption':1,
  18405. 'inserttitle':1,
  18406. 'deletetitle':1,
  18407. "mergeright":1,
  18408. "mergedown":1,
  18409. "mergecells":1,
  18410. "insertrow":1,
  18411. "insertrownext":1,
  18412. "deleterow":1,
  18413. "insertcol":1,
  18414. "insertcolnext":1,
  18415. "deletecol":1,
  18416. "splittocells":1,
  18417. "splittorows":1,
  18418. "splittocols":1,
  18419. "adaptbytext":1,
  18420. "adaptbywindow":1,
  18421. "adaptbycustomer":1,
  18422. "insertparagraph":1,
  18423. "insertparagraphbeforetable":1,
  18424. "averagedistributecol":1,
  18425. "averagedistributerow":1
  18426. };
  18427. me.ready(function () {
  18428. utils.cssRule('table',
  18429. //选中的td上的样式
  18430. '.selectTdClass{background-color:#edf5fa !important}' +
  18431. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18432. //插入的表格的默认样式
  18433. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18434. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18435. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18436. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18437. 'table tr.firstRow th{border-top-width:2px;}' +
  18438. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18439. 'td p{margin:0;padding:0;}', me.document);
  18440. var tableCopyList, isFullCol, isFullRow;
  18441. //注册del/backspace事件
  18442. me.addListener('keydown', function (cmd, evt) {
  18443. var me = this;
  18444. var keyCode = evt.keyCode || evt.which;
  18445. if (keyCode == 8) {
  18446. var ut = getUETableBySelected(me);
  18447. if (ut && ut.selectedTds.length) {
  18448. if (ut.isFullCol()) {
  18449. me.execCommand('deletecol')
  18450. } else if (ut.isFullRow()) {
  18451. me.execCommand('deleterow')
  18452. } else {
  18453. me.fireEvent('delcells');
  18454. }
  18455. domUtils.preventDefault(evt);
  18456. }
  18457. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18458. range = me.selection.getRange();
  18459. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18460. me.fireEvent('saveScene');
  18461. var table = caption.parentNode;
  18462. domUtils.remove(caption);
  18463. if (table) {
  18464. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18465. }
  18466. me.fireEvent('saveScene');
  18467. }
  18468. }
  18469. if (keyCode == 46) {
  18470. ut = getUETableBySelected(me);
  18471. if (ut) {
  18472. me.fireEvent('saveScene');
  18473. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18474. domUtils.fillNode(me.document, ci)
  18475. }
  18476. me.fireEvent('saveScene');
  18477. domUtils.preventDefault(evt);
  18478. }
  18479. }
  18480. if (keyCode == 13) {
  18481. var rng = me.selection.getRange(),
  18482. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18483. if (caption) {
  18484. var table = domUtils.findParentByTagName(caption, 'table');
  18485. if (!rng.collapsed) {
  18486. rng.deleteContents();
  18487. me.fireEvent('saveScene');
  18488. } else {
  18489. if (caption) {
  18490. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18491. }
  18492. }
  18493. domUtils.preventDefault(evt);
  18494. return;
  18495. }
  18496. if (rng.collapsed) {
  18497. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18498. if (table) {
  18499. var cell = table.rows[0].cells[0],
  18500. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18501. preNode = table.previousSibling;
  18502. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18503. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18504. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18505. me.execCommand('insertparagraphbeforetable');
  18506. domUtils.preventDefault(evt);
  18507. }
  18508. }
  18509. }
  18510. }
  18511. }
  18512. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18513. tableCopyList = null;
  18514. var ut = getUETableBySelected(me);
  18515. if (ut) {
  18516. var tds = ut.selectedTds;
  18517. isFullCol = ut.isFullCol();
  18518. isFullRow = ut.isFullRow();
  18519. tableCopyList = [
  18520. [ut.cloneCell(tds[0],null,true)]
  18521. ];
  18522. for (var i = 1, ci; ci = tds[i]; i++) {
  18523. if (ci.parentNode !== tds[i - 1].parentNode) {
  18524. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18525. } else {
  18526. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18527. }
  18528. }
  18529. }
  18530. }
  18531. });
  18532. me.addListener("tablehasdeleted",function(){
  18533. toggleDraggableState(this, false, "", null);
  18534. if (dragButton)domUtils.remove(dragButton);
  18535. });
  18536. me.addListener('beforepaste', function (cmd, html) {
  18537. var me = this;
  18538. var rng = me.selection.getRange();
  18539. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18540. var div = me.document.createElement("div");
  18541. div.innerHTML = html.html;
  18542. //trace:3729
  18543. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18544. return;
  18545. }
  18546. var table = getUETableBySelected(me);
  18547. if (tableCopyList) {
  18548. me.fireEvent('saveScene');
  18549. var rng = me.selection.getRange();
  18550. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18551. if (td) {
  18552. var ut = getUETable(td);
  18553. if (isFullRow) {
  18554. var rowIndex = ut.getCellInfo(td).rowIndex;
  18555. if (td.tagName == 'TH') {
  18556. rowIndex++;
  18557. }
  18558. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18559. var tr = ut.insertRow(rowIndex++, "td");
  18560. for (var j = 0, cj; cj = ci[j]; j++) {
  18561. var cell = tr.cells[j];
  18562. if (!cell) {
  18563. cell = tr.insertCell(j)
  18564. }
  18565. cell.innerHTML = cj.innerHTML;
  18566. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18567. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18568. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18569. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18570. }
  18571. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18572. if (!ci[j])
  18573. break;
  18574. cj.innerHTML = ci[j].innerHTML;
  18575. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18576. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18577. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18578. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18579. }
  18580. }
  18581. } else {
  18582. if (isFullCol) {
  18583. cellInfo = ut.getCellInfo(td);
  18584. var maxColNum = 0;
  18585. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18586. maxColNum += cj.colSpan || 1;
  18587. }
  18588. me.__hasEnterExecCommand = true;
  18589. for (i = 0; i < maxColNum; i++) {
  18590. me.execCommand('insertcol');
  18591. }
  18592. me.__hasEnterExecCommand = false;
  18593. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18594. if (td.tagName == 'TH') {
  18595. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18596. }
  18597. }
  18598. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18599. tmpNode = td;
  18600. for (var j = 0, cj; cj = ci[j++];) {
  18601. if (td) {
  18602. td.innerHTML = cj.innerHTML;
  18603. //todo 定制处理
  18604. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18605. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18606. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18607. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18608. preNode = td;
  18609. td = td.nextSibling;
  18610. } else {
  18611. var cloneTd = cj.cloneNode(true);
  18612. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18613. preNode.parentNode.appendChild(cloneTd)
  18614. }
  18615. }
  18616. td = ut.getNextCell(tmpNode, true, true);
  18617. if (!tableCopyList[i])
  18618. break;
  18619. if (!td) {
  18620. var cellInfo = ut.getCellInfo(tmpNode);
  18621. ut.table.insertRow(ut.table.rows.length);
  18622. ut.update();
  18623. td = ut.getVSideCell(tmpNode, true);
  18624. }
  18625. }
  18626. }
  18627. ut.update();
  18628. } else {
  18629. table = me.document.createElement('table');
  18630. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18631. var tr = table.insertRow(table.rows.length);
  18632. for (var j = 0, cj; cj = ci[j++];) {
  18633. cloneTd = UT.cloneCell(cj,null,true);
  18634. domUtils.removeAttributes(cloneTd, ['class']);
  18635. tr.appendChild(cloneTd)
  18636. }
  18637. if (j == 2 && cloneTd.rowSpan > 1) {
  18638. cloneTd.rowSpan = 1;
  18639. }
  18640. }
  18641. var defaultValue = getDefaultValue(me),
  18642. width = me.body.offsetWidth -
  18643. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18644. me.execCommand('insertHTML', '<table ' +
  18645. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18646. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18647. }
  18648. me.fireEvent('contentchange');
  18649. me.fireEvent('saveScene');
  18650. html.html = '';
  18651. return true;
  18652. } else {
  18653. var div = me.document.createElement("div"), tables;
  18654. div.innerHTML = html.html;
  18655. tables = div.getElementsByTagName("table");
  18656. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18657. utils.each(tables, function (t) {
  18658. domUtils.remove(t)
  18659. });
  18660. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18661. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18662. }
  18663. } else {
  18664. utils.each(tables, function (table) {
  18665. removeStyleSize(table, true);
  18666. domUtils.removeAttributes(table, ['style', 'border']);
  18667. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18668. if (isEmptyBlock(td)) {
  18669. domUtils.fillNode(me.document, td);
  18670. }
  18671. removeStyleSize(td, true);
  18672. // domUtils.removeAttributes(td, ['style'])
  18673. });
  18674. });
  18675. }
  18676. html.html = div.innerHTML;
  18677. }
  18678. });
  18679. me.addListener('afterpaste', function () {
  18680. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18681. if (table.offsetWidth > me.body.offsetWidth) {
  18682. var defaultValue = getDefaultValue(me, table);
  18683. 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'
  18684. }
  18685. })
  18686. });
  18687. me.addListener('blur', function () {
  18688. tableCopyList = null;
  18689. });
  18690. var timer;
  18691. me.addListener('keydown', function () {
  18692. clearTimeout(timer);
  18693. timer = setTimeout(function () {
  18694. var rng = me.selection.getRange(),
  18695. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18696. if (cell) {
  18697. var table = cell.parentNode.parentNode.parentNode;
  18698. if (table.offsetWidth > table.getAttribute("width")) {
  18699. cell.style.wordBreak = "break-all";
  18700. }
  18701. }
  18702. }, 100);
  18703. });
  18704. me.addListener("selectionchange", function () {
  18705. toggleDraggableState(me, false, "", null);
  18706. });
  18707. //内容变化时触发索引更新
  18708. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18709. me.addListener("contentchange", function () {
  18710. var me = this;
  18711. //尽可能排除一些不需要更新的状况
  18712. hideDragLine(me);
  18713. if (getUETableBySelected(me))return;
  18714. var rng = me.selection.getRange();
  18715. var start = rng.startContainer;
  18716. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18717. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18718. if (me.fireEvent("excludetable", table) === true) return;
  18719. table.ueTable = new UT(table);
  18720. //trace:3742
  18721. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18722. //
  18723. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18724. // domUtils.fillNode(me.document, td);
  18725. // if (browser.ie && browser.version == 6) {
  18726. // td.innerHTML = '&nbsp;'
  18727. // }
  18728. // }
  18729. // });
  18730. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18731. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18732. // domUtils.fillNode(me.document, th);
  18733. // if (browser.ie && browser.version == 6) {
  18734. // th.innerHTML = '&nbsp;'
  18735. // }
  18736. // }
  18737. // });
  18738. table.onmouseover = function () {
  18739. me.fireEvent('tablemouseover', table);
  18740. };
  18741. table.onmousemove = function () {
  18742. me.fireEvent('tablemousemove', table);
  18743. me.options.tableDragable && toggleDragButton(true, this, me);
  18744. utils.defer(function(){
  18745. me.fireEvent('contentchange',50)
  18746. },true)
  18747. };
  18748. table.onmouseout = function () {
  18749. me.fireEvent('tablemouseout', table);
  18750. toggleDraggableState(me, false, "", null);
  18751. hideDragLine(me);
  18752. };
  18753. table.onclick = function (evt) {
  18754. evt = me.window.event || evt;
  18755. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18756. if (!target)return;
  18757. var ut = getUETable(target),
  18758. table = ut.table,
  18759. cellInfo = ut.getCellInfo(target),
  18760. cellsRange,
  18761. rng = me.selection.getRange();
  18762. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18763. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18764. // ut.setSelected(cellsRange);
  18765. // return;
  18766. // }
  18767. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18768. //
  18769. // return;
  18770. // }
  18771. if (inTableSide(table, target, evt, true)) {
  18772. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18773. if (evt.shiftKey && ut.selectedTds.length) {
  18774. if (ut.selectedTds[0] !== endTdCol) {
  18775. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18776. ut.setSelected(cellsRange);
  18777. } else {
  18778. rng && rng.selectNodeContents(endTdCol).select();
  18779. }
  18780. } else {
  18781. if (target !== endTdCol) {
  18782. cellsRange = ut.getCellsRange(target, endTdCol);
  18783. ut.setSelected(cellsRange);
  18784. } else {
  18785. rng && rng.selectNodeContents(endTdCol).select();
  18786. }
  18787. }
  18788. return;
  18789. }
  18790. if (inTableSide(table, target, evt)) {
  18791. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18792. if (evt.shiftKey && ut.selectedTds.length) {
  18793. if (ut.selectedTds[0] !== endTdRow) {
  18794. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18795. ut.setSelected(cellsRange);
  18796. } else {
  18797. rng && rng.selectNodeContents(endTdRow).select();
  18798. }
  18799. } else {
  18800. if (target !== endTdRow) {
  18801. cellsRange = ut.getCellsRange(target, endTdRow);
  18802. ut.setSelected(cellsRange);
  18803. } else {
  18804. rng && rng.selectNodeContents(endTdRow).select();
  18805. }
  18806. }
  18807. }
  18808. };
  18809. });
  18810. switchBorderColor(me, true);
  18811. });
  18812. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18813. domUtils.on(me.document, "mouseout", function (evt) {
  18814. var target = evt.target || evt.srcElement;
  18815. if (target.tagName == "TABLE") {
  18816. toggleDraggableState(me, false, "", null);
  18817. }
  18818. });
  18819. /**
  18820. * 表格隔行变色
  18821. */
  18822. me.addListener("interlacetable",function(type,table,classList){
  18823. if(!table) return;
  18824. var me = this,
  18825. rows = table.rows,
  18826. len = rows.length,
  18827. getClass = function(list,index,repeat){
  18828. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18829. };
  18830. for(var i = 0;i<len;i++){
  18831. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18832. }
  18833. });
  18834. me.addListener("uninterlacetable",function(type,table){
  18835. if(!table) return;
  18836. var me = this,
  18837. rows = table.rows,
  18838. classList = me.options.classList,
  18839. len = rows.length;
  18840. for(var i = 0;i<len;i++){
  18841. domUtils.removeClasses( rows[i], classList );
  18842. }
  18843. });
  18844. me.addListener("mousedown", mouseDownEvent);
  18845. me.addListener("mouseup", mouseUpEvent);
  18846. //拖动的时候触发mouseup
  18847. domUtils.on( me.body, 'dragstart', function( evt ){
  18848. mouseUpEvent.call( me, 'dragstart', evt );
  18849. });
  18850. me.addOutputRule(function(root){
  18851. utils.each(root.getNodesByTagName('div'),function(n){
  18852. if (n.getAttr('id') == 'ue_tableDragLine') {
  18853. n.parentNode.removeChild(n);
  18854. }
  18855. });
  18856. });
  18857. var currentRowIndex = 0;
  18858. me.addListener("mousedown", function () {
  18859. currentRowIndex = 0;
  18860. });
  18861. me.addListener('tabkeydown', function () {
  18862. var range = this.selection.getRange(),
  18863. common = range.getCommonAncestor(true, true),
  18864. table = domUtils.findParentByTagName(common, 'table');
  18865. if (table) {
  18866. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18867. var cell = domUtils.getElementsByTagName(table, 'th td');
  18868. if (cell && cell.length) {
  18869. range.setStart(cell[0], 0).setCursor(false, true)
  18870. }
  18871. } else {
  18872. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18873. ua = getUETable(cell);
  18874. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18875. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18876. if (nextCell) {
  18877. if (isEmptyBlock(nextCell)) {
  18878. range.setStart(nextCell, 0).setCursor(false, true)
  18879. } else {
  18880. range.selectNodeContents(nextCell).select()
  18881. }
  18882. } else {
  18883. me.fireEvent('saveScene');
  18884. me.__hasEnterExecCommand = true;
  18885. this.execCommand('insertrownext');
  18886. me.__hasEnterExecCommand = false;
  18887. range = this.selection.getRange();
  18888. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18889. me.fireEvent('saveScene');
  18890. }
  18891. }
  18892. return true;
  18893. }
  18894. });
  18895. browser.ie && me.addListener('selectionchange', function () {
  18896. toggleDraggableState(this, false, "", null);
  18897. });
  18898. me.addListener("keydown", function (type, evt) {
  18899. var me = this;
  18900. //处理在表格的最后一个输入tab产生新的表格
  18901. var keyCode = evt.keyCode || evt.which;
  18902. if (keyCode == 8 || keyCode == 46) {
  18903. return;
  18904. }
  18905. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18906. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18907. var ut = getUETableBySelected(me);
  18908. if (!ut) return;
  18909. notCtrlKey && ut.clearSelected();
  18910. });
  18911. me.addListener("beforegetcontent", function () {
  18912. switchBorderColor(this, false);
  18913. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18914. if (domUtils.isEmptyNode(ci)) {
  18915. ci.innerHTML = '&nbsp;'
  18916. }
  18917. });
  18918. });
  18919. me.addListener("aftergetcontent", function () {
  18920. switchBorderColor(this, true);
  18921. });
  18922. me.addListener("getAllHtml", function () {
  18923. removeSelectedClass(me.document.getElementsByTagName("td"));
  18924. });
  18925. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18926. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18927. if (!fullscreen) {
  18928. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18929. tables = domUtils.getElementsByTagName(this.body, "table");
  18930. utils.each(tables, function (table) {
  18931. if (table.offsetWidth < me.body.offsetWidth) return false;
  18932. var tds = domUtils.getElementsByTagName(table, "td"),
  18933. backWidths = [];
  18934. utils.each(tds, function (td) {
  18935. backWidths.push(td.offsetWidth);
  18936. });
  18937. for (var i = 0, td; td = tds[i]; i++) {
  18938. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18939. }
  18940. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18941. });
  18942. }
  18943. });
  18944. //重写execCommand命令,用于处理框选时的处理
  18945. var oldExecCommand = me.execCommand;
  18946. me.execCommand = function (cmd, datatat) {
  18947. var me = this,
  18948. args = arguments;
  18949. cmd = cmd.toLowerCase();
  18950. var ut = getUETableBySelected(me), tds,
  18951. range = new dom.Range(me.document),
  18952. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18953. result;
  18954. if (!cmdFun) return;
  18955. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18956. me.__hasEnterExecCommand = true;
  18957. me.fireEvent("beforeexeccommand", cmd);
  18958. tds = ut.selectedTds;
  18959. var lastState = -2, lastValue = -2, value, state;
  18960. for (var i = 0, td; td = tds[i]; i++) {
  18961. if (isEmptyBlock(td)) {
  18962. range.setStart(td, 0).setCursor(false, true)
  18963. } else {
  18964. range.selectNode(td).select(true);
  18965. }
  18966. state = me.queryCommandState(cmd);
  18967. value = me.queryCommandValue(cmd);
  18968. if (state != -1) {
  18969. if (lastState !== state || lastValue !== value) {
  18970. me._ignoreContentChange = true;
  18971. result = oldExecCommand.apply(me, arguments);
  18972. me._ignoreContentChange = false;
  18973. }
  18974. lastState = me.queryCommandState(cmd);
  18975. lastValue = me.queryCommandValue(cmd);
  18976. if (domUtils.isEmptyBlock(td)) {
  18977. domUtils.fillNode(me.document, td)
  18978. }
  18979. }
  18980. }
  18981. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  18982. me.fireEvent('contentchange');
  18983. me.fireEvent("afterexeccommand", cmd);
  18984. me.__hasEnterExecCommand = false;
  18985. me._selectionChange();
  18986. } else {
  18987. result = oldExecCommand.apply(me, arguments);
  18988. }
  18989. return result;
  18990. };
  18991. });
  18992. /**
  18993. * 删除obj的宽高style,改成属性宽高
  18994. * @param obj
  18995. * @param replaceToProperty
  18996. */
  18997. function removeStyleSize(obj, replaceToProperty) {
  18998. removeStyle(obj, "width", true);
  18999. removeStyle(obj, "height", true);
  19000. }
  19001. function removeStyle(obj, styleName, replaceToProperty) {
  19002. if (obj.style[styleName]) {
  19003. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19004. obj.style[styleName] = "";
  19005. }
  19006. }
  19007. function getParentTdOrTh(ele) {
  19008. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19009. var td;
  19010. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19011. return null;
  19012. }
  19013. function isEmptyBlock(node) {
  19014. var reg = new RegExp(domUtils.fillChar, 'g');
  19015. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19016. return 0;
  19017. }
  19018. for (var n in dtd.$isNotEmpty) {
  19019. if (node.getElementsByTagName(n).length) {
  19020. return 0;
  19021. }
  19022. }
  19023. return 1;
  19024. }
  19025. function mouseCoords(evt) {
  19026. if (evt.pageX || evt.pageY) {
  19027. return { x:evt.pageX, y:evt.pageY };
  19028. }
  19029. return {
  19030. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19031. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19032. };
  19033. }
  19034. function mouseMoveEvent(evt) {
  19035. if( isEditorDisabled() ) {
  19036. return;
  19037. }
  19038. try {
  19039. //普通状态下鼠标移动
  19040. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19041. pos;
  19042. //区分用户的行为是拖动还是双击
  19043. if( isInResizeBuffer ) {
  19044. me.body.style.webkitUserSelect = 'none';
  19045. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19046. clearTableDragTimer();
  19047. isInResizeBuffer = false;
  19048. singleClickState = 0;
  19049. //drag action
  19050. tableBorderDrag(evt);
  19051. }
  19052. }
  19053. //修改单元格大小时的鼠标移动
  19054. if (onDrag && dragTd) {
  19055. singleClickState = 0;
  19056. me.body.style.webkitUserSelect = 'none';
  19057. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19058. pos = mouseCoords(evt);
  19059. toggleDraggableState(me, true, onDrag, pos, target);
  19060. if (onDrag == "h") {
  19061. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19062. } else if (onDrag == "v") {
  19063. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19064. }
  19065. return;
  19066. }
  19067. //当鼠标处于table上时,修改移动过程中的光标状态
  19068. if (target) {
  19069. //针对使用table作为容器的组件不触发拖拽效果
  19070. if (me.fireEvent('excludetable', target) === true)
  19071. return;
  19072. pos = mouseCoords(evt);
  19073. var state = getRelation(target, pos),
  19074. table = domUtils.findParentByTagName(target, "table", true);
  19075. if (inTableSide(table, target, evt, true)) {
  19076. if (me.fireEvent("excludetable", table) === true) return;
  19077. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19078. } else if (inTableSide(table, target, evt)) {
  19079. if (me.fireEvent("excludetable", table) === true) return;
  19080. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19081. } else {
  19082. me.body.style.cursor = "text";
  19083. var curCell = target;
  19084. if (/\d/.test(state)) {
  19085. state = state.replace(/\d/, '');
  19086. target = getUETable(target).getPreviewCell(target, state == "v");
  19087. }
  19088. //位于第一行的顶部或者第一列的左边时不可拖动
  19089. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19090. }
  19091. } else {
  19092. toggleDragButton(false, table, me);
  19093. }
  19094. } catch (e) {
  19095. showError(e);
  19096. }
  19097. }
  19098. var dragButtonTimer;
  19099. function toggleDragButton(show, table, editor) {
  19100. if (!show) {
  19101. if (dragOver)return;
  19102. dragButtonTimer = setTimeout(function () {
  19103. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19104. }, 2000);
  19105. } else {
  19106. createDragButton(table, editor);
  19107. }
  19108. }
  19109. function createDragButton(table, editor) {
  19110. var pos = domUtils.getXY(table),
  19111. doc = table.ownerDocument;
  19112. if (dragButton && dragButton.parentNode)return dragButton;
  19113. dragButton = doc.createElement("div");
  19114. dragButton.contentEditable = false;
  19115. dragButton.innerHTML = "";
  19116. 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;";
  19117. domUtils.unSelectable(dragButton);
  19118. dragButton.onmouseover = function (evt) {
  19119. dragOver = true;
  19120. };
  19121. dragButton.onmouseout = function (evt) {
  19122. dragOver = false;
  19123. };
  19124. domUtils.on(dragButton, 'click', function (type, evt) {
  19125. doClick(evt, this);
  19126. });
  19127. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19128. doDblClick(evt);
  19129. });
  19130. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19131. domUtils.preventDefault(evt);
  19132. });
  19133. var timer;
  19134. function doClick(evt, button) {
  19135. // 部分浏览器下需要清理
  19136. clearTimeout(timer);
  19137. timer = setTimeout(function () {
  19138. editor.fireEvent("tableClicked", table, button);
  19139. }, 300);
  19140. }
  19141. function doDblClick(evt) {
  19142. clearTimeout(timer);
  19143. var ut = getUETable(table),
  19144. start = table.rows[0].cells[0],
  19145. end = ut.getLastCell(),
  19146. range = ut.getCellsRange(start, end);
  19147. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19148. ut.setSelected(range);
  19149. }
  19150. doc.body.appendChild(dragButton);
  19151. }
  19152. // function inPosition(table, pos) {
  19153. // var tablePos = domUtils.getXY(table),
  19154. // width = table.offsetWidth,
  19155. // height = table.offsetHeight;
  19156. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19157. // return "topLeft";
  19158. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19159. // return "bottomRight";
  19160. // }
  19161. // }
  19162. function inTableSide(table, cell, evt, top) {
  19163. var pos = mouseCoords(evt),
  19164. state = getRelation(cell, pos);
  19165. if (top) {
  19166. var caption = table.getElementsByTagName("caption")[0],
  19167. capHeight = caption ? caption.offsetHeight : 0;
  19168. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19169. } else {
  19170. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19171. }
  19172. }
  19173. /**
  19174. * 获取拖动时允许的X轴坐标
  19175. * @param dragTd
  19176. * @param evt
  19177. */
  19178. function getPermissionX(dragTd, evt) {
  19179. var ut = getUETable(dragTd);
  19180. if (ut) {
  19181. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19182. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19183. mouseX = mouseCoords(evt).x,
  19184. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19185. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19186. left += cellMinWidth;
  19187. right -= cellMinWidth;
  19188. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19189. }
  19190. }
  19191. /**
  19192. * 获取拖动时允许的Y轴坐标
  19193. */
  19194. function getPermissionY(dragTd, evt) {
  19195. try {
  19196. var top = domUtils.getXY(dragTd).y,
  19197. mousePosY = mouseCoords(evt).y;
  19198. return mousePosY < top ? top : mousePosY;
  19199. } catch (e) {
  19200. showError(e);
  19201. }
  19202. }
  19203. /**
  19204. * 移动状态切换
  19205. */
  19206. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19207. try {
  19208. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19209. if (browser.ie) {
  19210. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19211. getDragLine(editor, editor.document);
  19212. showDragLineAt(dir, cell);
  19213. } else {
  19214. hideDragLine(editor)
  19215. }
  19216. }
  19217. onBorder = draggable;
  19218. } catch (e) {
  19219. showError(e);
  19220. }
  19221. }
  19222. /**
  19223. * 获取与UETable相关的resize line
  19224. * @param uetable UETable对象
  19225. */
  19226. function getResizeLineByUETable() {
  19227. var lineId = '_UETableResizeLine',
  19228. line = this.document.getElementById( lineId );
  19229. if( !line ) {
  19230. line = this.document.createElement("div");
  19231. line.id = lineId;
  19232. line.contnetEditable = false;
  19233. line.setAttribute("unselectable", "on");
  19234. var styles = {
  19235. width: 2*cellBorderWidth + 1 + 'px',
  19236. position: 'absolute',
  19237. 'z-index': 100000,
  19238. cursor: 'col-resize',
  19239. background: 'red',
  19240. display: 'none'
  19241. };
  19242. //切换状态
  19243. line.onmouseout = function(){
  19244. this.style.display = 'none';
  19245. };
  19246. utils.extend( line.style, styles );
  19247. this.document.body.appendChild( line );
  19248. }
  19249. return line;
  19250. }
  19251. /**
  19252. * 更新resize-line
  19253. */
  19254. function updateResizeLine( cell, uetable ) {
  19255. var line = getResizeLineByUETable.call( this ),
  19256. table = uetable.table,
  19257. styles = {
  19258. top: domUtils.getXY( table ).y + 'px',
  19259. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19260. display: 'block',
  19261. height: table.offsetHeight + 'px'
  19262. };
  19263. utils.extend( line.style, styles );
  19264. }
  19265. /**
  19266. * 显示resize-line
  19267. */
  19268. function showResizeLine( cell ) {
  19269. var uetable = getUETable( cell );
  19270. updateResizeLine.call( this, cell, uetable );
  19271. }
  19272. /**
  19273. * 获取鼠标与当前单元格的相对位置
  19274. * @param ele
  19275. * @param mousePos
  19276. */
  19277. function getRelation(ele, mousePos) {
  19278. var elePos = domUtils.getXY(ele);
  19279. if( !elePos ) {
  19280. return '';
  19281. }
  19282. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19283. return "h";
  19284. }
  19285. if (mousePos.x - elePos.x < cellBorderWidth) {
  19286. return 'h1'
  19287. }
  19288. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19289. return "v";
  19290. }
  19291. if (mousePos.y - elePos.y < cellBorderWidth) {
  19292. return 'v1'
  19293. }
  19294. return '';
  19295. }
  19296. function mouseDownEvent(type, evt) {
  19297. if( isEditorDisabled() ) {
  19298. return ;
  19299. }
  19300. userActionStatus = {
  19301. x: evt.clientX,
  19302. y: evt.clientY
  19303. };
  19304. //右键菜单单独处理
  19305. if (evt.button == 2) {
  19306. var ut = getUETableBySelected(me),
  19307. flag = false;
  19308. if (ut) {
  19309. var td = getTargetTd(me, evt);
  19310. utils.each(ut.selectedTds, function (ti) {
  19311. if (ti === td) {
  19312. flag = true;
  19313. }
  19314. });
  19315. if (!flag) {
  19316. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19317. ut.clearSelected()
  19318. } else {
  19319. td = ut.selectedTds[0];
  19320. setTimeout(function () {
  19321. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19322. }, 0);
  19323. }
  19324. }
  19325. } else {
  19326. tableClickHander( evt );
  19327. }
  19328. }
  19329. //清除表格的计时器
  19330. function clearTableTimer() {
  19331. tabTimer && clearTimeout( tabTimer );
  19332. tabTimer = null;
  19333. }
  19334. //双击收缩
  19335. function tableDbclickHandler(evt) {
  19336. singleClickState = 0;
  19337. evt = evt || me.window.event;
  19338. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19339. if (target) {
  19340. var h;
  19341. if (h = getRelation(target, mouseCoords(evt))) {
  19342. hideDragLine( me );
  19343. if (h == 'h1') {
  19344. h = 'h';
  19345. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19346. me.execCommand('adaptbywindow');
  19347. } else {
  19348. target = getUETable(target).getPreviewCell(target);
  19349. if (target) {
  19350. var rng = me.selection.getRange();
  19351. rng.selectNodeContents(target).setCursor(true, true)
  19352. }
  19353. }
  19354. }
  19355. if (h == 'h') {
  19356. var ut = getUETable(target),
  19357. table = ut.table,
  19358. cells = getCellsByMoveBorder( target, table, true );
  19359. cells = extractArray( cells, 'left' );
  19360. ut.width = ut.offsetWidth;
  19361. var oldWidth = [],
  19362. newWidth = [];
  19363. utils.each( cells, function( cell ){
  19364. oldWidth.push( cell.offsetWidth );
  19365. } );
  19366. utils.each( cells, function( cell ){
  19367. cell.removeAttribute("width");
  19368. } );
  19369. window.setTimeout( function(){
  19370. //是否允许改变
  19371. var changeable = true;
  19372. utils.each( cells, function( cell, index ){
  19373. var width = cell.offsetWidth;
  19374. if( width > oldWidth[index] ) {
  19375. changeable = false;
  19376. return false;
  19377. }
  19378. newWidth.push( width );
  19379. } );
  19380. var change = changeable ? newWidth : oldWidth;
  19381. utils.each( cells, function( cell, index ){
  19382. cell.width = change[index] - getTabcellSpace();
  19383. } );
  19384. }, 0 );
  19385. // minWidth -= cellMinWidth;
  19386. //
  19387. // table.removeAttribute("width");
  19388. // utils.each(cells, function (cell) {
  19389. // cell.style.width = "";
  19390. // cell.width -= minWidth;
  19391. // });
  19392. }
  19393. }
  19394. }
  19395. }
  19396. function tableClickHander( evt ) {
  19397. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19398. //trace:3113
  19399. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19400. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19401. t.ueTable = null;
  19402. });
  19403. startTd = getTargetTd(me, evt);
  19404. if( !startTd ) return;
  19405. var table = domUtils.findParentByTagName(startTd, "table", true);
  19406. ut = getUETable(table);
  19407. ut && ut.clearSelected();
  19408. //判断当前鼠标状态
  19409. if (!onBorder) {
  19410. me.document.body.style.webkitUserSelect = '';
  19411. mousedown = true;
  19412. me.addListener('mouseover', mouseOverEvent);
  19413. } else {
  19414. //边框上的动作处理
  19415. borderActionHandler( evt );
  19416. }
  19417. }
  19418. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19419. function borderActionHandler( evt ) {
  19420. if ( browser.ie ) {
  19421. evt = reconstruct(evt );
  19422. }
  19423. clearTableDragTimer();
  19424. //是否正在等待resize的缓冲中
  19425. isInResizeBuffer = true;
  19426. tableDragTimer = setTimeout(function(){
  19427. tableBorderDrag( evt );
  19428. }, dblclickTime);
  19429. }
  19430. function extractArray( originArr, key ) {
  19431. var result = [],
  19432. tmp = null;
  19433. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19434. tmp = originArr[ i ][ key ];
  19435. if( tmp ) {
  19436. result.push( tmp );
  19437. }
  19438. }
  19439. return result;
  19440. }
  19441. function clearTableDragTimer() {
  19442. tableDragTimer && clearTimeout(tableDragTimer);
  19443. tableDragTimer = null;
  19444. }
  19445. function reconstruct( obj ) {
  19446. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19447. newObj = {};
  19448. if( obj ) {
  19449. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19450. val=obj[ key ];
  19451. val && (newObj[ key ] = val);
  19452. }
  19453. }
  19454. return newObj;
  19455. }
  19456. //边框拖动
  19457. function tableBorderDrag( evt ) {
  19458. isInResizeBuffer = false;
  19459. startTd = evt.target || evt.srcElement;
  19460. if( !startTd ) return;
  19461. var state = getRelation(startTd, mouseCoords(evt));
  19462. if (/\d/.test(state)) {
  19463. state = state.replace(/\d/, '');
  19464. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19465. }
  19466. hideDragLine(me);
  19467. getDragLine(me, me.document);
  19468. me.fireEvent('saveScene');
  19469. showDragLineAt(state, startTd);
  19470. mousedown = true;
  19471. //拖动开始
  19472. onDrag = state;
  19473. dragTd = startTd;
  19474. }
  19475. function mouseUpEvent(type, evt) {
  19476. if( isEditorDisabled() ) {
  19477. return ;
  19478. }
  19479. clearTableDragTimer();
  19480. isInResizeBuffer = false;
  19481. if( onBorder ) {
  19482. singleClickState = ++singleClickState % 3;
  19483. userActionStatus = {
  19484. x: evt.clientX,
  19485. y: evt.clientY
  19486. };
  19487. tableResizeTimer = setTimeout(function(){
  19488. singleClickState > 0 && singleClickState--;
  19489. }, dblclickTime );
  19490. if( singleClickState === 2 ) {
  19491. singleClickState = 0;
  19492. tableDbclickHandler(evt);
  19493. return;
  19494. }
  19495. }
  19496. if (evt.button == 2)return;
  19497. var me = this;
  19498. //清除表格上原生跨选问题
  19499. var range = me.selection.getRange(),
  19500. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19501. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19502. if (start || end) {
  19503. if (start === end) {
  19504. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19505. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19506. if (start !== end) {
  19507. me.selection.clearRange()
  19508. }
  19509. } else {
  19510. me.selection.clearRange()
  19511. }
  19512. }
  19513. mousedown = false;
  19514. me.document.body.style.webkitUserSelect = '';
  19515. //拖拽状态下的mouseUP
  19516. if ( onDrag && dragTd ) {
  19517. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19518. singleClickState = 0;
  19519. dragLine = me.document.getElementById('ue_tableDragLine');
  19520. // trace 3973
  19521. if (dragLine) {
  19522. var dragTdPos = domUtils.getXY(dragTd),
  19523. dragLinePos = domUtils.getXY(dragLine);
  19524. switch (onDrag) {
  19525. case "h":
  19526. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19527. break;
  19528. case "v":
  19529. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19530. break;
  19531. default:
  19532. }
  19533. onDrag = "";
  19534. dragTd = null;
  19535. hideDragLine(me);
  19536. me.fireEvent('saveScene');
  19537. return;
  19538. }
  19539. }
  19540. //正常状态下的mouseup
  19541. if (!startTd) {
  19542. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19543. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19544. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19545. if (me.fireEvent("excludetable", target) === true) return;
  19546. range = new dom.Range(me.document);
  19547. range.setStart(target, 0).setCursor(false, true);
  19548. }
  19549. } else {
  19550. var ut = getUETable(startTd),
  19551. cell = ut ? ut.selectedTds[0] : null;
  19552. if (cell) {
  19553. range = new dom.Range(me.document);
  19554. if (domUtils.isEmptyBlock(cell)) {
  19555. range.setStart(cell, 0).setCursor(false, true);
  19556. } else {
  19557. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19558. }
  19559. } else {
  19560. range = me.selection.getRange().shrinkBoundary();
  19561. if (!range.collapsed) {
  19562. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19563. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19564. //在table里边的不能清除
  19565. if (start && !end || !start && end || start && end && start !== end) {
  19566. range.setCursor(false, true);
  19567. }
  19568. }
  19569. }
  19570. startTd = null;
  19571. me.removeListener('mouseover', mouseOverEvent);
  19572. }
  19573. me._selectionChange(250, evt);
  19574. }
  19575. function mouseOverEvent(type, evt) {
  19576. if( isEditorDisabled() ) {
  19577. return;
  19578. }
  19579. var me = this,
  19580. tar = evt.target || evt.srcElement;
  19581. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19582. //需要判断两个TD是否位于同一个表格内
  19583. if (startTd && currentTd &&
  19584. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19585. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19586. var ut = getUETable(currentTd);
  19587. if (startTd != currentTd) {
  19588. me.document.body.style.webkitUserSelect = 'none';
  19589. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19590. var range = ut.getCellsRange(startTd, currentTd);
  19591. ut.setSelected(range);
  19592. } else {
  19593. me.document.body.style.webkitUserSelect = '';
  19594. ut.clearSelected();
  19595. }
  19596. }
  19597. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19598. }
  19599. function setCellHeight(cell, height, backHeight) {
  19600. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19601. tmpHeight = backHeight + height;
  19602. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19603. if (cell.style.height) cell.style.height = "";
  19604. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19605. }
  19606. function getWidth(cell) {
  19607. if (!cell)return 0;
  19608. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19609. }
  19610. function changeColWidth(cell, changeValue) {
  19611. var ut = getUETable(cell);
  19612. if (ut) {
  19613. //根据当前移动的边框获取相关的单元格
  19614. var table = ut.table,
  19615. cells = getCellsByMoveBorder( cell, table );
  19616. table.style.width = "";
  19617. table.removeAttribute("width");
  19618. //修正改变量
  19619. changeValue = correctChangeValue( changeValue, cell, cells );
  19620. if (cell.nextSibling) {
  19621. var i=0;
  19622. utils.each( cells, function( cellGroup ){
  19623. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19624. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19625. } );
  19626. } else {
  19627. utils.each( cells, function( cellGroup ){
  19628. cellGroup.left.width -= -changeValue;
  19629. } );
  19630. }
  19631. }
  19632. }
  19633. function isEditorDisabled() {
  19634. return me.body.contentEditable === "false";
  19635. }
  19636. function changeRowHeight(td, changeValue) {
  19637. if (Math.abs(changeValue) < 10) return;
  19638. var ut = getUETable(td);
  19639. if (ut) {
  19640. var cells = ut.getSameEndPosCells(td, "y"),
  19641. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19642. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19643. for (var i = 0, cell; cell = cells[i++];) {
  19644. setCellHeight(cell, changeValue, backHeight);
  19645. }
  19646. }
  19647. }
  19648. /**
  19649. * 获取调整单元格大小的相关单元格
  19650. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19651. */
  19652. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19653. if( !table ) {
  19654. table = domUtils.findParentByTagName( cell, 'table' );
  19655. }
  19656. if( !table ) {
  19657. return null;
  19658. }
  19659. //获取到该单元格所在行的序列号
  19660. var index = domUtils.getNodeIndex( cell ),
  19661. temp = cell,
  19662. rows = table.rows,
  19663. colIndex = 0;
  19664. while( temp ) {
  19665. //获取到当前单元格在未发生单元格合并时的序列
  19666. if( temp.nodeType === 1 ) {
  19667. colIndex += (temp.colSpan || 1);
  19668. }
  19669. temp = temp.previousSibling;
  19670. }
  19671. temp = null;
  19672. //记录想关的单元格
  19673. var borderCells = [];
  19674. utils.each(rows, function( tabRow ){
  19675. var cells = tabRow.cells,
  19676. currIndex = 0;
  19677. utils.each( cells, function( tabCell ){
  19678. currIndex += (tabCell.colSpan || 1);
  19679. if( currIndex === colIndex ) {
  19680. borderCells.push({
  19681. left: tabCell,
  19682. right: tabCell.nextSibling || null
  19683. });
  19684. return false;
  19685. } else if( currIndex > colIndex ) {
  19686. if( isContainMergeCell ) {
  19687. borderCells.push({
  19688. left: tabCell
  19689. });
  19690. }
  19691. return false;
  19692. }
  19693. } );
  19694. });
  19695. return borderCells;
  19696. }
  19697. /**
  19698. * 通过给定的单元格集合获取最小的单元格width
  19699. */
  19700. function getMinWidthByTableCells( cells ) {
  19701. var minWidth = Number.MAX_VALUE;
  19702. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19703. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19704. }
  19705. return minWidth;
  19706. }
  19707. function correctChangeValue( changeValue, relatedCell, cells ) {
  19708. //为单元格的paading预留空间
  19709. changeValue -= getTabcellSpace();
  19710. if( changeValue < 0 ) {
  19711. return 0;
  19712. }
  19713. changeValue -= getTableCellWidth( relatedCell );
  19714. //确定方向
  19715. var direction = changeValue < 0 ? 'left':'right';
  19716. changeValue = Math.abs(changeValue);
  19717. //只关心非最后一个单元格就可以
  19718. utils.each( cells, function( cellGroup ){
  19719. var curCell = cellGroup[direction];
  19720. //为单元格保留最小空间
  19721. if( curCell ) {
  19722. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19723. }
  19724. } );
  19725. //修正越界
  19726. changeValue = changeValue < 0 ? 0 : changeValue;
  19727. return direction === 'left' ? -changeValue : changeValue;
  19728. }
  19729. function getTableCellWidth( cell ) {
  19730. var width = 0,
  19731. //偏移纠正量
  19732. offset = 0,
  19733. width = cell.offsetWidth - getTabcellSpace();
  19734. //最后一个节点纠正一下
  19735. if( !cell.nextSibling ) {
  19736. width -= getTableCellOffset( cell );
  19737. }
  19738. width = width < 0 ? 0 : width;
  19739. try {
  19740. cell.width = width;
  19741. } catch(e) {
  19742. }
  19743. return width;
  19744. }
  19745. /**
  19746. * 获取单元格所在表格的最末单元格的偏移量
  19747. */
  19748. function getTableCellOffset( cell ) {
  19749. tab = domUtils.findParentByTagName( cell, "table", false);
  19750. if( tab.offsetVal === undefined ) {
  19751. var prev = cell.previousSibling;
  19752. if( prev ) {
  19753. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19754. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19755. } else {
  19756. tab.offsetVal = 0;
  19757. }
  19758. }
  19759. return tab.offsetVal;
  19760. }
  19761. function getTabcellSpace() {
  19762. if( UT.tabcellSpace === undefined ) {
  19763. var cell = null,
  19764. tab = me.document.createElement("table"),
  19765. tbody = me.document.createElement("tbody"),
  19766. trow = me.document.createElement("tr"),
  19767. tabcell = me.document.createElement("td"),
  19768. mirror = null;
  19769. tabcell.style.cssText = 'border: 0;';
  19770. tabcell.width = 1;
  19771. trow.appendChild( tabcell );
  19772. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19773. tbody.appendChild( trow );
  19774. tab.appendChild( tbody );
  19775. tab.style.cssText = "visibility: hidden;";
  19776. me.body.appendChild( tab );
  19777. UT.paddingSpace = tabcell.offsetWidth - 1;
  19778. var tmpTabWidth = tab.offsetWidth;
  19779. tabcell.style.cssText = '';
  19780. mirror.style.cssText = '';
  19781. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19782. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19783. me.body.removeChild( tab );
  19784. }
  19785. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19786. return UT.tabcellSpace;
  19787. }
  19788. function getDragLine(editor, doc) {
  19789. if (mousedown)return;
  19790. dragLine = editor.document.createElement("div");
  19791. domUtils.setAttributes(dragLine, {
  19792. id:"ue_tableDragLine",
  19793. unselectable:'on',
  19794. contenteditable:false,
  19795. 'onresizestart':'return false',
  19796. 'ondragstart':'return false',
  19797. 'onselectstart':'return false',
  19798. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19799. });
  19800. editor.body.appendChild(dragLine);
  19801. }
  19802. function hideDragLine(editor) {
  19803. if (mousedown)return;
  19804. var line;
  19805. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19806. domUtils.remove(line)
  19807. }
  19808. }
  19809. /**
  19810. * 依据state(v|h)在cell位置显示横线
  19811. * @param state
  19812. * @param cell
  19813. */
  19814. function showDragLineAt(state, cell) {
  19815. if (!cell) return;
  19816. var table = domUtils.findParentByTagName(cell, "table"),
  19817. caption = table.getElementsByTagName('caption'),
  19818. width = table.offsetWidth,
  19819. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19820. tablePos = domUtils.getXY(table),
  19821. cellPos = domUtils.getXY(cell), css;
  19822. switch (state) {
  19823. case "h":
  19824. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19825. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19826. break;
  19827. case "v":
  19828. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19829. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19830. dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)';
  19831. break;
  19832. default:
  19833. }
  19834. }
  19835. /**
  19836. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19837. * @param editor
  19838. * @param flag
  19839. */
  19840. function switchBorderColor(editor, flag) {
  19841. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19842. for (var i = 0, node; node = tableArr[i++];) {
  19843. var td = domUtils.getElementsByTagName(node, "td");
  19844. if (td[0]) {
  19845. if (flag) {
  19846. color = (td[0].style.borderColor).replace(/\s/g, "");
  19847. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19848. domUtils.addClass(node, "noBorderTable")
  19849. } else {
  19850. domUtils.removeClasses(node, "noBorderTable")
  19851. }
  19852. }
  19853. }
  19854. }
  19855. function getTableWidth(editor, needIEHack, defaultValue) {
  19856. var body = editor.body;
  19857. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19858. }
  19859. /**
  19860. * 获取当前拖动的单元格
  19861. */
  19862. function getTargetTd(editor, evt) {
  19863. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19864. dir = null;
  19865. if( !target ) {
  19866. return null;
  19867. }
  19868. dir = getRelation( target, mouseCoords( evt ) );
  19869. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19870. if( !target ) {
  19871. return null;
  19872. }
  19873. if( dir === 'h1' && target.previousSibling ) {
  19874. var position = domUtils.getXY( target),
  19875. cellWidth = target.offsetWidth;
  19876. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19877. target = target.previousSibling;
  19878. }
  19879. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19880. var position = domUtils.getXY( target),
  19881. cellHeight = target.offsetHeight;
  19882. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19883. target = target.parentNode.previousSibling.firstChild;
  19884. }
  19885. }
  19886. //排除了非td内部以及用于代码高亮部分的td
  19887. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19888. }
  19889. };
  19890. // plugins/table.sort.js
  19891. /**
  19892. * Created with JetBrains PhpStorm.
  19893. * User: Jinqn
  19894. * Date: 13-10-12
  19895. * Time: 上午10:20
  19896. * To change this template use File | Settings | File Templates.
  19897. */
  19898. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19899. var table = this.table,
  19900. rows = table.rows,
  19901. trArray = [],
  19902. flag = rows[0].cells[0].tagName === "TH",
  19903. lastRowIndex = 0;
  19904. if(this.selectedTds.length){
  19905. var range = this.cellsRange,
  19906. len = range.endRowIndex + 1;
  19907. for (var i = range.beginRowIndex; i < len; i++) {
  19908. trArray[i] = rows[i];
  19909. }
  19910. trArray.splice(0,range.beginRowIndex);
  19911. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19912. }else{
  19913. for (var i = 0,len = rows.length; i < len; i++) {
  19914. trArray[i] = rows[i];
  19915. }
  19916. }
  19917. var Fn = {
  19918. 'reversecurrent': function(td1,td2){
  19919. return 1;
  19920. },
  19921. 'orderbyasc': function(td1,td2){
  19922. var value1 = td1.innerText||td1.textContent,
  19923. value2 = td2.innerText||td2.textContent;
  19924. return value1.localeCompare(value2);
  19925. },
  19926. 'reversebyasc': function(td1,td2){
  19927. var value1 = td1.innerHTML,
  19928. value2 = td2.innerHTML;
  19929. return value2.localeCompare(value1);
  19930. },
  19931. 'orderbynum': function(td1,td2){
  19932. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19933. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19934. if(value1) value1 = +value1[0];
  19935. if(value2) value2 = +value2[0];
  19936. return (value1||0) - (value2||0);
  19937. },
  19938. 'reversebynum': function(td1,td2){
  19939. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19940. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19941. if(value1) value1 = +value1[0];
  19942. if(value2) value2 = +value2[0];
  19943. return (value2||0) - (value1||0);
  19944. }
  19945. };
  19946. //对表格设置排序的标记data-sort-type
  19947. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19948. //th不参与排序
  19949. flag && trArray.splice(0, 1);
  19950. trArray = utils.sort(trArray,function (tr1, tr2) {
  19951. var result;
  19952. if (compareFn && typeof compareFn === "function") {
  19953. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19954. } else if (compareFn && typeof compareFn === "number") {
  19955. result = 1;
  19956. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19957. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19958. } else {
  19959. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19960. }
  19961. return result;
  19962. });
  19963. var fragment = table.ownerDocument.createDocumentFragment();
  19964. for (var j = 0, len = trArray.length; j < len; j++) {
  19965. fragment.appendChild(trArray[j]);
  19966. }
  19967. var tbody = table.getElementsByTagName("tbody")[0];
  19968. if(!lastRowIndex){
  19969. tbody.appendChild(fragment);
  19970. }else{
  19971. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  19972. }
  19973. };
  19974. UE.plugins['tablesort'] = function () {
  19975. var me = this,
  19976. UT = UE.UETable,
  19977. getUETable = function (tdOrTable) {
  19978. return UT.getUETable(tdOrTable);
  19979. },
  19980. getTableItemsByRange = function (editor) {
  19981. return UT.getTableItemsByRange(editor);
  19982. };
  19983. me.ready(function () {
  19984. //添加表格可排序的样式
  19985. utils.cssRule('tablesort',
  19986. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  19987. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  19988. me.document);
  19989. //做单元格合并操作时,清除可排序标识
  19990. me.addListener("afterexeccommand", function (type, cmd) {
  19991. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  19992. this.execCommand('disablesort');
  19993. }
  19994. });
  19995. });
  19996. //表格排序
  19997. UE.commands['sorttable'] = {
  19998. queryCommandState: function () {
  19999. var me = this,
  20000. tableItems = getTableItemsByRange(me);
  20001. if (!tableItems.cell) return -1;
  20002. var table = tableItems.table,
  20003. cells = table.getElementsByTagName("td");
  20004. for (var i = 0, cell; cell = cells[i++];) {
  20005. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20006. }
  20007. return 0;
  20008. },
  20009. execCommand: function (cmd, fn) {
  20010. var me = this,
  20011. range = me.selection.getRange(),
  20012. bk = range.createBookmark(true),
  20013. tableItems = getTableItemsByRange(me),
  20014. cell = tableItems.cell,
  20015. ut = getUETable(tableItems.table),
  20016. cellInfo = ut.getCellInfo(cell);
  20017. ut.sortTable(cellInfo.cellIndex, fn);
  20018. range.moveToBookmark(bk);
  20019. try{
  20020. range.select();
  20021. }catch(e){}
  20022. }
  20023. };
  20024. //设置表格可排序,清除表格可排序
  20025. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20026. queryCommandState: function (cmd) {
  20027. var table = getTableItemsByRange(this).table;
  20028. if(table && cmd=='enablesort') {
  20029. var cells = domUtils.getElementsByTagName(table, 'th td');
  20030. for(var i = 0; i<cells.length; i++) {
  20031. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20032. }
  20033. }
  20034. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20035. },
  20036. execCommand: function (cmd) {
  20037. var table = getTableItemsByRange(this).table;
  20038. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20039. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20040. }
  20041. };
  20042. };
  20043. // plugins/contextmenu.js
  20044. ///import core
  20045. ///commands 右键菜单
  20046. ///commandsName ContextMenu
  20047. ///commandsTitle 右键菜单
  20048. /**
  20049. * 右键菜单
  20050. * @function
  20051. * @name baidu.editor.plugins.contextmenu
  20052. * @author zhanyi
  20053. */
  20054. UE.plugins['contextmenu'] = function () {
  20055. var me = this;
  20056. me.setOpt('enableContextMenu',true);
  20057. if(me.getOpt('enableContextMenu') === false){
  20058. return;
  20059. }
  20060. var lang = me.getLang( "contextMenu" ),
  20061. menu,
  20062. items = me.options.contextMenu || [
  20063. {label:lang['selectall'], cmdName:'selectall'},
  20064. {
  20065. label:lang.cleardoc,
  20066. cmdName:'cleardoc',
  20067. exec:function () {
  20068. if ( confirm( lang.confirmclear ) ) {
  20069. this.execCommand( 'cleardoc' );
  20070. }
  20071. }
  20072. },
  20073. '-',
  20074. {
  20075. label:lang.unlink,
  20076. cmdName:'unlink'
  20077. },
  20078. '-',
  20079. {
  20080. group:lang.paragraph,
  20081. icon:'justifyjustify',
  20082. subMenu:[
  20083. {
  20084. label:lang.justifyleft,
  20085. cmdName:'justify',
  20086. value:'left'
  20087. },
  20088. {
  20089. label:lang.justifyright,
  20090. cmdName:'justify',
  20091. value:'right'
  20092. },
  20093. {
  20094. label:lang.justifycenter,
  20095. cmdName:'justify',
  20096. value:'center'
  20097. },
  20098. {
  20099. label:lang.justifyjustify,
  20100. cmdName:'justify',
  20101. value:'justify'
  20102. }
  20103. ]
  20104. },
  20105. '-',
  20106. {
  20107. group:lang.table,
  20108. icon:'table',
  20109. subMenu:[
  20110. {
  20111. label:lang.inserttable,
  20112. cmdName:'inserttable'
  20113. },
  20114. {
  20115. label:lang.deletetable,
  20116. cmdName:'deletetable'
  20117. },
  20118. '-',
  20119. {
  20120. label:lang.deleterow,
  20121. cmdName:'deleterow'
  20122. },
  20123. {
  20124. label:lang.deletecol,
  20125. cmdName:'deletecol'
  20126. },
  20127. {
  20128. label:lang.insertcol,
  20129. cmdName:'insertcol'
  20130. },
  20131. {
  20132. label:lang.insertcolnext,
  20133. cmdName:'insertcolnext'
  20134. },
  20135. {
  20136. label:lang.insertrow,
  20137. cmdName:'insertrow'
  20138. },
  20139. {
  20140. label:lang.insertrownext,
  20141. cmdName:'insertrownext'
  20142. },
  20143. '-',
  20144. {
  20145. label:lang.insertcaption,
  20146. cmdName:'insertcaption'
  20147. },
  20148. {
  20149. label:lang.deletecaption,
  20150. cmdName:'deletecaption'
  20151. },
  20152. {
  20153. label:lang.inserttitle,
  20154. cmdName:'inserttitle'
  20155. },
  20156. {
  20157. label:lang.deletetitle,
  20158. cmdName:'deletetitle'
  20159. },
  20160. {
  20161. label:lang.inserttitlecol,
  20162. cmdName:'inserttitlecol'
  20163. },
  20164. {
  20165. label:lang.deletetitlecol,
  20166. cmdName:'deletetitlecol'
  20167. },
  20168. '-',
  20169. {
  20170. label:lang.mergecells,
  20171. cmdName:'mergecells'
  20172. },
  20173. {
  20174. label:lang.mergeright,
  20175. cmdName:'mergeright'
  20176. },
  20177. {
  20178. label:lang.mergedown,
  20179. cmdName:'mergedown'
  20180. },
  20181. '-',
  20182. {
  20183. label:lang.splittorows,
  20184. cmdName:'splittorows'
  20185. },
  20186. {
  20187. label:lang.splittocols,
  20188. cmdName:'splittocols'
  20189. },
  20190. {
  20191. label:lang.splittocells,
  20192. cmdName:'splittocells'
  20193. },
  20194. '-',
  20195. {
  20196. label:lang.averageDiseRow,
  20197. cmdName:'averagedistributerow'
  20198. },
  20199. {
  20200. label:lang.averageDisCol,
  20201. cmdName:'averagedistributecol'
  20202. },
  20203. '-',
  20204. {
  20205. label:lang.edittd,
  20206. cmdName:'edittd',
  20207. exec:function () {
  20208. if ( UE.ui['edittd'] ) {
  20209. new UE.ui['edittd']( this );
  20210. }
  20211. this.getDialog('edittd').open();
  20212. }
  20213. },
  20214. {
  20215. label:lang.edittable,
  20216. cmdName:'edittable',
  20217. exec:function () {
  20218. if ( UE.ui['edittable'] ) {
  20219. new UE.ui['edittable']( this );
  20220. }
  20221. this.getDialog('edittable').open();
  20222. }
  20223. },
  20224. {
  20225. label:lang.setbordervisible,
  20226. cmdName:'setbordervisible'
  20227. }
  20228. ]
  20229. },
  20230. {
  20231. group:lang.tablesort,
  20232. icon:'tablesort',
  20233. subMenu:[
  20234. {
  20235. label:lang.enablesort,
  20236. cmdName:'enablesort'
  20237. },
  20238. {
  20239. label:lang.disablesort,
  20240. cmdName:'disablesort'
  20241. },
  20242. '-',
  20243. {
  20244. label:lang.reversecurrent,
  20245. cmdName:'sorttable',
  20246. value:'reversecurrent'
  20247. },
  20248. {
  20249. label:lang.orderbyasc,
  20250. cmdName:'sorttable',
  20251. value:'orderbyasc'
  20252. },
  20253. {
  20254. label:lang.reversebyasc,
  20255. cmdName:'sorttable',
  20256. value:'reversebyasc'
  20257. },
  20258. {
  20259. label:lang.orderbynum,
  20260. cmdName:'sorttable',
  20261. value:'orderbynum'
  20262. },
  20263. {
  20264. label:lang.reversebynum,
  20265. cmdName:'sorttable',
  20266. value:'reversebynum'
  20267. }
  20268. ]
  20269. },
  20270. {
  20271. group:lang.borderbk,
  20272. icon:'borderBack',
  20273. subMenu:[
  20274. {
  20275. label:lang.setcolor,
  20276. cmdName:"interlacetable",
  20277. exec:function(){
  20278. this.execCommand("interlacetable");
  20279. }
  20280. },
  20281. {
  20282. label:lang.unsetcolor,
  20283. cmdName:"uninterlacetable",
  20284. exec:function(){
  20285. this.execCommand("uninterlacetable");
  20286. }
  20287. },
  20288. {
  20289. label:lang.setbackground,
  20290. cmdName:"settablebackground",
  20291. exec:function(){
  20292. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20293. }
  20294. },
  20295. {
  20296. label:lang.unsetbackground,
  20297. cmdName:"cleartablebackground",
  20298. exec:function(){
  20299. this.execCommand("cleartablebackground");
  20300. }
  20301. },
  20302. {
  20303. label:lang.redandblue,
  20304. cmdName:"settablebackground",
  20305. exec:function(){
  20306. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20307. }
  20308. },
  20309. {
  20310. label:lang.threecolorgradient,
  20311. cmdName:"settablebackground",
  20312. exec:function(){
  20313. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20314. }
  20315. }
  20316. ]
  20317. },
  20318. {
  20319. group:lang.aligntd,
  20320. icon:'aligntd',
  20321. subMenu:[
  20322. {
  20323. cmdName:'cellalignment',
  20324. value:{align:'left',vAlign:'top'}
  20325. },
  20326. {
  20327. cmdName:'cellalignment',
  20328. value:{align:'center',vAlign:'top'}
  20329. },
  20330. {
  20331. cmdName:'cellalignment',
  20332. value:{align:'right',vAlign:'top'}
  20333. },
  20334. {
  20335. cmdName:'cellalignment',
  20336. value:{align:'left',vAlign:'middle'}
  20337. },
  20338. {
  20339. cmdName:'cellalignment',
  20340. value:{align:'center',vAlign:'middle'}
  20341. },
  20342. {
  20343. cmdName:'cellalignment',
  20344. value:{align:'right',vAlign:'middle'}
  20345. },
  20346. {
  20347. cmdName:'cellalignment',
  20348. value:{align:'left',vAlign:'bottom'}
  20349. },
  20350. {
  20351. cmdName:'cellalignment',
  20352. value:{align:'center',vAlign:'bottom'}
  20353. },
  20354. {
  20355. cmdName:'cellalignment',
  20356. value:{align:'right',vAlign:'bottom'}
  20357. }
  20358. ]
  20359. },
  20360. {
  20361. group:lang.aligntable,
  20362. icon:'aligntable',
  20363. subMenu:[
  20364. {
  20365. cmdName:'tablealignment',
  20366. className: 'left',
  20367. label:lang.tableleft,
  20368. value:"left"
  20369. },
  20370. {
  20371. cmdName:'tablealignment',
  20372. className: 'center',
  20373. label:lang.tablecenter,
  20374. value:"center"
  20375. },
  20376. {
  20377. cmdName:'tablealignment',
  20378. className: 'right',
  20379. label:lang.tableright,
  20380. value:"right"
  20381. }
  20382. ]
  20383. },
  20384. '-',
  20385. {
  20386. label:lang.insertparagraphbefore,
  20387. cmdName:'insertparagraph',
  20388. value:true
  20389. },
  20390. {
  20391. label:lang.insertparagraphafter,
  20392. cmdName:'insertparagraph'
  20393. },
  20394. {
  20395. label:lang['copy'],
  20396. cmdName:'copy'
  20397. },
  20398. {
  20399. label:lang['paste'],
  20400. cmdName:'paste'
  20401. }
  20402. ];
  20403. if ( !items.length ) {
  20404. return;
  20405. }
  20406. var uiUtils = UE.ui.uiUtils;
  20407. me.addListener( 'contextmenu', function ( type, evt ) {
  20408. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20409. me.fireEvent( 'beforeselectionchange' );
  20410. if ( menu ) {
  20411. menu.destroy();
  20412. }
  20413. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20414. var last;
  20415. (function ( item ) {
  20416. if ( item == '-' ) {
  20417. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20418. contextItems.push( '-' );
  20419. }
  20420. } else if ( item.hasOwnProperty( "group" ) ) {
  20421. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20422. (function ( subItem ) {
  20423. if ( subItem == '-' ) {
  20424. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20425. subMenu.push( '-' );
  20426. }else{
  20427. subMenu.splice(subMenu.length-1);
  20428. }
  20429. } else {
  20430. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20431. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20432. subMenu.push( {
  20433. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20434. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20435. onclick:subItem.exec ? function () {
  20436. subItem.exec.call( me );
  20437. } : function () {
  20438. me.execCommand( subItem.cmdName, subItem.value );
  20439. }
  20440. } );
  20441. }
  20442. }
  20443. })( cj );
  20444. }
  20445. if ( subMenu.length ) {
  20446. function getLabel(){
  20447. switch (item.icon){
  20448. case "table":
  20449. return me.getLang( "contextMenu.table" );
  20450. case "justifyjustify":
  20451. return me.getLang( "contextMenu.paragraph" );
  20452. case "aligntd":
  20453. return me.getLang("contextMenu.aligntd");
  20454. case "aligntable":
  20455. return me.getLang("contextMenu.aligntable");
  20456. case "tablesort":
  20457. return lang.tablesort;
  20458. case "borderBack":
  20459. return lang.borderbk;
  20460. default :
  20461. return '';
  20462. }
  20463. }
  20464. contextItems.push( {
  20465. //todo 修正成自动获取方式
  20466. 'label':getLabel(),
  20467. className:'edui-for-' + item.icon,
  20468. 'subMenu':{
  20469. items:subMenu,
  20470. editor:me
  20471. }
  20472. } );
  20473. }
  20474. } else {
  20475. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20476. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20477. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20478. contextItems.push( {
  20479. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20480. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20481. onclick:item.exec ? function () {
  20482. item.exec.call( me );
  20483. } : function () {
  20484. me.execCommand( item.cmdName, item.value );
  20485. }
  20486. } );
  20487. }
  20488. }
  20489. })( ti );
  20490. }
  20491. if ( contextItems[contextItems.length - 1] == '-' ) {
  20492. contextItems.pop();
  20493. }
  20494. menu = new UE.ui.Menu( {
  20495. items:contextItems,
  20496. className:"edui-contextmenu",
  20497. editor:me
  20498. } );
  20499. menu.render();
  20500. menu.showAt( offset );
  20501. me.fireEvent("aftershowcontextmenu",menu);
  20502. domUtils.preventDefault( evt );
  20503. if ( browser.ie ) {
  20504. var ieRange;
  20505. try {
  20506. ieRange = me.selection.getNative().createRange();
  20507. } catch ( e ) {
  20508. return;
  20509. }
  20510. if ( ieRange.item ) {
  20511. var range = new dom.Range( me.document );
  20512. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20513. }
  20514. }
  20515. });
  20516. // 添加复制的flash按钮
  20517. me.addListener('aftershowcontextmenu', function(type, menu) {
  20518. if (me.zeroclipboard) {
  20519. var items = menu.items;
  20520. for (var key in items) {
  20521. if (items[key].className == 'edui-for-copy') {
  20522. me.zeroclipboard.clip(items[key].getDom());
  20523. }
  20524. }
  20525. }
  20526. });
  20527. };
  20528. // plugins/shortcutmenu.js
  20529. ///import core
  20530. ///commands 弹出菜单
  20531. // commandsName popupmenu
  20532. ///commandsTitle 弹出菜单
  20533. /**
  20534. * 弹出菜单
  20535. * @function
  20536. * @name baidu.editor.plugins.popupmenu
  20537. * @author xuheng
  20538. */
  20539. UE.plugins['shortcutmenu'] = function () {
  20540. var me = this,
  20541. menu,
  20542. items = me.options.shortcutMenu || [];
  20543. if (!items.length) {
  20544. return;
  20545. }
  20546. me.addListener ('contextmenu mouseup' , function (type , e) {
  20547. var me = this,
  20548. customEvt = {
  20549. type : type ,
  20550. target : e.target || e.srcElement ,
  20551. screenX : e.screenX ,
  20552. screenY : e.screenY ,
  20553. clientX : e.clientX ,
  20554. clientY : e.clientY
  20555. };
  20556. setTimeout (function () {
  20557. var rng = me.selection.getRange ();
  20558. if (rng.collapsed === false || type == "contextmenu") {
  20559. if (!menu) {
  20560. menu = new baidu.editor.ui.ShortCutMenu ({
  20561. editor : me ,
  20562. items : items ,
  20563. theme : me.options.theme ,
  20564. className : 'edui-shortcutmenu'
  20565. });
  20566. menu.render ();
  20567. me.fireEvent ("afterrendershortcutmenu" , menu);
  20568. }
  20569. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20570. }
  20571. });
  20572. if (type == 'contextmenu') {
  20573. domUtils.preventDefault (e);
  20574. if (browser.ie9below) {
  20575. var ieRange;
  20576. try {
  20577. ieRange = me.selection.getNative().createRange();
  20578. } catch (e) {
  20579. return;
  20580. }
  20581. if (ieRange.item) {
  20582. var range = new dom.Range (me.document);
  20583. range.selectNode (ieRange.item (0)).select (true , true);
  20584. }
  20585. }
  20586. }
  20587. });
  20588. me.addListener ('keydown' , function (type) {
  20589. if (type == "keydown") {
  20590. menu && !menu.isHidden && menu.hide ();
  20591. }
  20592. });
  20593. };
  20594. // plugins/basestyle.js
  20595. /**
  20596. * B、I、sub、super命令支持
  20597. * @file
  20598. * @since 1.2.6.1
  20599. */
  20600. UE.plugins['basestyle'] = function(){
  20601. /**
  20602. * 字体加粗
  20603. * @command bold
  20604. * @param { String } cmd 命令字符串
  20605. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20606. * @method execCommand
  20607. * @example
  20608. * ```javascript
  20609. * //editor是编辑器实例
  20610. * //对当前选中的文本内容执行加粗操作
  20611. * //第一次执行, 文本内容加粗
  20612. * editor.execCommand( 'bold' );
  20613. *
  20614. * //第二次执行, 文本内容取消加粗
  20615. * editor.execCommand( 'bold' );
  20616. * ```
  20617. */
  20618. /**
  20619. * 字体倾斜
  20620. * @command italic
  20621. * @method execCommand
  20622. * @param { String } cmd 命令字符串
  20623. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20624. * @example
  20625. * ```javascript
  20626. * //editor是编辑器实例
  20627. * //对当前选中的文本内容执行斜体操作
  20628. * //第一次操作, 文本内容将变成斜体
  20629. * editor.execCommand( 'italic' );
  20630. *
  20631. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20632. * editor.execCommand( 'italic' );
  20633. * ```
  20634. */
  20635. /**
  20636. * 下标文本,与“superscript”命令互斥
  20637. * @command subscript
  20638. * @method execCommand
  20639. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20640. * @param { String } cmd 命令字符串
  20641. * @example
  20642. * ```javascript
  20643. * //editor是编辑器实例
  20644. * //对当前选中的文本内容执行下标操作
  20645. * //第一次操作, 文本内容将变成下标文本
  20646. * editor.execCommand( 'subscript' );
  20647. *
  20648. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20649. * editor.execCommand( 'subscript' );
  20650. * ```
  20651. */
  20652. /**
  20653. * 上标文本,与“subscript”命令互斥
  20654. * @command superscript
  20655. * @method execCommand
  20656. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20657. * @param { String } cmd 命令字符串
  20658. * @example
  20659. * ```javascript
  20660. * //editor是编辑器实例
  20661. * //对当前选中的文本内容执行上标操作
  20662. * //第一次操作, 文本内容将变成上标文本
  20663. * editor.execCommand( 'superscript' );
  20664. *
  20665. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20666. * editor.execCommand( 'superscript' );
  20667. * ```
  20668. */
  20669. var basestyles = {
  20670. 'bold':['strong','b'],
  20671. 'italic':['em','i'],
  20672. 'subscript':['sub'],
  20673. 'superscript':['sup']
  20674. },
  20675. getObj = function(editor,tagNames){
  20676. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20677. },
  20678. me = this;
  20679. //添加快捷键
  20680. me.addshortcutkey({
  20681. "Bold" : "ctrl+66",//^B
  20682. "Italic" : "ctrl+73", //^I
  20683. "Underline" : "ctrl+85"//^U
  20684. });
  20685. me.addInputRule(function(root){
  20686. utils.each(root.getNodesByTagName('b i'),function(node){
  20687. switch (node.tagName){
  20688. case 'b':
  20689. node.tagName = 'strong';
  20690. break;
  20691. case 'i':
  20692. node.tagName = 'em';
  20693. }
  20694. });
  20695. });
  20696. for ( var style in basestyles ) {
  20697. (function( cmd, tagNames ) {
  20698. me.commands[cmd] = {
  20699. execCommand : function( cmdName ) {
  20700. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20701. if ( range.collapsed ) {
  20702. if ( obj ) {
  20703. var tmpText = me.document.createTextNode('');
  20704. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20705. range.setStartBefore(tmpText);
  20706. domUtils.remove(tmpText);
  20707. } else {
  20708. var tmpNode = range.document.createElement( tagNames[0] );
  20709. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20710. tmpText = me.document.createTextNode('');
  20711. range.insertNode(tmpText)
  20712. .removeInlineStyle(['sub','sup'])
  20713. .setStartBefore(tmpText)
  20714. .collapse(true);
  20715. }
  20716. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20717. }
  20718. range.collapse( true );
  20719. } else {
  20720. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20721. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20722. range.removeInlineStyle(['sub','sup']);
  20723. }
  20724. }
  20725. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20726. }
  20727. range.select();
  20728. },
  20729. queryCommandState : function() {
  20730. return getObj(this,tagNames) ? 1 : 0;
  20731. }
  20732. };
  20733. })( style, basestyles[style] );
  20734. }
  20735. };
  20736. // plugins/elementpath.js
  20737. /**
  20738. * 选取路径命令
  20739. * @file
  20740. */
  20741. UE.plugins['elementpath'] = function(){
  20742. var currentLevel,
  20743. tagNames,
  20744. me = this;
  20745. me.setOpt('elementPathEnabled',true);
  20746. if(!me.options.elementPathEnabled){
  20747. return;
  20748. }
  20749. me.commands['elementpath'] = {
  20750. execCommand : function( cmdName, level ) {
  20751. var start = tagNames[level],
  20752. range = me.selection.getRange();
  20753. currentLevel = level*1;
  20754. range.selectNode(start).select();
  20755. },
  20756. queryCommandValue : function() {
  20757. //产生一个副本,不能修改原来的startElementPath;
  20758. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20759. names = [];
  20760. tagNames = parents;
  20761. for(var i=0,ci;ci=parents[i];i++){
  20762. if(ci.nodeType == 3) {
  20763. continue;
  20764. }
  20765. var name = ci.tagName.toLowerCase();
  20766. if(name == 'img' && ci.getAttribute('anchorname')){
  20767. name = 'anchor';
  20768. }
  20769. names[i] = name;
  20770. if(currentLevel == i){
  20771. currentLevel = -1;
  20772. break;
  20773. }
  20774. }
  20775. return names;
  20776. }
  20777. };
  20778. };
  20779. // plugins/formatmatch.js
  20780. /**
  20781. * 格式刷,只格式inline的
  20782. * @file
  20783. * @since 1.2.6.1
  20784. */
  20785. /**
  20786. * 格式刷
  20787. * @command formatmatch
  20788. * @method execCommand
  20789. * @remind 该操作不能复制段落格式
  20790. * @param { String } cmd 命令字符串
  20791. * @example
  20792. * ```javascript
  20793. * //editor是编辑器实例
  20794. * //获取格式刷
  20795. * editor.execCommand( 'formatmatch' );
  20796. * ```
  20797. */
  20798. UE.plugins['formatmatch'] = function(){
  20799. var me = this,
  20800. list = [],img,
  20801. flag = 0;
  20802. me.addListener('reset',function(){
  20803. list = [];
  20804. flag = 0;
  20805. });
  20806. function addList(type,evt){
  20807. if(browser.webkit){
  20808. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20809. }
  20810. function addFormat(range){
  20811. if(text){
  20812. range.selectNode(text);
  20813. }
  20814. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20815. }
  20816. me.undoManger && me.undoManger.save();
  20817. var range = me.selection.getRange(),
  20818. imgT = target || range.getClosedNode();
  20819. if(img && imgT && imgT.tagName == 'IMG'){
  20820. //trace:964
  20821. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20822. img = null;
  20823. }else{
  20824. if(!img){
  20825. var collapsed = range.collapsed;
  20826. if(collapsed){
  20827. var text = me.document.createTextNode('match');
  20828. range.insertNode(text).select();
  20829. }
  20830. me.__hasEnterExecCommand = true;
  20831. //不能把block上的属性干掉
  20832. //trace:1553
  20833. var removeFormatAttributes = me.options.removeFormatAttributes;
  20834. me.options.removeFormatAttributes = '';
  20835. me.execCommand('removeformat');
  20836. me.options.removeFormatAttributes = removeFormatAttributes;
  20837. me.__hasEnterExecCommand = false;
  20838. //trace:969
  20839. range = me.selection.getRange();
  20840. if(list.length){
  20841. addFormat(range);
  20842. }
  20843. if(text){
  20844. range.setStartBefore(text).collapse(true);
  20845. }
  20846. range.select();
  20847. text && domUtils.remove(text);
  20848. }
  20849. }
  20850. me.undoManger && me.undoManger.save();
  20851. me.removeListener('mouseup',addList);
  20852. flag = 0;
  20853. }
  20854. me.commands['formatmatch'] = {
  20855. execCommand : function( cmdName ) {
  20856. if(flag){
  20857. flag = 0;
  20858. list = [];
  20859. me.removeListener('mouseup',addList);
  20860. return;
  20861. }
  20862. var range = me.selection.getRange();
  20863. img = range.getClosedNode();
  20864. if(!img || img.tagName != 'IMG'){
  20865. range.collapse(true).shrinkBoundary();
  20866. var start = range.startContainer;
  20867. list = domUtils.findParents(start,true,function(node){
  20868. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20869. });
  20870. //a不能加入格式刷, 并且克隆节点
  20871. for(var i=0,ci;ci=list[i];i++){
  20872. if(ci.tagName == 'A'){
  20873. list.splice(i,1);
  20874. break;
  20875. }
  20876. }
  20877. }
  20878. me.addListener('mouseup',addList);
  20879. flag = 1;
  20880. },
  20881. queryCommandState : function() {
  20882. return flag;
  20883. },
  20884. notNeedUndo : 1
  20885. };
  20886. };
  20887. // plugins/searchreplace.js
  20888. ///import core
  20889. ///commands 查找替换
  20890. ///commandsName SearchReplace
  20891. ///commandsTitle 查询替换
  20892. ///commandsDialog dialogs\searchreplace
  20893. /**
  20894. * @description 查找替换
  20895. * @author zhanyi
  20896. */
  20897. UE.plugin.register('searchreplace',function(){
  20898. var me = this;
  20899. var _blockElm = {'table':1,'tbody':1,'tr':1,'ol':1,'ul':1};
  20900. function findTextInString(textContent,opt,currentIndex){
  20901. var str = opt.searchStr;
  20902. if(opt.dir == -1){
  20903. textContent = textContent.split('').reverse().join('');
  20904. str = str.split('').reverse().join('');
  20905. currentIndex = textContent.length - currentIndex;
  20906. }
  20907. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20908. while(match = reg.exec(textContent)){
  20909. if(match.index >= currentIndex){
  20910. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20911. }
  20912. }
  20913. return -1
  20914. }
  20915. function findTextBlockElm(node,currentIndex,opt){
  20916. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20917. if(domUtils.isBody(node)){
  20918. node = node.firstChild;
  20919. }
  20920. var first = 1;
  20921. while(node){
  20922. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20923. index = findTextInString(textContent,opt,currentIndex );
  20924. first = 0;
  20925. if(index!=-1){
  20926. return {
  20927. 'node':node,
  20928. 'index':index
  20929. }
  20930. }
  20931. node = domUtils[methodName](node);
  20932. while(node && _blockElm[node.nodeName.toLowerCase()]){
  20933. node = domUtils[methodName](node,true);
  20934. }
  20935. if(node){
  20936. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20937. }
  20938. }
  20939. }
  20940. function findNTextInBlockElm(node,index,str){
  20941. var currentIndex = 0,
  20942. currentNode = node.firstChild,
  20943. currentNodeLength = 0,
  20944. result;
  20945. while(currentNode){
  20946. if(currentNode.nodeType == 3){
  20947. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20948. currentIndex += currentNodeLength;
  20949. if(currentIndex >= index){
  20950. return {
  20951. 'node':currentNode,
  20952. 'index': currentNodeLength - (currentIndex - index)
  20953. }
  20954. }
  20955. }else if(!dtd.$empty[currentNode.tagName]){
  20956. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20957. currentIndex += currentNodeLength;
  20958. if(currentIndex >= index){
  20959. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  20960. if(result){
  20961. return result;
  20962. }
  20963. }
  20964. }
  20965. currentNode = domUtils.getNextDomNode(currentNode);
  20966. }
  20967. }
  20968. function searchReplace(me,opt){
  20969. var rng = me.selection.getRange(),
  20970. startBlockNode,
  20971. searchStr = opt.searchStr,
  20972. span = me.document.createElement('span');
  20973. span.innerHTML = '$$ueditor_searchreplace_key$$';
  20974. rng.shrinkBoundary(true);
  20975. //判断是不是第一次选中
  20976. if(!rng.collapsed){
  20977. rng.select();
  20978. var rngText = me.selection.getText();
  20979. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  20980. if(opt.replaceStr != undefined){
  20981. replaceText(rng,opt.replaceStr);
  20982. rng.select();
  20983. return true;
  20984. }else{
  20985. rng.collapse(opt.dir == -1)
  20986. }
  20987. }
  20988. }
  20989. rng.insertNode(span);
  20990. rng.enlargeToBlockElm(true);
  20991. startBlockNode = rng.startContainer;
  20992. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  20993. rng.setStartBefore(span);
  20994. domUtils.remove(span);
  20995. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  20996. if(result){
  20997. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  20998. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  20999. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  21000. if(opt.replaceStr !== undefined){
  21001. replaceText(rng,opt.replaceStr)
  21002. }
  21003. rng.select();
  21004. return true;
  21005. }else{
  21006. rng.setCursor()
  21007. }
  21008. }
  21009. function replaceText(rng,str){
  21010. str = me.document.createTextNode(str);
  21011. rng.deleteContents().insertNode(str);
  21012. }
  21013. return {
  21014. commands:{
  21015. 'searchreplace':{
  21016. execCommand:function(cmdName,opt){
  21017. utils.extend(opt,{
  21018. all : false,
  21019. casesensitive : false,
  21020. dir : 1
  21021. },true);
  21022. var num = 0;
  21023. if(opt.all){
  21024. var rng = me.selection.getRange(),
  21025. first = me.body.firstChild;
  21026. if(first && first.nodeType == 1){
  21027. rng.setStart(first,0);
  21028. rng.shrinkBoundary(true);
  21029. }else if(first.nodeType == 3){
  21030. rng.setStartBefore(first)
  21031. }
  21032. rng.collapse(true).select(true);
  21033. if(opt.replaceStr !== undefined){
  21034. me.fireEvent('saveScene');
  21035. }
  21036. while(searchReplace(this,opt)){
  21037. num++;
  21038. }
  21039. if(num){
  21040. me.fireEvent('saveScene');
  21041. }
  21042. }else{
  21043. if(opt.replaceStr !== undefined){
  21044. me.fireEvent('saveScene');
  21045. }
  21046. if(searchReplace(this,opt)){
  21047. num++
  21048. }
  21049. if(num){
  21050. me.fireEvent('saveScene');
  21051. }
  21052. }
  21053. return num;
  21054. },
  21055. notNeedUndo:1
  21056. }
  21057. }
  21058. }
  21059. });
  21060. // plugins/customstyle.js
  21061. /**
  21062. * 自定义样式
  21063. * @file
  21064. * @since 1.2.6.1
  21065. */
  21066. /**
  21067. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21068. * @command customstyle
  21069. * @method execCommand
  21070. * @param { String } cmd 命令字符串
  21071. * @example
  21072. * ```javascript
  21073. * editor.execCommand( 'customstyle' );
  21074. * ```
  21075. */
  21076. UE.plugins['customstyle'] = function() {
  21077. var me = this;
  21078. me.setOpt({ 'customstyle':[
  21079. {tag:'h1',name:'tc', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
  21080. {tag:'h1',name:'tl', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;'},
  21081. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21082. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21083. ]});
  21084. me.commands['customstyle'] = {
  21085. execCommand : function(cmdName, obj) {
  21086. var me = this,
  21087. tagName = obj.tag,
  21088. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21089. return node.getAttribute('label');
  21090. }, true),
  21091. range,bk,tmpObj = {};
  21092. for (var p in obj) {
  21093. if(obj[p]!==undefined)
  21094. tmpObj[p] = obj[p];
  21095. }
  21096. delete tmpObj.tag;
  21097. if (node && node.getAttribute('label') == obj.label) {
  21098. range = this.selection.getRange();
  21099. bk = range.createBookmark();
  21100. if (range.collapsed) {
  21101. //trace:1732 删掉自定义标签,要有p来回填站位
  21102. if(dtd.$block[node.tagName]){
  21103. var fillNode = me.document.createElement('p');
  21104. domUtils.moveChild(node, fillNode);
  21105. node.parentNode.insertBefore(fillNode, node);
  21106. domUtils.remove(node);
  21107. }else{
  21108. domUtils.remove(node,true);
  21109. }
  21110. } else {
  21111. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21112. nodes = domUtils.getElementsByTagName(common, tagName);
  21113. if(new RegExp(tagName,'i').test(common.tagName)){
  21114. nodes.push(common);
  21115. }
  21116. for (var i = 0,ni; ni = nodes[i++];) {
  21117. if (ni.getAttribute('label') == obj.label) {
  21118. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21119. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21120. &&
  21121. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21122. )
  21123. if (dtd.$block[tagName]) {
  21124. var fillNode = me.document.createElement('p');
  21125. domUtils.moveChild(ni, fillNode);
  21126. ni.parentNode.insertBefore(fillNode, ni);
  21127. }
  21128. domUtils.remove(ni, true);
  21129. }
  21130. }
  21131. node = domUtils.findParent(common, function(node) {
  21132. return node.getAttribute('label') == obj.label;
  21133. }, true);
  21134. if (node) {
  21135. domUtils.remove(node, true);
  21136. }
  21137. }
  21138. range.moveToBookmark(bk).select();
  21139. } else {
  21140. if (dtd.$block[tagName]) {
  21141. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21142. range = me.selection.getRange();
  21143. if (!range.collapsed) {
  21144. range.collapse();
  21145. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21146. return node.getAttribute('label') == obj.label;
  21147. }, true);
  21148. var pNode = me.document.createElement('p');
  21149. domUtils.insertAfter(node, pNode);
  21150. domUtils.fillNode(me.document, pNode);
  21151. range.setStart(pNode, 0).setCursor();
  21152. }
  21153. } else {
  21154. range = me.selection.getRange();
  21155. if (range.collapsed) {
  21156. node = me.document.createElement(tagName);
  21157. domUtils.setAttributes(node, tmpObj);
  21158. range.insertNode(node).setStart(node, 0).setCursor();
  21159. return;
  21160. }
  21161. bk = range.createBookmark();
  21162. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21163. }
  21164. }
  21165. },
  21166. queryCommandValue : function() {
  21167. var parent = domUtils.filterNodeList(
  21168. this.selection.getStartElementPath(),
  21169. function(node){return node.getAttribute('label')}
  21170. );
  21171. return parent ? parent.getAttribute('label') : '';
  21172. }
  21173. };
  21174. //当去掉customstyle是,如果是块元素,用p代替
  21175. me.addListener('keyup', function(type, evt) {
  21176. var keyCode = evt.keyCode || evt.which;
  21177. if (keyCode == 32 || keyCode == 13) {
  21178. var range = me.selection.getRange();
  21179. if (range.collapsed) {
  21180. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21181. return node.getAttribute('label');
  21182. }, true);
  21183. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21184. var p = me.document.createElement('p');
  21185. domUtils.insertAfter(node, p);
  21186. domUtils.fillNode(me.document, p);
  21187. domUtils.remove(node);
  21188. range.setStart(p, 0).setCursor();
  21189. }
  21190. }
  21191. }
  21192. });
  21193. };
  21194. // plugins/catchremoteimage.js
  21195. ///import core
  21196. ///commands 远程图片抓取
  21197. ///commandsName catchRemoteImage,catchremoteimageenable
  21198. ///commandsTitle 远程图片抓取
  21199. /**
  21200. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21201. */
  21202. UE.plugins['catchremoteimage'] = function () {
  21203. var me = this,
  21204. ajax = UE.ajax;
  21205. /* 设置默认值 */
  21206. if (me.options.catchRemoteImageEnable === false) return;
  21207. me.setOpt({
  21208. catchRemoteImageEnable: false
  21209. });
  21210. me.addListener("afterpaste", function () {
  21211. me.fireEvent("catchRemoteImage");
  21212. });
  21213. me.addListener("catchRemoteImage", function () {
  21214. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21215. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21216. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21217. catcherFieldName = me.getOpt('catcherFieldName');
  21218. var remoteImages = [],
  21219. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21220. test = function (src, urls) {
  21221. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21222. return true;
  21223. }
  21224. if (urls) {
  21225. for (var j = 0, url; url = urls[j++];) {
  21226. if (src.indexOf(url) !== -1) {
  21227. return true;
  21228. }
  21229. }
  21230. }
  21231. return false;
  21232. };
  21233. for (var i = 0, ci; ci = imgs[i++];) {
  21234. if (ci.getAttribute("word_img")) {
  21235. continue;
  21236. }
  21237. var src = ci.getAttribute("_src") || ci.src || "";
  21238. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21239. remoteImages.push(src);
  21240. }
  21241. }
  21242. if (remoteImages.length) {
  21243. catchremoteimage(remoteImages, {
  21244. //成功抓取
  21245. success: function (r) {
  21246. try {
  21247. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21248. } catch (e) {
  21249. return;
  21250. }
  21251. /* 获取源路径和新路径 */
  21252. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21253. for (i = 0; ci = imgs[i++];) {
  21254. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21255. for (j = 0; cj = list[j++];) {
  21256. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21257. newSrc = catcherUrlPrefix + cj.url;
  21258. domUtils.setAttributes(ci, {
  21259. "src": newSrc,
  21260. "_src": newSrc
  21261. });
  21262. break;
  21263. }
  21264. }
  21265. }
  21266. me.fireEvent('catchremotesuccess')
  21267. },
  21268. //回调失败,本次请求超时
  21269. error: function () {
  21270. me.fireEvent("catchremoteerror");
  21271. }
  21272. });
  21273. }
  21274. function catchremoteimage(imgs, callbacks) {
  21275. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21276. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21277. isJsonp = utils.isCrossDomainUrl(url),
  21278. opt = {
  21279. 'method': 'POST',
  21280. 'dataType': isJsonp ? 'jsonp':'',
  21281. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21282. 'onsuccess': callbacks["success"],
  21283. 'onerror': callbacks["error"]
  21284. };
  21285. opt[catcherFieldName] = imgs;
  21286. ajax.request(url, opt);
  21287. }
  21288. });
  21289. };
  21290. // plugins/snapscreen.js
  21291. /**
  21292. * 截屏插件,为UEditor提供插入支持
  21293. * @file
  21294. * @since 1.4.2
  21295. */
  21296. UE.plugin.register('snapscreen', function (){
  21297. var me = this;
  21298. var snapplugin;
  21299. function getLocation(url){
  21300. var search,
  21301. a = document.createElement('a'),
  21302. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21303. a.href = url;
  21304. if (browser.ie) {
  21305. a.href = a.href;
  21306. }
  21307. search = a.search;
  21308. if (params) {
  21309. search = search + (search.indexOf('?') == -1 ? '?':'&')+ params;
  21310. search = search.replace(/[&]+/ig, '&');
  21311. }
  21312. return {
  21313. 'port': a.port,
  21314. 'hostname': a.hostname,
  21315. 'path': a.pathname + search || + a.hash
  21316. }
  21317. }
  21318. return {
  21319. commands:{
  21320. /**
  21321. * 字体背景颜色
  21322. * @command snapscreen
  21323. * @method execCommand
  21324. * @param { String } cmd 命令字符串
  21325. * @example
  21326. * ```javascript
  21327. * editor.execCommand('snapscreen');
  21328. * ```
  21329. */
  21330. 'snapscreen':{
  21331. execCommand:function (cmd) {
  21332. var url, local, res;
  21333. var lang = me.getLang("snapScreen_plugin");
  21334. if(!snapplugin){
  21335. var container = me.container;
  21336. var doc = me.container.ownerDocument || me.container.document;
  21337. snapplugin = doc.createElement("object");
  21338. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21339. return;
  21340. }
  21341. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21342. snapplugin.setAttribute("width","0");
  21343. snapplugin.setAttribute("height","0");
  21344. container.appendChild(snapplugin);
  21345. }
  21346. function onSuccess(rs){
  21347. try{
  21348. rs = eval("("+ rs +")");
  21349. if(rs.state == 'SUCCESS'){
  21350. var opt = me.options;
  21351. me.execCommand('insertimage', {
  21352. src: opt.snapscreenUrlPrefix + rs.url,
  21353. _src: opt.snapscreenUrlPrefix + rs.url,
  21354. alt: rs.title || '',
  21355. floatStyle: opt.snapscreenImgAlign
  21356. });
  21357. } else {
  21358. alert(rs.state);
  21359. }
  21360. }catch(e){
  21361. alert(lang.callBackErrorMsg);
  21362. }
  21363. }
  21364. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21365. local = getLocation(url);
  21366. setTimeout(function () {
  21367. try{
  21368. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21369. }catch(e){
  21370. me.ui._dialogs['snapscreenDialog'].open();
  21371. return;
  21372. }
  21373. onSuccess(res);
  21374. }, 50);
  21375. },
  21376. queryCommandState: function(){
  21377. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21378. }
  21379. }
  21380. }
  21381. }
  21382. });
  21383. // plugins/insertparagraph.js
  21384. /**
  21385. * 插入段落
  21386. * @file
  21387. * @since 1.2.6.1
  21388. */
  21389. /**
  21390. * 插入段落
  21391. * @command insertparagraph
  21392. * @method execCommand
  21393. * @param { String } cmd 命令字符串
  21394. * @example
  21395. * ```javascript
  21396. * //editor是编辑器实例
  21397. * editor.execCommand( 'insertparagraph' );
  21398. * ```
  21399. */
  21400. UE.commands['insertparagraph'] = {
  21401. execCommand : function( cmdName,front) {
  21402. var me = this,
  21403. range = me.selection.getRange(),
  21404. start = range.startContainer,tmpNode;
  21405. while(start ){
  21406. if(domUtils.isBody(start)){
  21407. break;
  21408. }
  21409. tmpNode = start;
  21410. start = start.parentNode;
  21411. }
  21412. if(tmpNode){
  21413. var p = me.document.createElement('p');
  21414. if(front){
  21415. tmpNode.parentNode.insertBefore(p,tmpNode)
  21416. }else{
  21417. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21418. }
  21419. domUtils.fillNode(me.document,p);
  21420. range.setStart(p,0).setCursor(false,true);
  21421. }
  21422. }
  21423. };
  21424. // plugins/webapp.js
  21425. /**
  21426. * 百度应用
  21427. * @file
  21428. * @since 1.2.6.1
  21429. */
  21430. /**
  21431. * 插入百度应用
  21432. * @command webapp
  21433. * @method execCommand
  21434. * @remind 需要百度APPKey
  21435. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21436. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21437. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21438. * @example
  21439. * ```javascript
  21440. * //editor是编辑器实例
  21441. * //在编辑器里插入一个“植物大战僵尸”的APP
  21442. * editor.execCommand( 'webapp' , {
  21443. * title: '植物大战僵尸',
  21444. * width: 560,
  21445. * height: 465,
  21446. * logo: '应用展示的图片',
  21447. * url: '百度应用的地址'
  21448. * } );
  21449. * ```
  21450. */
  21451. //UE.plugins['webapp'] = function () {
  21452. // var me = this;
  21453. // function createInsertStr( obj, toIframe, addParagraph ) {
  21454. // return !toIframe ?
  21455. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21456. // ' 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 + '" />' +
  21457. // (addParagraph ? '</p>' : '')
  21458. // :
  21459. // '<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>';
  21460. // }
  21461. //
  21462. // function switchImgAndIframe( img2frame ) {
  21463. // var tmpdiv,
  21464. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21465. // for ( var i = 0, node; node = nodes[i++]; ) {
  21466. // if ( node.className != "edui-faked-webapp" ){
  21467. // continue;
  21468. // }
  21469. // tmpdiv = me.document.createElement( "div" );
  21470. // 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 );
  21471. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21472. // }
  21473. // }
  21474. //
  21475. // me.addListener( "beforegetcontent", function () {
  21476. // switchImgAndIframe( true );
  21477. // } );
  21478. // me.addListener( 'aftersetcontent', function () {
  21479. // switchImgAndIframe( false );
  21480. // } );
  21481. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21482. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21483. // return;
  21484. // }
  21485. // switchImgAndIframe( false );
  21486. // } );
  21487. //
  21488. // me.commands['webapp'] = {
  21489. // execCommand:function ( cmd, obj ) {
  21490. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21491. // }
  21492. // };
  21493. //};
  21494. UE.plugin.register('webapp', function (){
  21495. var me = this;
  21496. function createInsertStr(obj,toEmbed){
  21497. return !toEmbed ?
  21498. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21499. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21500. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21501. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21502. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21503. '/>'
  21504. :
  21505. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21506. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21507. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21508. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21509. }
  21510. return {
  21511. outputRule: function(root){
  21512. utils.each(root.getNodesByTagName('img'),function(node){
  21513. var html;
  21514. if(node.getAttr('class') == 'edui-faked-webapp'){
  21515. html = createInsertStr({
  21516. title:node.getAttr('title'),
  21517. 'width':node.getAttr('width'),
  21518. 'height':node.getAttr('height'),
  21519. 'align':node.getAttr('align'),
  21520. 'cssfloat':node.getStyle('float'),
  21521. 'url':node.getAttr("_url"),
  21522. 'logo':node.getAttr('_logo_url')
  21523. },true);
  21524. var embed = UE.uNode.createElement(html);
  21525. node.parentNode.replaceChild(embed,node);
  21526. }
  21527. })
  21528. },
  21529. inputRule:function(root){
  21530. utils.each(root.getNodesByTagName('iframe'),function(node){
  21531. if(node.getAttr('class') == 'edui-faked-webapp'){
  21532. var img = UE.uNode.createElement(createInsertStr({
  21533. title:node.getAttr('title'),
  21534. 'width':node.getAttr('width'),
  21535. 'height':node.getAttr('height'),
  21536. 'align':node.getAttr('align'),
  21537. 'cssfloat':node.getStyle('float'),
  21538. 'url':node.getAttr("src"),
  21539. 'logo':node.getAttr('logo_url')
  21540. }));
  21541. node.parentNode.replaceChild(img,node);
  21542. }
  21543. })
  21544. },
  21545. commands:{
  21546. /**
  21547. * 插入百度应用
  21548. * @command webapp
  21549. * @method execCommand
  21550. * @remind 需要百度APPKey
  21551. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21552. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21553. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21554. * @example
  21555. * ```javascript
  21556. * //editor是编辑器实例
  21557. * //在编辑器里插入一个“植物大战僵尸”的APP
  21558. * editor.execCommand( 'webapp' , {
  21559. * title: '植物大战僵尸',
  21560. * width: 560,
  21561. * height: 465,
  21562. * logo: '应用展示的图片',
  21563. * url: '百度应用的地址'
  21564. * } );
  21565. * ```
  21566. */
  21567. 'webapp':{
  21568. execCommand:function (cmd, obj) {
  21569. var me = this,
  21570. str = createInsertStr(utils.extend(obj,{
  21571. align:'none'
  21572. }), false);
  21573. me.execCommand("inserthtml",str);
  21574. },
  21575. queryCommandState:function () {
  21576. var me = this,
  21577. img = me.selection.getRange().getClosedNode(),
  21578. flag = img && (img.className == "edui-faked-webapp");
  21579. return flag ? 1 : 0;
  21580. }
  21581. }
  21582. }
  21583. }
  21584. });
  21585. // plugins/template.js
  21586. ///import core
  21587. ///import plugins\inserthtml.js
  21588. ///import plugins\cleardoc.js
  21589. ///commands 模板
  21590. ///commandsName template
  21591. ///commandsTitle 模板
  21592. ///commandsDialog dialogs\template
  21593. UE.plugins['template'] = function () {
  21594. UE.commands['template'] = {
  21595. execCommand:function (cmd, obj) {
  21596. obj.html && this.execCommand("inserthtml", obj.html);
  21597. }
  21598. };
  21599. this.addListener("click", function (type, evt) {
  21600. var el = evt.target || evt.srcElement,
  21601. range = this.selection.getRange();
  21602. var tnode = domUtils.findParent(el, function (node) {
  21603. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21604. return node;
  21605. }
  21606. }, true);
  21607. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21608. });
  21609. this.addListener("keydown", function (type, evt) {
  21610. var range = this.selection.getRange();
  21611. if (!range.collapsed) {
  21612. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21613. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21614. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21615. return node;
  21616. }
  21617. }, true);
  21618. if (tnode) {
  21619. domUtils.removeClasses(tnode, ["ue_t"]);
  21620. }
  21621. }
  21622. }
  21623. });
  21624. };
  21625. // plugins/music.js
  21626. /**
  21627. * 插入音乐命令
  21628. * @file
  21629. */
  21630. UE.plugin.register('music', function (){
  21631. var me = this;
  21632. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21633. return !toEmbed ?
  21634. '<img ' +
  21635. (align && !cssfloat? 'align="' + align + '"' : '') +
  21636. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21637. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21638. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21639. :
  21640. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21641. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21642. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21643. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21644. }
  21645. return {
  21646. outputRule: function(root){
  21647. utils.each(root.getNodesByTagName('img'),function(node){
  21648. var html;
  21649. if(node.getAttr('class') == 'edui-faked-music'){
  21650. var cssfloat = node.getStyle('float');
  21651. var align = node.getAttr('align');
  21652. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21653. var embed = UE.uNode.createElement(html);
  21654. node.parentNode.replaceChild(embed,node);
  21655. }
  21656. })
  21657. },
  21658. inputRule:function(root){
  21659. utils.each(root.getNodesByTagName('embed'),function(node){
  21660. if(node.getAttr('class') == 'edui-faked-music'){
  21661. var cssfloat = node.getStyle('float');
  21662. var align = node.getAttr('align');
  21663. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21664. var img = UE.uNode.createElement(html);
  21665. node.parentNode.replaceChild(img,node);
  21666. }
  21667. })
  21668. },
  21669. commands:{
  21670. /**
  21671. * 插入音乐
  21672. * @command music
  21673. * @method execCommand
  21674. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21675. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21676. * @example
  21677. * ```javascript
  21678. * //editor是编辑器实例
  21679. * //在编辑器里插入一个“植物大战僵尸”的APP
  21680. * editor.execCommand( 'music' , {
  21681. * width: 400,
  21682. * height: 95,
  21683. * align: "center",
  21684. * url: "音乐地址"
  21685. * } );
  21686. * ```
  21687. */
  21688. 'music':{
  21689. execCommand:function (cmd, musicObj) {
  21690. var me = this,
  21691. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21692. me.execCommand("inserthtml",str);
  21693. },
  21694. queryCommandState:function () {
  21695. var me = this,
  21696. img = me.selection.getRange().getClosedNode(),
  21697. flag = img && (img.className == "edui-faked-music");
  21698. return flag ? 1 : 0;
  21699. }
  21700. }
  21701. }
  21702. }
  21703. });
  21704. // plugins/autoupload.js
  21705. /**
  21706. * @description
  21707. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21708. * 2.插入粘贴板的图片,自动上传并插入到选区
  21709. * @author Jinqn
  21710. * @date 2013-10-14
  21711. */
  21712. UE.plugin.register('autoupload', function (){
  21713. function sendAndInsertFile(file, editor) {
  21714. var me = editor;
  21715. //模拟数据
  21716. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21717. loadingHtml, errorHandler, successHandler,
  21718. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21719. loadingId = 'loading_' + (+new Date()).toString(36);
  21720. fieldName = me.getOpt(filetype + 'FieldName');
  21721. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21722. maxSize = me.getOpt(filetype + 'MaxSize');
  21723. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21724. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21725. errorHandler = function(title) {
  21726. var loader = me.document.getElementById(loadingId);
  21727. loader && domUtils.remove(loader);
  21728. me.fireEvent('showmessage', {
  21729. 'id': loadingId,
  21730. 'content': title,
  21731. 'type': 'error',
  21732. 'timeout': 4000
  21733. });
  21734. };
  21735. if (filetype == 'image') {
  21736. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21737. me.options.themePath + me.options.theme +
  21738. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21739. successHandler = function(data) {
  21740. var link = urlPrefix + data.url,
  21741. loader = me.document.getElementById(loadingId);
  21742. if (loader) {
  21743. loader.setAttribute('src', link);
  21744. loader.setAttribute('_src', link);
  21745. loader.setAttribute('title', data.title || '');
  21746. loader.setAttribute('alt', data.original || '');
  21747. loader.removeAttribute('id');
  21748. domUtils.removeClasses(loader, 'loadingclass');
  21749. }
  21750. };
  21751. } else {
  21752. loadingHtml = '<p>' +
  21753. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21754. me.options.themePath + me.options.theme +
  21755. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21756. '</p>';
  21757. successHandler = function(data) {
  21758. var link = urlPrefix + data.url,
  21759. loader = me.document.getElementById(loadingId);
  21760. var rng = me.selection.getRange(),
  21761. bk = rng.createBookmark();
  21762. rng.selectNode(loader).select();
  21763. me.execCommand('insertfile', {'url': link});
  21764. rng.moveToBookmark(bk).select();
  21765. };
  21766. }
  21767. /* 插入loading的占位符 */
  21768. me.execCommand('inserthtml', loadingHtml);
  21769. /* 判断后端配置是否没有加载成功 */
  21770. if (!me.getOpt(filetype + 'ActionName')) {
  21771. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21772. return;
  21773. }
  21774. /* 判断文件大小是否超出限制 */
  21775. if(file.size > maxSize) {
  21776. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21777. return;
  21778. }
  21779. /* 判断文件格式是否超出允许 */
  21780. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21781. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21782. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21783. return;
  21784. }
  21785. /* 创建Ajax并提交 */
  21786. var xhr = new XMLHttpRequest(),
  21787. fd = new FormData(),
  21788. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21789. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21790. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21791. fd.append('type', 'ajax');
  21792. xhr.open("post", url, true);
  21793. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21794. xhr.addEventListener('load', function (e) {
  21795. try{
  21796. var json = (new Function("return " + utils.trim(e.target.response)))();
  21797. if (json.state == 'SUCCESS' && json.url) {
  21798. successHandler(json);
  21799. } else {
  21800. errorHandler(json.state);
  21801. }
  21802. }catch(er){
  21803. errorHandler(me.getLang('autoupload.loadError'));
  21804. }
  21805. });
  21806. xhr.send(fd);
  21807. }
  21808. function getPasteImage(e){
  21809. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21810. }
  21811. function getDropImage(e){
  21812. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21813. }
  21814. return {
  21815. outputRule: function(root){
  21816. utils.each(root.getNodesByTagName('img'),function(n){
  21817. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21818. n.parentNode.removeChild(n);
  21819. }
  21820. });
  21821. utils.each(root.getNodesByTagName('p'),function(n){
  21822. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21823. n.parentNode.removeChild(n);
  21824. }
  21825. });
  21826. },
  21827. bindEvents:{
  21828. //插入粘贴板的图片,拖放插入图片
  21829. 'ready':function(e){
  21830. var me = this;
  21831. if(window.FormData && window.FileReader) {
  21832. domUtils.on(me.body, 'paste drop', function(e){
  21833. var hasImg = false,
  21834. items;
  21835. //获取粘贴板文件列表或者拖放文件列表
  21836. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21837. if(items){
  21838. var len = items.length,
  21839. file;
  21840. while (len--){
  21841. file = items[len];
  21842. if(file.getAsFile) file = file.getAsFile();
  21843. if(file && file.size > 0) {
  21844. sendAndInsertFile(file, me);
  21845. hasImg = true;
  21846. }
  21847. }
  21848. hasImg && e.preventDefault();
  21849. }
  21850. });
  21851. //取消拖放图片时出现的文字光标位置提示
  21852. domUtils.on(me.body, 'dragover', function (e) {
  21853. if(e.dataTransfer.types[0] == 'Files') {
  21854. e.preventDefault();
  21855. }
  21856. });
  21857. //设置loading的样式
  21858. utils.cssRule('loading',
  21859. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21860. + this.options.themePath
  21861. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21862. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21863. + this.options.themePath
  21864. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21865. '}',
  21866. this.document);
  21867. }
  21868. }
  21869. }
  21870. }
  21871. });
  21872. // plugins/autosave.js
  21873. UE.plugin.register('autosave', function (){
  21874. var me = this,
  21875. //无限循环保护
  21876. lastSaveTime = new Date(),
  21877. //最小保存间隔时间
  21878. MIN_TIME = 20,
  21879. //auto save key
  21880. saveKey = null;
  21881. function save ( editor ) {
  21882. var saveData;
  21883. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21884. return;
  21885. }
  21886. if ( !editor.hasContents() ) {
  21887. //这里不能调用命令来删除, 会造成事件死循环
  21888. saveKey && me.removePreferences( saveKey );
  21889. return;
  21890. }
  21891. lastSaveTime = new Date();
  21892. editor._saveFlag = null;
  21893. saveData = me.body.innerHTML;
  21894. if ( editor.fireEvent( "beforeautosave", {
  21895. content: saveData
  21896. } ) === false ) {
  21897. return;
  21898. }
  21899. me.setPreferences( saveKey, saveData );
  21900. editor.fireEvent( "afterautosave", {
  21901. content: saveData
  21902. } );
  21903. }
  21904. return {
  21905. defaultOptions: {
  21906. //默认间隔时间
  21907. saveInterval: 500
  21908. },
  21909. bindEvents:{
  21910. 'ready':function(){
  21911. var _suffix = "-drafts-data",
  21912. key = null;
  21913. if ( me.key ) {
  21914. key = me.key + _suffix;
  21915. } else {
  21916. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21917. }
  21918. //页面地址+编辑器ID 保持唯一
  21919. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21920. },
  21921. 'contentchange': function () {
  21922. if ( !saveKey ) {
  21923. return;
  21924. }
  21925. if ( me._saveFlag ) {
  21926. window.clearTimeout( me._saveFlag );
  21927. }
  21928. if ( me.options.saveInterval > 0 ) {
  21929. me._saveFlag = window.setTimeout( function () {
  21930. save( me );
  21931. }, me.options.saveInterval );
  21932. } else {
  21933. save(me);
  21934. }
  21935. }
  21936. },
  21937. commands:{
  21938. 'clearlocaldata':{
  21939. execCommand:function (cmd, name) {
  21940. if ( saveKey && me.getPreferences( saveKey ) ) {
  21941. me.removePreferences( saveKey )
  21942. }
  21943. },
  21944. notNeedUndo: true,
  21945. ignoreContentChange:true
  21946. },
  21947. 'getlocaldata':{
  21948. execCommand:function (cmd, name) {
  21949. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21950. },
  21951. notNeedUndo: true,
  21952. ignoreContentChange:true
  21953. },
  21954. 'drafts':{
  21955. execCommand:function (cmd, name) {
  21956. if ( saveKey ) {
  21957. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  21958. me.focus(true);
  21959. }
  21960. },
  21961. queryCommandState: function () {
  21962. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  21963. },
  21964. notNeedUndo: true,
  21965. ignoreContentChange:true
  21966. }
  21967. }
  21968. }
  21969. });
  21970. // plugins/charts.js
  21971. UE.plugin.register('charts', function (){
  21972. var me = this;
  21973. return {
  21974. bindEvents: {
  21975. 'chartserror': function () {
  21976. }
  21977. },
  21978. commands:{
  21979. 'charts': {
  21980. execCommand: function ( cmd, data ) {
  21981. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  21982. flagText = [],
  21983. config = {};
  21984. if ( !tableNode ) {
  21985. return false;
  21986. }
  21987. if ( !validData( tableNode ) ) {
  21988. me.fireEvent( "chartserror" );
  21989. return false;
  21990. }
  21991. config.title = data.title || '';
  21992. config.subTitle = data.subTitle || '';
  21993. config.xTitle = data.xTitle || '';
  21994. config.yTitle = data.yTitle || '';
  21995. config.suffix = data.suffix || '';
  21996. config.tip = data.tip || '';
  21997. //数据对齐方式
  21998. config.dataFormat = data.tableDataFormat || '';
  21999. //图表类型
  22000. config.chartType = data.chartType || 0;
  22001. for ( var key in config ) {
  22002. if ( !config.hasOwnProperty( key ) ) {
  22003. continue;
  22004. }
  22005. flagText.push( key+":"+config[ key ] );
  22006. }
  22007. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  22008. domUtils.addClass( tableNode, "edui-charts-table" );
  22009. },
  22010. queryCommandState: function ( cmd, name ) {
  22011. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22012. return tableNode && validData( tableNode ) ? 0 : -1;
  22013. }
  22014. }
  22015. },
  22016. inputRule:function(root){
  22017. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22018. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22019. tableNode.setAttr("style");
  22020. }
  22021. })
  22022. },
  22023. outputRule:function(root){
  22024. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22025. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22026. tableNode.setAttr("style", "display: none;");
  22027. }
  22028. })
  22029. }
  22030. }
  22031. function validData ( table ) {
  22032. var firstRows = null,
  22033. cellCount = 0;
  22034. //行数不够
  22035. if ( table.rows.length < 2 ) {
  22036. return false;
  22037. }
  22038. //列数不够
  22039. if ( table.rows[0].cells.length < 2 ) {
  22040. return false;
  22041. }
  22042. //第一行所有cell必须是th
  22043. firstRows = table.rows[ 0 ].cells;
  22044. cellCount = firstRows.length;
  22045. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22046. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22047. return false;
  22048. }
  22049. }
  22050. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22051. //每行单元格数不匹配, 返回false
  22052. if ( row.cells.length != cellCount ) {
  22053. return false;
  22054. }
  22055. //第一列不是th也返回false
  22056. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22057. return false;
  22058. }
  22059. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22060. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22061. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22062. //必须是数字
  22063. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22064. return false;
  22065. }
  22066. }
  22067. }
  22068. return true;
  22069. }
  22070. });
  22071. // plugins/section.js
  22072. /**
  22073. * 目录大纲支持插件
  22074. * @file
  22075. * @since 1.3.0
  22076. */
  22077. UE.plugin.register('section', function (){
  22078. /* 目录节点对象 */
  22079. function Section(option){
  22080. this.tag = '';
  22081. this.level = -1,
  22082. this.dom = null;
  22083. this.nextSection = null;
  22084. this.previousSection = null;
  22085. this.parentSection = null;
  22086. this.startAddress = [];
  22087. this.endAddress = [];
  22088. this.children = [];
  22089. }
  22090. function getSection(option) {
  22091. var section = new Section();
  22092. return utils.extend(section, option);
  22093. }
  22094. function getNodeFromAddress(startAddress, root) {
  22095. var current = root;
  22096. for(var i = 0;i < startAddress.length; i++) {
  22097. if(!current.childNodes) return null;
  22098. current = current.childNodes[startAddress[i]];
  22099. }
  22100. return current;
  22101. }
  22102. var me = this;
  22103. return {
  22104. bindMultiEvents:{
  22105. type: 'aftersetcontent afterscencerestore',
  22106. handler: function(){
  22107. me.fireEvent('updateSections');
  22108. }
  22109. },
  22110. bindEvents:{
  22111. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22112. 'ready': function (){
  22113. me.fireEvent('updateSections');
  22114. domUtils.on(me.body, 'drop paste', function(){
  22115. me.fireEvent('updateSections');
  22116. });
  22117. },
  22118. /* 执行paragraph命令之后 */
  22119. 'afterexeccommand': function (type, cmd) {
  22120. if(cmd == 'paragraph') {
  22121. me.fireEvent('updateSections');
  22122. }
  22123. },
  22124. /* 部分键盘操作,触发updateSections事件 */
  22125. 'keyup': function (type, e) {
  22126. var me = this,
  22127. range = me.selection.getRange();
  22128. if(range.collapsed != true) {
  22129. me.fireEvent('updateSections');
  22130. } else {
  22131. var keyCode = e.keyCode || e.which;
  22132. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22133. me.fireEvent('updateSections');
  22134. }
  22135. }
  22136. }
  22137. },
  22138. commands:{
  22139. 'getsections': {
  22140. execCommand: function (cmd, levels) {
  22141. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22142. for (var i = 0; i < levelFn.length; i++) {
  22143. if (typeof levelFn[i] == 'string') {
  22144. levelFn[i] = function(fn){
  22145. return function(node){
  22146. return node.tagName == fn.toUpperCase()
  22147. };
  22148. }(levelFn[i]);
  22149. } else if (typeof levelFn[i] != 'function') {
  22150. levelFn[i] = function (node) {
  22151. return null;
  22152. }
  22153. }
  22154. }
  22155. function getSectionLevel(node) {
  22156. for (var i = 0; i < levelFn.length; i++) {
  22157. if (levelFn[i](node)) return i;
  22158. }
  22159. return -1;
  22160. }
  22161. var me = this,
  22162. Directory = getSection({'level':-1, 'title':'root'}),
  22163. previous = Directory;
  22164. function traversal(node, Directory) {
  22165. var level,
  22166. tmpSection = null,
  22167. parent,
  22168. child,
  22169. children = node.childNodes;
  22170. for (var i = 0, len = children.length; i < len; i++) {
  22171. child = children[i];
  22172. level = getSectionLevel(child);
  22173. if (level >= 0) {
  22174. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22175. current = getSection({
  22176. 'tag': child.tagName,
  22177. 'title': child.innerText || child.textContent || '',
  22178. 'level': level,
  22179. 'dom': child,
  22180. 'startAddress': utils.clone(address, []),
  22181. 'endAddress': utils.clone(address, []),
  22182. 'children': []
  22183. });
  22184. previous.nextSection = current;
  22185. current.previousSection = previous;
  22186. parent = previous;
  22187. while(level <= parent.level){
  22188. parent = parent.parentSection;
  22189. }
  22190. current.parentSection = parent;
  22191. parent.children.push(current);
  22192. tmpSection = previous = current;
  22193. } else {
  22194. child.nodeType === 1 && traversal(child, Directory);
  22195. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22196. }
  22197. }
  22198. }
  22199. traversal(me.body, Directory);
  22200. return Directory;
  22201. },
  22202. notNeedUndo: true
  22203. },
  22204. 'movesection': {
  22205. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22206. var me = this,
  22207. targetAddress,
  22208. target;
  22209. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22210. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22211. target = getNodeFromAddress(targetAddress, me.body);
  22212. /* 判断目标地址是否被源章节包含 */
  22213. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22214. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22215. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22216. current,
  22217. nextNode;
  22218. if(isAfter) {
  22219. current = endNode;
  22220. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22221. nextNode = current.previousSibling;
  22222. domUtils.insertAfter(target, current);
  22223. if(current == startNode) break;
  22224. current = nextNode;
  22225. }
  22226. } else {
  22227. current = startNode;
  22228. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22229. nextNode = current.nextSibling;
  22230. target.parentNode.insertBefore(current, target);
  22231. if(current == endNode) break;
  22232. current = nextNode;
  22233. }
  22234. }
  22235. me.fireEvent('updateSections');
  22236. /* 获取地址的包含关系 */
  22237. function isContainsAddress(startAddress, endAddress, addressTarget){
  22238. var isAfterStartAddress = false,
  22239. isBeforeEndAddress = false;
  22240. for(var i = 0; i< startAddress.length; i++){
  22241. if(i >= addressTarget.length) break;
  22242. if(addressTarget[i] > startAddress[i]) {
  22243. isAfterStartAddress = true;
  22244. break;
  22245. } else if(addressTarget[i] < startAddress[i]) {
  22246. break;
  22247. }
  22248. }
  22249. for(var i = 0; i< endAddress.length; i++){
  22250. if(i >= addressTarget.length) break;
  22251. if(addressTarget[i] < startAddress[i]) {
  22252. isBeforeEndAddress = true;
  22253. break;
  22254. } else if(addressTarget[i] > startAddress[i]) {
  22255. break;
  22256. }
  22257. }
  22258. return isAfterStartAddress && isBeforeEndAddress;
  22259. }
  22260. }
  22261. },
  22262. 'deletesection': {
  22263. execCommand: function (cmd, section, keepChildren) {
  22264. var me = this;
  22265. if(!section) return;
  22266. function getNodeFromAddress(startAddress) {
  22267. var current = me.body;
  22268. for(var i = 0;i < startAddress.length; i++) {
  22269. if(!current.childNodes) return null;
  22270. current = current.childNodes[startAddress[i]];
  22271. }
  22272. return current;
  22273. }
  22274. var startNode = getNodeFromAddress(section.startAddress),
  22275. endNode = getNodeFromAddress(section.endAddress),
  22276. current = startNode,
  22277. nextNode;
  22278. if(!keepChildren) {
  22279. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22280. nextNode = current.nextSibling;
  22281. domUtils.remove(current);
  22282. current = nextNode;
  22283. }
  22284. } else {
  22285. domUtils.remove(current);
  22286. }
  22287. me.fireEvent('updateSections');
  22288. }
  22289. },
  22290. 'selectsection': {
  22291. execCommand: function (cmd, section) {
  22292. if(!section && !section.dom) return false;
  22293. var me = this,
  22294. range = me.selection.getRange(),
  22295. address = {
  22296. 'startAddress':utils.clone(section.startAddress, []),
  22297. 'endAddress':utils.clone(section.endAddress, [])
  22298. };
  22299. address.endAddress[address.endAddress.length - 1]++;
  22300. range.moveToAddress(address).select().scrollToView();
  22301. return true;
  22302. },
  22303. notNeedUndo: true
  22304. },
  22305. 'scrolltosection': {
  22306. execCommand: function (cmd, section) {
  22307. if(!section && !section.dom) return false;
  22308. var me = this,
  22309. range = me.selection.getRange(),
  22310. address = {
  22311. 'startAddress':section.startAddress,
  22312. 'endAddress':section.endAddress
  22313. };
  22314. address.endAddress[address.endAddress.length - 1]++;
  22315. range.moveToAddress(address).scrollToView();
  22316. return true;
  22317. },
  22318. notNeedUndo: true
  22319. }
  22320. }
  22321. }
  22322. });
  22323. // plugins/simpleupload.js
  22324. /**
  22325. * @description
  22326. * 简单上传:点击按钮,直接选择文件上传
  22327. * @author Jinqn
  22328. * @date 2014-03-31
  22329. */
  22330. UE.plugin.register('simpleupload', function (){
  22331. var me = this,
  22332. isLoaded = false,
  22333. containerBtn;
  22334. function initUploadBtn(){
  22335. var w = containerBtn.offsetWidth || 20,
  22336. h = containerBtn.offsetHeight || 20,
  22337. btnIframe = document.createElement('iframe'),
  22338. 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;';
  22339. domUtils.on(btnIframe, 'load', function(){
  22340. var timestrap = (+new Date()).toString(36),
  22341. wrapper,
  22342. btnIframeDoc,
  22343. btnIframeBody;
  22344. btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
  22345. btnIframeBody = btnIframeDoc.body;
  22346. wrapper = btnIframeDoc.createElement('div');
  22347. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22348. 'style="' + btnStyle + '">' +
  22349. '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
  22350. 'style="' + btnStyle + '">' +
  22351. '</form>' +
  22352. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22353. wrapper.className = 'edui-' + me.options.theme;
  22354. wrapper.id = me.ui.id + '_iframeupload';
  22355. btnIframeBody.style.cssText = btnStyle;
  22356. btnIframeBody.style.width = w + 'px';
  22357. btnIframeBody.style.height = h + 'px';
  22358. btnIframeBody.appendChild(wrapper);
  22359. if (btnIframeBody.parentNode) {
  22360. btnIframeBody.parentNode.style.width = w + 'px';
  22361. btnIframeBody.parentNode.style.height = w + 'px';
  22362. }
  22363. var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
  22364. var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
  22365. var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);
  22366. domUtils.on(input, 'change', function(){
  22367. if(!input.value) return;
  22368. var loadingId = 'loading_' + (+new Date()).toString(36);
  22369. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22370. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22371. var allowFiles = me.getOpt('imageAllowFiles');
  22372. me.focus();
  22373. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22374. function callback(){
  22375. try{
  22376. var link, json, loader,
  22377. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22378. result = body.innerText || body.textContent || '';
  22379. json = (new Function("return " + result))();
  22380. link = me.options.imageUrlPrefix + json.url;
  22381. if(json.state == 'SUCCESS' && json.url) {
  22382. loader = me.document.getElementById(loadingId);
  22383. loader.setAttribute('src', link);
  22384. loader.setAttribute('_src', link);
  22385. loader.setAttribute('title', json.title || '');
  22386. loader.setAttribute('alt', json.original || '');
  22387. loader.removeAttribute('id');
  22388. domUtils.removeClasses(loader, 'loadingclass');
  22389. } else {
  22390. showErrorLoader && showErrorLoader(json.state);
  22391. }
  22392. }catch(er){
  22393. showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
  22394. }
  22395. form.reset();
  22396. domUtils.un(iframe, 'load', callback);
  22397. }
  22398. function showErrorLoader(title){
  22399. if(loadingId) {
  22400. var loader = me.document.getElementById(loadingId);
  22401. loader && domUtils.remove(loader);
  22402. me.fireEvent('showmessage', {
  22403. 'id': loadingId,
  22404. 'content': title,
  22405. 'type': 'error',
  22406. 'timeout': 4000
  22407. });
  22408. }
  22409. }
  22410. /* 判断后端配置是否没有加载成功 */
  22411. if (!me.getOpt('imageActionName')) {
  22412. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22413. return;
  22414. }
  22415. // 判断文件格式是否错误
  22416. var filename = input.value,
  22417. fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22418. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22419. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22420. return;
  22421. }
  22422. domUtils.on(iframe, 'load', callback);
  22423. form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22424. form.submit();
  22425. });
  22426. var stateTimer;
  22427. me.addListener('selectionchange', function () {
  22428. clearTimeout(stateTimer);
  22429. stateTimer = setTimeout(function() {
  22430. var state = me.queryCommandState('simpleupload');
  22431. if (state == -1) {
  22432. input.disabled = 'disabled';
  22433. } else {
  22434. input.disabled = false;
  22435. }
  22436. }, 400);
  22437. });
  22438. isLoaded = true;
  22439. });
  22440. btnIframe.style.cssText = btnStyle;
  22441. containerBtn.appendChild(btnIframe);
  22442. }
  22443. return {
  22444. bindEvents:{
  22445. 'ready': function() {
  22446. //设置loading的样式
  22447. utils.cssRule('loading',
  22448. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22449. + this.options.themePath
  22450. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22451. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22452. + this.options.themePath
  22453. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22454. '}',
  22455. this.document);
  22456. },
  22457. /* 初始化简单上传按钮 */
  22458. 'simpleuploadbtnready': function(type, container) {
  22459. containerBtn = container;
  22460. me.afterConfigReady(initUploadBtn);
  22461. }
  22462. },
  22463. outputRule: function(root){
  22464. utils.each(root.getNodesByTagName('img'),function(n){
  22465. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22466. n.parentNode.removeChild(n);
  22467. }
  22468. });
  22469. },
  22470. commands: {
  22471. 'simpleupload': {
  22472. queryCommandState: function () {
  22473. return isLoaded ? 0:-1;
  22474. }
  22475. }
  22476. }
  22477. }
  22478. });
  22479. ///////////////////////////////////////////////////////
  22480. UE.plugin.register('importword', function (){
  22481. var me = this,
  22482. isLoaded = false,
  22483. containerBtn;
  22484. function initUploadBtn(){
  22485. var w = containerBtn.offsetWidth || 20,
  22486. h = containerBtn.offsetHeight || 20,
  22487. btnIframe = document.createElement('iframe'),
  22488. 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;';
  22489. domUtils.on(btnIframe, 'load', function(){
  22490. var timestrap = (+new Date()).toString(36),
  22491. wrapper,
  22492. btnIframeDoc,
  22493. btnIframeBody;
  22494. btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
  22495. btnIframeBody = btnIframeDoc.body;
  22496. wrapper = btnIframeDoc.createElement('div');
  22497. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22498. 'style="' + btnStyle + '">' +
  22499. '<input id="edui_input_' + timestrap + '" type="file" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document" name="' + me.options.imageFieldName + '" ' +
  22500. 'style="' + btnStyle + '">' +
  22501. '</form>' +
  22502. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22503. wrapper.className = 'edui-' + me.options.theme;
  22504. wrapper.id = me.ui.id + '_iframeupload';
  22505. btnIframeBody.style.cssText = btnStyle;
  22506. btnIframeBody.style.width = w + 'px';
  22507. btnIframeBody.style.height = h + 'px';
  22508. btnIframeBody.appendChild(wrapper);
  22509. if (btnIframeBody.parentNode) {
  22510. btnIframeBody.parentNode.style.width = w + 'px';
  22511. btnIframeBody.parentNode.style.height = w + 'px';
  22512. }
  22513. var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
  22514. var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
  22515. var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);
  22516. domUtils.on(input, 'change', function(){
  22517. if(!input.value) return;
  22518. var loadingId = 'loading_' + (+new Date()).toString(36);
  22519. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22520. var imageActionUrl = me.getActionUrl(me.getOpt('fileActionName'));
  22521. var allowFiles = me.getOpt('fileAllowFiles');
  22522. me.focus();
  22523. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('importword.loading') || '') + '" >');
  22524. function callback(){
  22525. try{
  22526. var link, json, loader,
  22527. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22528. result = body.innerText || body.textContent || '';
  22529. json = (new Function("return " + result))();
  22530. link = me.options.imageUrlPrefix + json.url;
  22531. if(json.state == 'SUCCESS' && json.url) {
  22532. $.get(contextPath+"/myconsole/ueditor/word2Html?docPath="+link,function(data){
  22533. /*var loader = me.document.getElementById(loadingId);
  22534. loader && domUtils.remove(loader);
  22535. me.execCommand('inserthtml', data);*/
  22536. me.setContent(data);
  22537. })
  22538. /* loader = me.document.getElementById(loadingId);
  22539. loader.setAttribute('src', link);
  22540. loader.setAttribute('_src', link);
  22541. loader.setAttribute('title', json.title || '');
  22542. loader.setAttribute('alt', json.original || '');
  22543. loader.removeAttribute('id');
  22544. domUtils.removeClasses(loader, 'loadingclass');*/
  22545. } else {
  22546. showErrorLoader && showErrorLoader(json.state);
  22547. }
  22548. }catch(er){
  22549. showErrorLoader && showErrorLoader(me.getLang('importword.loadError'));
  22550. }
  22551. form.reset();
  22552. domUtils.un(iframe, 'load', callback);
  22553. }
  22554. function showErrorLoader(title){
  22555. if(loadingId) {
  22556. var loader = me.document.getElementById(loadingId);
  22557. loader && domUtils.remove(loader);
  22558. me.fireEvent('showmessage', {
  22559. 'id': loadingId,
  22560. 'content': title,
  22561. 'type': 'error',
  22562. 'timeout': 4000
  22563. });
  22564. }
  22565. }
  22566. /* 判断后端配置是否没有加载成功 */
  22567. if (!me.getOpt('fileActionName')) {
  22568. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22569. return;
  22570. }
  22571. // 判断文件格式是否错误
  22572. var filename = input.value,
  22573. fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22574. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22575. showErrorLoader(me.getLang('importword.exceedTypeError'));
  22576. return;
  22577. }
  22578. domUtils.on(iframe, 'load', callback);
  22579. form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22580. form.submit();
  22581. });
  22582. var stateTimer;
  22583. me.addListener('selectionchange', function () {
  22584. clearTimeout(stateTimer);
  22585. stateTimer = setTimeout(function() {
  22586. var state = me.queryCommandState('importword');
  22587. if (state == -1) {
  22588. input.disabled = 'disabled';
  22589. } else {
  22590. input.disabled = false;
  22591. }
  22592. }, 400);
  22593. });
  22594. isLoaded = true;
  22595. });
  22596. btnIframe.style.cssText = btnStyle;
  22597. containerBtn.appendChild(btnIframe);
  22598. }
  22599. return {
  22600. bindEvents:{
  22601. 'ready': function() {
  22602. //设置loading的样式
  22603. utils.cssRule('loading',
  22604. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22605. + this.options.themePath
  22606. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22607. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22608. + this.options.themePath
  22609. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22610. '}',
  22611. this.document);
  22612. },
  22613. /* 初始化简单上传按钮 */
  22614. 'importwordbtnready': function(type, container) {
  22615. containerBtn = container;
  22616. me.afterConfigReady(initUploadBtn);
  22617. }
  22618. },
  22619. outputRule: function(root){
  22620. utils.each(root.getNodesByTagName('img'),function(n){
  22621. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22622. n.parentNode.removeChild(n);
  22623. }
  22624. });
  22625. },
  22626. commands: {
  22627. 'importword': {
  22628. queryCommandState: function () {
  22629. return isLoaded ? 0:-1;
  22630. }
  22631. }
  22632. }
  22633. }
  22634. });
  22635. UE.commands["titlepicbtn"] = {
  22636. execCommand : function(){
  22637. me=this;
  22638. range = me.selection.getRange();
  22639. if(!range.collapsed ){
  22640. var img = range.getClosedNode();
  22641. if(img && img.tagName == 'IMG'){
  22642. var strPicSrc = img.src;
  22643. var sBaseUrl = document.location.protocol + '//' + document.location.host;
  22644. var re = new RegExp(sBaseUrl.replace(/\//, "\/"), "gi");
  22645. var strSrcPicPath = strPicSrc.replace(re, "");
  22646. //var strPicPath = strSrcPicPath.substring(contextPath.length,strSrcPicPath.length);
  22647. document.getElementById("titlepicurl").value = strSrcPicPath;
  22648. }
  22649. }
  22650. },
  22651. queryCommandState : function(){
  22652. return this.highlight ? -1 :0;
  22653. }
  22654. };
  22655. ///////////////////////////////////////////////
  22656. // plugins/serverparam.js
  22657. /**
  22658. * 服务器提交的额外参数列表设置插件
  22659. * @file
  22660. * @since 1.2.6.1
  22661. */
  22662. UE.plugin.register('serverparam', function (){
  22663. var me = this,
  22664. serverParam = {};
  22665. return {
  22666. commands:{
  22667. /**
  22668. * 修改服务器提交的额外参数列表,清除所有项
  22669. * @command serverparam
  22670. * @method execCommand
  22671. * @param { String } cmd 命令字符串
  22672. * @example
  22673. * ```javascript
  22674. * editor.execCommand('serverparam');
  22675. * editor.queryCommandValue('serverparam'); //返回空
  22676. * ```
  22677. */
  22678. /**
  22679. * 修改服务器提交的额外参数列表,删除指定项
  22680. * @command serverparam
  22681. * @method execCommand
  22682. * @param { String } cmd 命令字符串
  22683. * @param { String } key 要清除的属性
  22684. * @example
  22685. * ```javascript
  22686. * editor.execCommand('serverparam', 'name'); //删除属性name
  22687. * ```
  22688. */
  22689. /**
  22690. * 修改服务器提交的额外参数列表,使用键值添加项
  22691. * @command serverparam
  22692. * @method execCommand
  22693. * @param { String } cmd 命令字符串
  22694. * @param { String } key 要添加的属性
  22695. * @param { String } value 要添加属性的值
  22696. * @example
  22697. * ```javascript
  22698. * editor.execCommand('serverparam', 'name', 'hello');
  22699. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22700. * ```
  22701. */
  22702. /**
  22703. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22704. * @command serverparam
  22705. * @method execCommand
  22706. * @param { String } cmd 命令字符串
  22707. * @param { Object } key 传入的键值对对象
  22708. * @example
  22709. * ```javascript
  22710. * editor.execCommand('serverparam', {'name': 'hello'});
  22711. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22712. * ```
  22713. */
  22714. /**
  22715. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22716. * @command serverparam
  22717. * @method execCommand
  22718. * @param { String } cmd 命令字符串
  22719. * @param { Function } key 自定义获取参数的函数
  22720. * @example
  22721. * ```javascript
  22722. * editor.execCommand('serverparam', function(editor){
  22723. * return {'key': 'value'};
  22724. * });
  22725. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22726. * ```
  22727. */
  22728. /**
  22729. * 获取服务器提交的额外参数列表
  22730. * @command serverparam
  22731. * @method queryCommandValue
  22732. * @param { String } cmd 命令字符串
  22733. * @example
  22734. * ```javascript
  22735. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22736. * ```
  22737. */
  22738. 'serverparam':{
  22739. execCommand:function (cmd, key, value) {
  22740. if (key === undefined || key === null) { //不传参数,清空列表
  22741. serverParam = {};
  22742. } else if (utils.isString(key)) { //传入键值
  22743. if(value === undefined || value === null) {
  22744. delete serverParam[key];
  22745. } else {
  22746. serverParam[key] = value;
  22747. }
  22748. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22749. utils.extend(serverParam, key, true);
  22750. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22751. utils.extend(serverParam, key(), true);
  22752. }
  22753. },
  22754. queryCommandValue: function(){
  22755. return serverParam || {};
  22756. }
  22757. }
  22758. }
  22759. }
  22760. });
  22761. // plugins/insertfile.js
  22762. /**
  22763. * 插入附件
  22764. */
  22765. UE.plugin.register('insertfile', function (){
  22766. var me = this;
  22767. function getFileIcon(url){
  22768. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22769. maps = {
  22770. "rar":"icon_rar.gif",
  22771. "zip":"icon_rar.gif",
  22772. "tar":"icon_rar.gif",
  22773. "gz":"icon_rar.gif",
  22774. "bz2":"icon_rar.gif",
  22775. "doc":"icon_doc.gif",
  22776. "docx":"icon_doc.gif",
  22777. "pdf":"icon_pdf.gif",
  22778. "mp3":"icon_mp3.gif",
  22779. "xls":"icon_xls.gif",
  22780. "chm":"icon_chm.gif",
  22781. "ppt":"icon_ppt.gif",
  22782. "pptx":"icon_ppt.gif",
  22783. "avi":"icon_mv.gif",
  22784. "rmvb":"icon_mv.gif",
  22785. "wmv":"icon_mv.gif",
  22786. "flv":"icon_mv.gif",
  22787. "swf":"icon_mv.gif",
  22788. "rm":"icon_mv.gif",
  22789. "exe":"icon_exe.gif",
  22790. "psd":"icon_psd.gif",
  22791. "txt":"icon_txt.gif",
  22792. "jpg":"icon_jpg.gif",
  22793. "png":"icon_jpg.gif",
  22794. "jpeg":"icon_jpg.gif",
  22795. "gif":"icon_jpg.gif",
  22796. "ico":"icon_jpg.gif",
  22797. "bmp":"icon_jpg.gif"
  22798. };
  22799. return maps[ext] ? maps[ext]:maps['txt'];
  22800. }
  22801. return {
  22802. commands:{
  22803. 'insertfile': {
  22804. execCommand: function (command, filelist){
  22805. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22806. var i, item, icon, title,
  22807. html = '',
  22808. URL = me.getOpt('UEDITOR_HOME_URL'),
  22809. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22810. for (i = 0; i < filelist.length; i++) {
  22811. item = filelist[i];
  22812. icon = iconDir + getFileIcon(item.url);
  22813. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22814. html += '<p style="line-height: 16px;">' +
  22815. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22816. '<a style="color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22817. '</p>';
  22818. }
  22819. me.execCommand('insertHtml', html);
  22820. }
  22821. }
  22822. }
  22823. }
  22824. });
  22825. // ui/ui.js
  22826. var baidu = baidu || {};
  22827. baidu.editor = baidu.editor || {};
  22828. UE.ui = baidu.editor.ui = {};
  22829. // ui/uiutils.js
  22830. (function (){
  22831. var browser = baidu.editor.browser,
  22832. domUtils = baidu.editor.dom.domUtils;
  22833. var magic = '$EDITORUI';
  22834. var root = window[magic] = {};
  22835. var uidMagic = 'ID' + magic;
  22836. var uidCount = 0;
  22837. var uiUtils = baidu.editor.ui.uiUtils = {
  22838. uid: function (obj){
  22839. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22840. },
  22841. hook: function ( fn, callback ) {
  22842. var dg;
  22843. if (fn && fn._callbacks) {
  22844. dg = fn;
  22845. } else {
  22846. dg = function (){
  22847. var q;
  22848. if (fn) {
  22849. q = fn.apply(this, arguments);
  22850. }
  22851. var callbacks = dg._callbacks;
  22852. var k = callbacks.length;
  22853. while (k --) {
  22854. var r = callbacks[k].apply(this, arguments);
  22855. if (q === undefined) {
  22856. q = r;
  22857. }
  22858. }
  22859. return q;
  22860. };
  22861. dg._callbacks = [];
  22862. }
  22863. dg._callbacks.push(callback);
  22864. return dg;
  22865. },
  22866. createElementByHtml: function (html){
  22867. var el = document.createElement('div');
  22868. el.innerHTML = html;
  22869. el = el.firstChild;
  22870. el.parentNode.removeChild(el);
  22871. return el;
  22872. },
  22873. getViewportElement: function (){
  22874. return (browser.ie && browser.quirks) ?
  22875. document.body : document.documentElement;
  22876. },
  22877. getClientRect: function (element){
  22878. var bcr;
  22879. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22880. try{
  22881. bcr = element.getBoundingClientRect();
  22882. }catch(e){
  22883. bcr={left:0,top:0,height:0,width:0}
  22884. }
  22885. var rect = {
  22886. left: Math.round(bcr.left),
  22887. top: Math.round(bcr.top),
  22888. height: Math.round(bcr.bottom - bcr.top),
  22889. width: Math.round(bcr.right - bcr.left)
  22890. };
  22891. var doc;
  22892. while ((doc = element.ownerDocument) !== document &&
  22893. (element = domUtils.getWindow(doc).frameElement)) {
  22894. bcr = element.getBoundingClientRect();
  22895. rect.left += bcr.left;
  22896. rect.top += bcr.top;
  22897. }
  22898. rect.bottom = rect.top + rect.height;
  22899. rect.right = rect.left + rect.width;
  22900. return rect;
  22901. },
  22902. getViewportRect: function (){
  22903. var viewportEl = uiUtils.getViewportElement();
  22904. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22905. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22906. return {
  22907. left: 0,
  22908. top: 0,
  22909. height: height,
  22910. width: width,
  22911. bottom: height,
  22912. right: width
  22913. };
  22914. },
  22915. setViewportOffset: function (element, offset){
  22916. var rect;
  22917. var fixedLayer = uiUtils.getFixedLayer();
  22918. if (element.parentNode === fixedLayer) {
  22919. element.style.left = offset.left + 'px';
  22920. element.style.top = offset.top + 'px';
  22921. } else {
  22922. domUtils.setViewportOffset(element, offset);
  22923. }
  22924. },
  22925. getEventOffset: function (evt){
  22926. var el = evt.target || evt.srcElement;
  22927. var rect = uiUtils.getClientRect(el);
  22928. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22929. return {
  22930. left: offset.left - rect.left,
  22931. top: offset.top - rect.top
  22932. };
  22933. },
  22934. getViewportOffsetByEvent: function (evt){
  22935. var el = evt.target || evt.srcElement;
  22936. var frameEl = domUtils.getWindow(el).frameElement;
  22937. var offset = {
  22938. left: evt.clientX,
  22939. top: evt.clientY
  22940. };
  22941. if (frameEl && el.ownerDocument !== document) {
  22942. var rect = uiUtils.getClientRect(frameEl);
  22943. offset.left += rect.left;
  22944. offset.top += rect.top;
  22945. }
  22946. return offset;
  22947. },
  22948. setGlobal: function (id, obj){
  22949. root[id] = obj;
  22950. return magic + '["' + id + '"]';
  22951. },
  22952. unsetGlobal: function (id){
  22953. delete root[id];
  22954. },
  22955. copyAttributes: function (tgt, src){
  22956. var attributes = src.attributes;
  22957. var k = attributes.length;
  22958. while (k --) {
  22959. var attrNode = attributes[k];
  22960. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22961. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22962. }
  22963. }
  22964. if (src.className) {
  22965. domUtils.addClass(tgt,src.className);
  22966. }
  22967. if (src.style.cssText) {
  22968. tgt.style.cssText += ';' + src.style.cssText;
  22969. }
  22970. },
  22971. removeStyle: function (el, styleName){
  22972. if (el.style.removeProperty) {
  22973. el.style.removeProperty(styleName);
  22974. } else if (el.style.removeAttribute) {
  22975. el.style.removeAttribute(styleName);
  22976. } else throw '';
  22977. },
  22978. contains: function (elA, elB){
  22979. return elA && elB && (elA === elB ? false : (
  22980. elA.contains ? elA.contains(elB) :
  22981. elA.compareDocumentPosition(elB) & 16
  22982. ));
  22983. },
  22984. startDrag: function (evt, callbacks,doc){
  22985. var doc = doc || document;
  22986. var startX = evt.clientX;
  22987. var startY = evt.clientY;
  22988. function handleMouseMove(evt){
  22989. var x = evt.clientX - startX;
  22990. var y = evt.clientY - startY;
  22991. callbacks.ondragmove(x, y,evt);
  22992. if (evt.stopPropagation) {
  22993. evt.stopPropagation();
  22994. } else {
  22995. evt.cancelBubble = true;
  22996. }
  22997. }
  22998. if (doc.addEventListener) {
  22999. function handleMouseUp(evt){
  23000. doc.removeEventListener('mousemove', handleMouseMove, true);
  23001. doc.removeEventListener('mouseup', handleMouseUp, true);
  23002. window.removeEventListener('mouseup', handleMouseUp, true);
  23003. callbacks.ondragstop();
  23004. }
  23005. doc.addEventListener('mousemove', handleMouseMove, true);
  23006. doc.addEventListener('mouseup', handleMouseUp, true);
  23007. window.addEventListener('mouseup', handleMouseUp, true);
  23008. evt.preventDefault();
  23009. } else {
  23010. var elm = evt.srcElement;
  23011. elm.setCapture();
  23012. function releaseCaptrue(){
  23013. elm.releaseCapture();
  23014. elm.detachEvent('onmousemove', handleMouseMove);
  23015. elm.detachEvent('onmouseup', releaseCaptrue);
  23016. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  23017. callbacks.ondragstop();
  23018. }
  23019. elm.attachEvent('onmousemove', handleMouseMove);
  23020. elm.attachEvent('onmouseup', releaseCaptrue);
  23021. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  23022. evt.returnValue = false;
  23023. }
  23024. callbacks.ondragstart();
  23025. },
  23026. getFixedLayer: function (){
  23027. var layer = document.getElementById('edui_fixedlayer');
  23028. if (layer == null) {
  23029. layer = document.createElement('div');
  23030. layer.id = 'edui_fixedlayer';
  23031. document.body.appendChild(layer);
  23032. if (browser.ie && browser.version <= 8) {
  23033. layer.style.position = 'absolute';
  23034. bindFixedLayer();
  23035. setTimeout(updateFixedOffset);
  23036. } else {
  23037. layer.style.position = 'fixed';
  23038. }
  23039. layer.style.left = '0';
  23040. layer.style.top = '0';
  23041. layer.style.width = '0';
  23042. layer.style.height = '0';
  23043. }
  23044. return layer;
  23045. },
  23046. makeUnselectable: function (element){
  23047. if (browser.opera || (browser.ie && browser.version < 9)) {
  23048. element.unselectable = 'on';
  23049. if (element.hasChildNodes()) {
  23050. for (var i=0; i<element.childNodes.length; i++) {
  23051. if (element.childNodes[i].nodeType == 1) {
  23052. uiUtils.makeUnselectable(element.childNodes[i]);
  23053. }
  23054. }
  23055. }
  23056. } else {
  23057. if (element.style.MozUserSelect !== undefined) {
  23058. element.style.MozUserSelect = 'none';
  23059. } else if (element.style.WebkitUserSelect !== undefined) {
  23060. element.style.WebkitUserSelect = 'none';
  23061. } else if (element.style.KhtmlUserSelect !== undefined) {
  23062. element.style.KhtmlUserSelect = 'none';
  23063. }
  23064. }
  23065. }
  23066. };
  23067. function updateFixedOffset(){
  23068. var layer = document.getElementById('edui_fixedlayer');
  23069. uiUtils.setViewportOffset(layer, {
  23070. left: 0,
  23071. top: 0
  23072. });
  23073. // layer.style.display = 'none';
  23074. // layer.style.display = 'block';
  23075. //#trace: 1354
  23076. // setTimeout(updateFixedOffset);
  23077. }
  23078. function bindFixedLayer(adjOffset){
  23079. domUtils.on(window, 'scroll', updateFixedOffset);
  23080. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  23081. }
  23082. })();
  23083. // ui/uibase.js
  23084. (function () {
  23085. var utils = baidu.editor.utils,
  23086. uiUtils = baidu.editor.ui.uiUtils,
  23087. EventBase = baidu.editor.EventBase,
  23088. UIBase = baidu.editor.ui.UIBase = function () {
  23089. };
  23090. UIBase.prototype = {
  23091. className:'',
  23092. uiName:'',
  23093. initOptions:function (options) {
  23094. var me = this;
  23095. for (var k in options) {
  23096. me[k] = options[k];
  23097. }
  23098. this.id = this.id || 'edui' + uiUtils.uid();
  23099. },
  23100. initUIBase:function () {
  23101. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23102. },
  23103. render:function (holder) {
  23104. var html = this.renderHtml();
  23105. var el = uiUtils.createElementByHtml(html);
  23106. //by xuheng 给每个node添加class
  23107. var list = domUtils.getElementsByTagName(el, "*");
  23108. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23109. var layer = document.getElementById('edui_fixedlayer');
  23110. for (var i = 0, node; node = list[i++];) {
  23111. domUtils.addClass(node, theme);
  23112. }
  23113. domUtils.addClass(el, theme);
  23114. if(layer){
  23115. layer.className="";
  23116. domUtils.addClass(layer,theme);
  23117. }
  23118. var seatEl = this.getDom();
  23119. if (seatEl != null) {
  23120. seatEl.parentNode.replaceChild(el, seatEl);
  23121. uiUtils.copyAttributes(el, seatEl);
  23122. } else {
  23123. if (typeof holder == 'string') {
  23124. holder = document.getElementById(holder);
  23125. }
  23126. holder = holder || uiUtils.getFixedLayer();
  23127. domUtils.addClass(holder, theme);
  23128. holder.appendChild(el);
  23129. }
  23130. this.postRender();
  23131. },
  23132. getDom:function (name) {
  23133. if (!name) {
  23134. return document.getElementById(this.id);
  23135. } else {
  23136. return document.getElementById(this.id + '_' + name);
  23137. }
  23138. },
  23139. postRender:function () {
  23140. this.fireEvent('postrender');
  23141. },
  23142. getHtmlTpl:function () {
  23143. return '';
  23144. },
  23145. formatHtml:function (tpl) {
  23146. var prefix = 'edui-' + this.uiName;
  23147. return (tpl
  23148. .replace(/##/g, this.id)
  23149. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23150. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23151. .replace(/\$\$/g, this._globalKey));
  23152. },
  23153. renderHtml:function () {
  23154. return this.formatHtml(this.getHtmlTpl());
  23155. },
  23156. dispose:function () {
  23157. var box = this.getDom();
  23158. if (box) baidu.editor.dom.domUtils.remove(box);
  23159. uiUtils.unsetGlobal(this.id);
  23160. }
  23161. };
  23162. utils.inherits(UIBase, EventBase);
  23163. })();
  23164. // ui/separator.js
  23165. (function (){
  23166. var utils = baidu.editor.utils,
  23167. UIBase = baidu.editor.ui.UIBase,
  23168. Separator = baidu.editor.ui.Separator = function (options){
  23169. this.initOptions(options);
  23170. this.initSeparator();
  23171. };
  23172. Separator.prototype = {
  23173. uiName: 'separator',
  23174. initSeparator: function (){
  23175. this.initUIBase();
  23176. },
  23177. getHtmlTpl: function (){
  23178. return '<div id="##" class="edui-box %%"></div>';
  23179. }
  23180. };
  23181. utils.inherits(Separator, UIBase);
  23182. })();
  23183. // ui/mask.js
  23184. ///import core
  23185. ///import uicore
  23186. (function (){
  23187. var utils = baidu.editor.utils,
  23188. domUtils = baidu.editor.dom.domUtils,
  23189. UIBase = baidu.editor.ui.UIBase,
  23190. uiUtils = baidu.editor.ui.uiUtils;
  23191. var Mask = baidu.editor.ui.Mask = function (options){
  23192. this.initOptions(options);
  23193. this.initUIBase();
  23194. };
  23195. Mask.prototype = {
  23196. getHtmlTpl: function (){
  23197. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23198. },
  23199. postRender: function (){
  23200. var me = this;
  23201. domUtils.on(window, 'resize', function (){
  23202. setTimeout(function (){
  23203. if (!me.isHidden()) {
  23204. me._fill();
  23205. }
  23206. });
  23207. });
  23208. },
  23209. show: function (zIndex){
  23210. this._fill();
  23211. this.getDom().style.display = '';
  23212. this.getDom().style.zIndex = zIndex;
  23213. },
  23214. hide: function (){
  23215. this.getDom().style.display = 'none';
  23216. this.getDom().style.zIndex = '';
  23217. },
  23218. isHidden: function (){
  23219. return this.getDom().style.display == 'none';
  23220. },
  23221. _onMouseDown: function (){
  23222. return false;
  23223. },
  23224. _onClick: function (e, target){
  23225. this.fireEvent('click', e, target);
  23226. },
  23227. _fill: function (){
  23228. var el = this.getDom();
  23229. var vpRect = uiUtils.getViewportRect();
  23230. el.style.width = vpRect.width + 'px';
  23231. el.style.height = vpRect.height + 'px';
  23232. }
  23233. };
  23234. utils.inherits(Mask, UIBase);
  23235. })();
  23236. // ui/popup.js
  23237. ///import core
  23238. ///import uicore
  23239. (function () {
  23240. var utils = baidu.editor.utils,
  23241. uiUtils = baidu.editor.ui.uiUtils,
  23242. domUtils = baidu.editor.dom.domUtils,
  23243. UIBase = baidu.editor.ui.UIBase,
  23244. Popup = baidu.editor.ui.Popup = function (options){
  23245. this.initOptions(options);
  23246. this.initPopup();
  23247. };
  23248. var allPopups = [];
  23249. function closeAllPopup( evt,el ){
  23250. for ( var i = 0; i < allPopups.length; i++ ) {
  23251. var pop = allPopups[i];
  23252. if (!pop.isHidden()) {
  23253. if (pop.queryAutoHide(el) !== false) {
  23254. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23255. pop.hide();
  23256. }
  23257. }
  23258. }
  23259. if(allPopups.length)
  23260. pop.editor.fireEvent("afterhidepop");
  23261. }
  23262. Popup.postHide = closeAllPopup;
  23263. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23264. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23265. Popup.prototype = {
  23266. SHADOW_RADIUS: 5,
  23267. content: null,
  23268. _hidden: false,
  23269. autoRender: true,
  23270. canSideLeft: true,
  23271. canSideUp: true,
  23272. initPopup: function (){
  23273. this.initUIBase();
  23274. allPopups.push( this );
  23275. },
  23276. getHtmlTpl: function (){
  23277. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23278. ' <div id="##_body" class="edui-popup-body">' +
  23279. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23280. ' <div class="edui-shadow"></div>' +
  23281. ' <div id="##_content" class="edui-popup-content">' +
  23282. this.getContentHtmlTpl() +
  23283. ' </div>' +
  23284. ' </div>' +
  23285. '</div>';
  23286. },
  23287. getContentHtmlTpl: function (){
  23288. if(this.content){
  23289. if (typeof this.content == 'string') {
  23290. return this.content;
  23291. }
  23292. return this.content.renderHtml();
  23293. }else{
  23294. return ''
  23295. }
  23296. },
  23297. _UIBase_postRender: UIBase.prototype.postRender,
  23298. postRender: function (){
  23299. if (this.content instanceof UIBase) {
  23300. this.content.postRender();
  23301. }
  23302. //捕获鼠标滚轮
  23303. if( this.captureWheel && !this.captured ) {
  23304. this.captured = true;
  23305. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23306. _height = this.getDom().offsetHeight,
  23307. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23308. content = this.getDom('content'),
  23309. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23310. me = this;
  23311. ifr.length && ( ifr = ifr[0] );
  23312. while( _top + _height > winHeight ) {
  23313. _height -= 30;
  23314. }
  23315. content.style.height = _height + 'px';
  23316. //同步更改iframe高度
  23317. ifr && ( ifr.style.height = _height + 'px' );
  23318. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23319. if( window.XMLHttpRequest ) {
  23320. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23321. if(e.preventDefault) {
  23322. e.preventDefault();
  23323. } else {
  23324. e.returnValue = false;
  23325. }
  23326. if( e.wheelDelta ) {
  23327. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23328. } else {
  23329. content.scrollTop -= ( e.detail / -3 )*60;
  23330. }
  23331. });
  23332. } else {
  23333. //ie6
  23334. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23335. e.returnValue = false;
  23336. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23337. });
  23338. }
  23339. }
  23340. this.fireEvent('postRenderAfter');
  23341. this.hide(true);
  23342. this._UIBase_postRender();
  23343. },
  23344. _doAutoRender: function (){
  23345. if (!this.getDom() && this.autoRender) {
  23346. this.render();
  23347. }
  23348. },
  23349. mesureSize: function (){
  23350. var box = this.getDom('content');
  23351. return uiUtils.getClientRect(box);
  23352. },
  23353. fitSize: function (){
  23354. if( this.captureWheel && this.sized ) {
  23355. return this.__size;
  23356. }
  23357. this.sized = true;
  23358. var popBodyEl = this.getDom('body');
  23359. popBodyEl.style.width = '';
  23360. popBodyEl.style.height = '';
  23361. var size = this.mesureSize();
  23362. if( this.captureWheel ) {
  23363. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23364. var height = parseInt( this.getDom('content').style.height, 10 );
  23365. !window.isNaN( height ) && ( size.height = height );
  23366. } else {
  23367. popBodyEl.style.width = size.width + 'px';
  23368. }
  23369. popBodyEl.style.height = size.height + 'px';
  23370. this.__size = size;
  23371. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23372. return size;
  23373. },
  23374. showAnchor: function ( element, hoz ){
  23375. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23376. },
  23377. showAnchorRect: function ( rect, hoz, adj ){
  23378. this._doAutoRender();
  23379. var vpRect = uiUtils.getViewportRect();
  23380. this.getDom().style.visibility = 'hidden';
  23381. this._show();
  23382. var popSize = this.fitSize();
  23383. var sideLeft, sideUp, left, top;
  23384. if (hoz) {
  23385. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23386. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23387. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23388. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23389. } else {
  23390. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23391. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23392. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23393. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23394. }
  23395. var popEl = this.getDom();
  23396. uiUtils.setViewportOffset(popEl, {
  23397. left: left,
  23398. top: top
  23399. });
  23400. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23401. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23402. if(this.editor){
  23403. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23404. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23405. }
  23406. this.getDom().style.visibility = 'visible';
  23407. },
  23408. showAt: function (offset) {
  23409. var left = offset.left;
  23410. var top = offset.top;
  23411. var rect = {
  23412. left: left,
  23413. top: top,
  23414. right: left,
  23415. bottom: top,
  23416. height: 0,
  23417. width: 0
  23418. };
  23419. this.showAnchorRect(rect, false, true);
  23420. },
  23421. _show: function (){
  23422. if (this._hidden) {
  23423. var box = this.getDom();
  23424. box.style.display = '';
  23425. this._hidden = false;
  23426. // if (box.setActive) {
  23427. // box.setActive();
  23428. // }
  23429. this.fireEvent('show');
  23430. }
  23431. },
  23432. isHidden: function (){
  23433. return this._hidden;
  23434. },
  23435. show: function (){
  23436. this._doAutoRender();
  23437. this._show();
  23438. },
  23439. hide: function (notNofity){
  23440. if (!this._hidden && this.getDom()) {
  23441. this.getDom().style.display = 'none';
  23442. this._hidden = true;
  23443. if (!notNofity) {
  23444. this.fireEvent('hide');
  23445. }
  23446. }
  23447. },
  23448. queryAutoHide: function (el){
  23449. return !el || !uiUtils.contains(this.getDom(), el);
  23450. }
  23451. };
  23452. utils.inherits(Popup, UIBase);
  23453. domUtils.on( document, 'mousedown', function ( evt ) {
  23454. var el = evt.target || evt.srcElement;
  23455. closeAllPopup( evt,el );
  23456. } );
  23457. domUtils.on( window, 'scroll', function (evt,el) {
  23458. closeAllPopup( evt,el );
  23459. } );
  23460. })();
  23461. // ui/colorpicker.js
  23462. ///import core
  23463. ///import uicore
  23464. (function (){
  23465. var utils = baidu.editor.utils,
  23466. UIBase = baidu.editor.ui.UIBase,
  23467. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23468. this.initOptions(options);
  23469. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23470. this.initUIBase();
  23471. };
  23472. ColorPicker.prototype = {
  23473. getHtmlTpl: function (){
  23474. return genColorPicker(this.noColorText,this.editor);
  23475. },
  23476. _onTableClick: function (evt){
  23477. var tgt = evt.target || evt.srcElement;
  23478. var color = tgt.getAttribute('data-color');
  23479. if (color) {
  23480. this.fireEvent('pickcolor', color);
  23481. }
  23482. },
  23483. _onTableOver: function (evt){
  23484. var tgt = evt.target || evt.srcElement;
  23485. var color = tgt.getAttribute('data-color');
  23486. if (color) {
  23487. this.getDom('preview').style.backgroundColor = color;
  23488. }
  23489. },
  23490. _onTableOut: function (){
  23491. this.getDom('preview').style.backgroundColor = '';
  23492. },
  23493. _onPickNoColor: function (){
  23494. this.fireEvent('picknocolor');
  23495. }
  23496. };
  23497. utils.inherits(ColorPicker, UIBase);
  23498. var COLORS = (
  23499. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23500. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23501. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23502. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23503. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23504. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23505. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23506. function genColorPicker(noColorText,editor){
  23507. var html = '<div id="##" class="edui-colorpicker %%">' +
  23508. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23509. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23510. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23511. '</div>' +
  23512. '<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">' +
  23513. '<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>'+
  23514. '<tr class="edui-colorpicker-tablefirstrow" >';
  23515. for (var i=0; i<COLORS.length; i++) {
  23516. if (i && i%10 === 0) {
  23517. 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"':'')+'>';
  23518. }
  23519. 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"' +
  23520. ' data-color="#'+ COLORS[i] +'"'+
  23521. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23522. (i<10 || i>=60?'border-width:1px;':
  23523. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23524. 'border-width:0 1px 0 1px;')+
  23525. '"' +
  23526. '></a></td>':'';
  23527. }
  23528. html += '</tr></table></div>';
  23529. return html;
  23530. }
  23531. })();
  23532. // ui/tablepicker.js
  23533. ///import core
  23534. ///import uicore
  23535. (function (){
  23536. var utils = baidu.editor.utils,
  23537. uiUtils = baidu.editor.ui.uiUtils,
  23538. UIBase = baidu.editor.ui.UIBase;
  23539. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23540. this.initOptions(options);
  23541. this.initTablePicker();
  23542. };
  23543. TablePicker.prototype = {
  23544. defaultNumRows: 10,
  23545. defaultNumCols: 10,
  23546. maxNumRows: 20,
  23547. maxNumCols: 20,
  23548. numRows: 10,
  23549. numCols: 10,
  23550. lengthOfCellSide: 22,
  23551. initTablePicker: function (){
  23552. this.initUIBase();
  23553. },
  23554. getHtmlTpl: function (){
  23555. var me = this;
  23556. return '<div id="##" class="edui-tablepicker %%">' +
  23557. '<div class="edui-tablepicker-body">' +
  23558. '<div class="edui-infoarea">' +
  23559. '<span id="##_label" class="edui-label"></span>' +
  23560. '</div>' +
  23561. '<div class="edui-pickarea"' +
  23562. ' onmousemove="$$._onMouseMove(event, this);"' +
  23563. ' onmouseover="$$._onMouseOver(event, this);"' +
  23564. ' onmouseout="$$._onMouseOut(event, this);"' +
  23565. ' onclick="$$._onClick(event, this);"' +
  23566. '>' +
  23567. '<div id="##_overlay" class="edui-overlay"></div>' +
  23568. '</div>' +
  23569. '</div>' +
  23570. '</div>';
  23571. },
  23572. _UIBase_render: UIBase.prototype.render,
  23573. render: function (holder){
  23574. this._UIBase_render(holder);
  23575. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23576. },
  23577. _track: function (numCols, numRows){
  23578. var style = this.getDom('overlay').style;
  23579. var sideLen = this.lengthOfCellSide;
  23580. style.width = numCols * sideLen + 'px';
  23581. style.height = numRows * sideLen + 'px';
  23582. var label = this.getDom('label');
  23583. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23584. this.numCols = numCols;
  23585. this.numRows = numRows;
  23586. },
  23587. _onMouseOver: function (evt, el){
  23588. var rel = evt.relatedTarget || evt.fromElement;
  23589. if (!uiUtils.contains(el, rel) && el !== rel) {
  23590. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23591. this.getDom('overlay').style.visibility = '';
  23592. }
  23593. },
  23594. _onMouseOut: function (evt, el){
  23595. var rel = evt.relatedTarget || evt.toElement;
  23596. if (!uiUtils.contains(el, rel) && el !== rel) {
  23597. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23598. this.getDom('overlay').style.visibility = 'hidden';
  23599. }
  23600. },
  23601. _onMouseMove: function (evt, el){
  23602. var style = this.getDom('overlay').style;
  23603. var offset = uiUtils.getEventOffset(evt);
  23604. var sideLen = this.lengthOfCellSide;
  23605. var numCols = Math.ceil(offset.left / sideLen);
  23606. var numRows = Math.ceil(offset.top / sideLen);
  23607. this._track(numCols, numRows);
  23608. },
  23609. _onClick: function (){
  23610. this.fireEvent('picktable', this.numCols, this.numRows);
  23611. }
  23612. };
  23613. utils.inherits(TablePicker, UIBase);
  23614. })();
  23615. // ui/stateful.js
  23616. (function (){
  23617. var browser = baidu.editor.browser,
  23618. domUtils = baidu.editor.dom.domUtils,
  23619. uiUtils = baidu.editor.ui.uiUtils;
  23620. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23621. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23622. ( browser.ie ? (
  23623. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23624. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23625. : (
  23626. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23627. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23628. baidu.editor.ui.Stateful = {
  23629. alwalysHoverable: false,
  23630. target:null,//目标元素和this指向dom不一样
  23631. Stateful_init: function (){
  23632. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23633. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23634. },
  23635. Stateful_getHtmlTpl: function (){
  23636. var tpl = this._Stateful_dGetHtmlTpl();
  23637. // 使用function避免$转义
  23638. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23639. },
  23640. Stateful_onMouseEnter: function (evt, el){
  23641. this.target=el;
  23642. if (!this.isDisabled() || this.alwalysHoverable) {
  23643. this.addState('hover');
  23644. this.fireEvent('over');
  23645. }
  23646. },
  23647. Stateful_onMouseLeave: function (evt, el){
  23648. if (!this.isDisabled() || this.alwalysHoverable) {
  23649. this.removeState('hover');
  23650. this.removeState('active');
  23651. this.fireEvent('out');
  23652. }
  23653. },
  23654. Stateful_onMouseOver: function (evt, el){
  23655. var rel = evt.relatedTarget;
  23656. if (!uiUtils.contains(el, rel) && el !== rel) {
  23657. this.Stateful_onMouseEnter(evt, el);
  23658. }
  23659. },
  23660. Stateful_onMouseOut: function (evt, el){
  23661. var rel = evt.relatedTarget;
  23662. if (!uiUtils.contains(el, rel) && el !== rel) {
  23663. this.Stateful_onMouseLeave(evt, el);
  23664. }
  23665. },
  23666. Stateful_onMouseDown: function (evt, el){
  23667. if (!this.isDisabled()) {
  23668. this.addState('active');
  23669. }
  23670. },
  23671. Stateful_onMouseUp: function (evt, el){
  23672. if (!this.isDisabled()) {
  23673. this.removeState('active');
  23674. }
  23675. },
  23676. Stateful_postRender: function (){
  23677. if (this.disabled && !this.hasState('disabled')) {
  23678. this.addState('disabled');
  23679. }
  23680. },
  23681. hasState: function (state){
  23682. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23683. },
  23684. addState: function (state){
  23685. if (!this.hasState(state)) {
  23686. this.getStateDom().className += ' edui-state-' + state;
  23687. }
  23688. },
  23689. removeState: function (state){
  23690. if (this.hasState(state)) {
  23691. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23692. }
  23693. },
  23694. getStateDom: function (){
  23695. return this.getDom('state');
  23696. },
  23697. isChecked: function (){
  23698. return this.hasState('checked');
  23699. },
  23700. setChecked: function (checked){
  23701. if (!this.isDisabled() && checked) {
  23702. this.addState('checked');
  23703. } else {
  23704. this.removeState('checked');
  23705. }
  23706. },
  23707. isDisabled: function (){
  23708. return this.hasState('disabled');
  23709. },
  23710. setDisabled: function (disabled){
  23711. if (disabled) {
  23712. this.removeState('hover');
  23713. this.removeState('checked');
  23714. this.removeState('active');
  23715. this.addState('disabled');
  23716. } else {
  23717. this.removeState('disabled');
  23718. }
  23719. }
  23720. };
  23721. })();
  23722. // ui/button.js
  23723. ///import core
  23724. ///import uicore
  23725. ///import ui/stateful.js
  23726. (function (){
  23727. var utils = baidu.editor.utils,
  23728. UIBase = baidu.editor.ui.UIBase,
  23729. Stateful = baidu.editor.ui.Stateful,
  23730. Button = baidu.editor.ui.Button = function (options){
  23731. if(options.name){
  23732. var btnName = options.name;
  23733. var cssRules = options.cssRules;
  23734. if(!options.className){
  23735. options.className = 'edui-for-' + btnName;
  23736. }
  23737. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23738. }
  23739. this.initOptions(options);
  23740. this.initButton();
  23741. };
  23742. Button.prototype = {
  23743. uiName: 'button',
  23744. label: '',
  23745. title: '',
  23746. showIcon: true,
  23747. showText: true,
  23748. cssRules:'',
  23749. initButton: function (){
  23750. this.initUIBase();
  23751. this.Stateful_init();
  23752. if(this.cssRules){
  23753. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23754. }
  23755. },
  23756. getHtmlTpl: function (){
  23757. return '<div id="##" class="edui-box %%">' +
  23758. '<div id="##_state" stateful>' +
  23759. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23760. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23761. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23762. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23763. '</div>' +
  23764. '</div>' +
  23765. '</div></div>';
  23766. },
  23767. postRender: function (){
  23768. this.Stateful_postRender();
  23769. this.setDisabled(this.disabled)
  23770. },
  23771. _onMouseDown: function (e){
  23772. var target = e.target || e.srcElement;
  23773. if (!(target && target.tagName && (target.tagName.toLowerCase() == 'input' || target.tagName.toLowerCase() == 'object'))) {
  23774. return false;
  23775. }
  23776. },
  23777. _onClick: function (){
  23778. if (!this.isDisabled()) {
  23779. this.fireEvent('click');
  23780. }
  23781. },
  23782. setTitle: function(text){
  23783. var label = this.getDom('label');
  23784. label.innerHTML = text;
  23785. }
  23786. };
  23787. utils.inherits(Button, UIBase);
  23788. utils.extend(Button.prototype, Stateful);
  23789. })();
  23790. // ui/splitbutton.js
  23791. ///import core
  23792. ///import uicore
  23793. ///import ui/stateful.js
  23794. (function (){
  23795. var utils = baidu.editor.utils,
  23796. uiUtils = baidu.editor.ui.uiUtils,
  23797. domUtils = baidu.editor.dom.domUtils,
  23798. UIBase = baidu.editor.ui.UIBase,
  23799. Stateful = baidu.editor.ui.Stateful,
  23800. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23801. this.initOptions(options);
  23802. this.initSplitButton();
  23803. };
  23804. SplitButton.prototype = {
  23805. popup: null,
  23806. uiName: 'splitbutton',
  23807. title: '',
  23808. initSplitButton: function (){
  23809. this.initUIBase();
  23810. this.Stateful_init();
  23811. var me = this;
  23812. if (this.popup != null) {
  23813. var popup = this.popup;
  23814. this.popup = null;
  23815. this.setPopup(popup);
  23816. }
  23817. },
  23818. _UIBase_postRender: UIBase.prototype.postRender,
  23819. postRender: function (){
  23820. this.Stateful_postRender();
  23821. this._UIBase_postRender();
  23822. },
  23823. setPopup: function (popup){
  23824. if (this.popup === popup) return;
  23825. if (this.popup != null) {
  23826. this.popup.dispose();
  23827. }
  23828. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23829. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23830. popup.addListener('postrender', utils.bind(function (){
  23831. popup.getDom('body').appendChild(
  23832. uiUtils.createElementByHtml('<div id="' +
  23833. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23834. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23835. );
  23836. popup.getDom().className += ' ' + this.className;
  23837. }, this));
  23838. this.popup = popup;
  23839. },
  23840. _onPopupShow: function (){
  23841. this.addState('opened');
  23842. },
  23843. _onPopupHide: function (){
  23844. this.removeState('opened');
  23845. },
  23846. getHtmlTpl: function (){
  23847. return '<div id="##" class="edui-box %%">' +
  23848. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23849. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23850. '<div class="edui-box edui-icon"></div>' +
  23851. '</div>' +
  23852. '<div class="edui-box edui-splitborder"></div>' +
  23853. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23854. '</div></div></div>';
  23855. },
  23856. showPopup: function (){
  23857. // 当popup往上弹出的时候,做特殊处理
  23858. var rect = uiUtils.getClientRect(this.getDom());
  23859. rect.top -= this.popup.SHADOW_RADIUS;
  23860. rect.height += this.popup.SHADOW_RADIUS;
  23861. this.popup.showAnchorRect(rect);
  23862. },
  23863. _onArrowClick: function (event, el){
  23864. if (!this.isDisabled()) {
  23865. this.showPopup();
  23866. }
  23867. },
  23868. _onButtonClick: function (){
  23869. if (!this.isDisabled()) {
  23870. this.fireEvent('buttonclick');
  23871. }
  23872. }
  23873. };
  23874. utils.inherits(SplitButton, UIBase);
  23875. utils.extend(SplitButton.prototype, Stateful, true);
  23876. })();
  23877. // ui/colorbutton.js
  23878. ///import core
  23879. ///import uicore
  23880. ///import ui/colorpicker.js
  23881. ///import ui/popup.js
  23882. ///import ui/splitbutton.js
  23883. (function (){
  23884. var utils = baidu.editor.utils,
  23885. uiUtils = baidu.editor.ui.uiUtils,
  23886. ColorPicker = baidu.editor.ui.ColorPicker,
  23887. Popup = baidu.editor.ui.Popup,
  23888. SplitButton = baidu.editor.ui.SplitButton,
  23889. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23890. this.initOptions(options);
  23891. this.initColorButton();
  23892. };
  23893. ColorButton.prototype = {
  23894. initColorButton: function (){
  23895. var me = this;
  23896. this.popup = new Popup({
  23897. content: new ColorPicker({
  23898. noColorText: me.editor.getLang("clearColor"),
  23899. editor:me.editor,
  23900. onpickcolor: function (t, color){
  23901. me._onPickColor(color);
  23902. },
  23903. onpicknocolor: function (t, color){
  23904. me._onPickNoColor(color);
  23905. }
  23906. }),
  23907. editor:me.editor
  23908. });
  23909. this.initSplitButton();
  23910. },
  23911. _SplitButton_postRender: SplitButton.prototype.postRender,
  23912. postRender: function (){
  23913. this._SplitButton_postRender();
  23914. this.getDom('button_body').appendChild(
  23915. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23916. );
  23917. this.getDom().className += ' edui-colorbutton';
  23918. },
  23919. setColor: function (color){
  23920. this.getDom('colorlump').style.backgroundColor = color;
  23921. this.color = color;
  23922. },
  23923. _onPickColor: function (color){
  23924. if (this.fireEvent('pickcolor', color) !== false) {
  23925. this.setColor(color);
  23926. this.popup.hide();
  23927. }
  23928. },
  23929. _onPickNoColor: function (color){
  23930. if (this.fireEvent('picknocolor') !== false) {
  23931. this.popup.hide();
  23932. }
  23933. }
  23934. };
  23935. utils.inherits(ColorButton, SplitButton);
  23936. })();
  23937. // ui/tablebutton.js
  23938. ///import core
  23939. ///import uicore
  23940. ///import ui/popup.js
  23941. ///import ui/tablepicker.js
  23942. ///import ui/splitbutton.js
  23943. (function (){
  23944. var utils = baidu.editor.utils,
  23945. Popup = baidu.editor.ui.Popup,
  23946. TablePicker = baidu.editor.ui.TablePicker,
  23947. SplitButton = baidu.editor.ui.SplitButton,
  23948. TableButton = baidu.editor.ui.TableButton = function (options){
  23949. this.initOptions(options);
  23950. this.initTableButton();
  23951. };
  23952. TableButton.prototype = {
  23953. initTableButton: function (){
  23954. var me = this;
  23955. this.popup = new Popup({
  23956. content: new TablePicker({
  23957. editor:me.editor,
  23958. onpicktable: function (t, numCols, numRows){
  23959. me._onPickTable(numCols, numRows);
  23960. }
  23961. }),
  23962. 'editor':me.editor
  23963. });
  23964. this.initSplitButton();
  23965. },
  23966. _onPickTable: function (numCols, numRows){
  23967. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23968. this.popup.hide();
  23969. }
  23970. }
  23971. };
  23972. utils.inherits(TableButton, SplitButton);
  23973. })();
  23974. // ui/autotypesetpicker.js
  23975. ///import core
  23976. ///import uicore
  23977. (function () {
  23978. var utils = baidu.editor.utils,
  23979. UIBase = baidu.editor.ui.UIBase;
  23980. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23981. this.initOptions(options);
  23982. this.initAutoTypeSetPicker();
  23983. };
  23984. AutoTypeSetPicker.prototype = {
  23985. initAutoTypeSetPicker:function () {
  23986. this.initUIBase();
  23987. },
  23988. getHtmlTpl:function () {
  23989. var me = this.editor,
  23990. opt = me.options.autotypeset,
  23991. lang = me.getLang("autoTypeSet");
  23992. var textAlignInputName = 'textAlignValue' + me.uid,
  23993. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23994. symbolConverInputName = 'symbolConverValue' + me.uid;
  23995. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23996. '<div class="edui-autotypesetpicker-body">' +
  23997. '<table >' +
  23998. '<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>' +
  23999. '<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>' +
  24000. '<tr>' +
  24001. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  24002. '<td colspan="2" id="' + textAlignInputName + '">' +
  24003. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24004. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24005. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24006. '</td>' +
  24007. '</tr>' +
  24008. '<tr>' +
  24009. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  24010. '<td nowrap id="'+ imageBlockInputName +'">' +
  24011. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  24012. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24013. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24014. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24015. '</td>' +
  24016. '</tr>' +
  24017. '<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>' +
  24018. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  24019. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  24020. '<tr>' +
  24021. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  24022. '<td id="' + symbolConverInputName + '">' +
  24023. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  24024. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  24025. '</td>' +
  24026. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  24027. '</tr>' +
  24028. '</table>' +
  24029. '</div>' +
  24030. '</div>';
  24031. },
  24032. _UIBase_render:UIBase.prototype.render
  24033. };
  24034. utils.inherits(AutoTypeSetPicker, UIBase);
  24035. })();
  24036. // ui/autotypesetbutton.js
  24037. ///import core
  24038. ///import uicore
  24039. ///import ui/popup.js
  24040. ///import ui/autotypesetpicker.js
  24041. ///import ui/splitbutton.js
  24042. (function (){
  24043. var utils = baidu.editor.utils,
  24044. Popup = baidu.editor.ui.Popup,
  24045. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  24046. SplitButton = baidu.editor.ui.SplitButton,
  24047. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  24048. this.initOptions(options);
  24049. this.initAutoTypeSetButton();
  24050. };
  24051. function getPara(me){
  24052. var opt = {},
  24053. cont = me.getDom(),
  24054. editorId = me.editor.uid,
  24055. inputType = null,
  24056. attrName = null,
  24057. ipts = domUtils.getElementsByTagName(cont,"input");
  24058. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  24059. inputType = ipt.getAttribute("type");
  24060. if(inputType=="checkbox"){
  24061. attrName = ipt.getAttribute("name");
  24062. opt[attrName] && delete opt[attrName];
  24063. if(ipt.checked){
  24064. var attrValue = document.getElementById( attrName + "Value" + editorId );
  24065. if(attrValue){
  24066. if(/input/ig.test(attrValue.tagName)){
  24067. opt[attrName] = attrValue.value;
  24068. } else {
  24069. var iptChilds = attrValue.getElementsByTagName("input");
  24070. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  24071. if(iptchild.checked){
  24072. opt[attrName] = iptchild.value;
  24073. break;
  24074. }
  24075. }
  24076. }
  24077. } else {
  24078. opt[attrName] = true;
  24079. }
  24080. } else {
  24081. opt[attrName] = false;
  24082. }
  24083. } else {
  24084. opt[ipt.getAttribute("value")] = ipt.checked;
  24085. }
  24086. }
  24087. var selects = domUtils.getElementsByTagName(cont,"select");
  24088. for(var i=0,si;si=selects[i++];){
  24089. var attr = si.getAttribute('name');
  24090. opt[attr] = opt[attr] ? si.value : '';
  24091. }
  24092. utils.extend(me.editor.options.autotypeset,opt);
  24093. me.editor.setPreferences('autotypeset', opt);
  24094. }
  24095. AutoTypeSetButton.prototype = {
  24096. initAutoTypeSetButton: function (){
  24097. var me = this;
  24098. this.popup = new Popup({
  24099. //传入配置参数
  24100. content: new AutoTypeSetPicker({editor:me.editor}),
  24101. 'editor':me.editor,
  24102. hide : function(){
  24103. if (!this._hidden && this.getDom()) {
  24104. getPara(this);
  24105. this.getDom().style.display = 'none';
  24106. this._hidden = true;
  24107. this.fireEvent('hide');
  24108. }
  24109. }
  24110. });
  24111. var flag = 0;
  24112. this.popup.addListener('postRenderAfter',function(){
  24113. var popupUI = this;
  24114. if(flag)return;
  24115. var cont = this.getDom(),
  24116. btn = cont.getElementsByTagName('button')[0];
  24117. btn.onclick = function(){
  24118. getPara(popupUI);
  24119. me.editor.execCommand('autotypeset');
  24120. popupUI.hide()
  24121. };
  24122. domUtils.on(cont, 'click', function(e) {
  24123. var target = e.target || e.srcElement,
  24124. editorId = me.editor.uid;
  24125. if (target && target.tagName == 'INPUT') {
  24126. // 点击图片浮动的checkbox,去除对应的radio
  24127. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24128. var checked = target.checked,
  24129. radioTd = document.getElementById( target.name + 'Value' + editorId),
  24130. radios = radioTd.getElementsByTagName('input'),
  24131. defalutSelect = {
  24132. 'imageBlockLine': 'none',
  24133. 'textAlign': 'left',
  24134. 'symbolConver': 'tobdc'
  24135. };
  24136. for (var i = 0; i < radios.length; i++) {
  24137. if (checked) {
  24138. if (radios[i].value == defalutSelect[target.name]) {
  24139. radios[i].checked = 'checked';
  24140. }
  24141. } else {
  24142. radios[i].checked = false;
  24143. }
  24144. }
  24145. }
  24146. // 点击radio,选中对应的checkbox
  24147. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24148. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24149. checkboxs && (checkboxs[0].checked = true);
  24150. }
  24151. getPara(popupUI);
  24152. }
  24153. });
  24154. flag = 1;
  24155. });
  24156. this.initSplitButton();
  24157. }
  24158. };
  24159. utils.inherits(AutoTypeSetButton, SplitButton);
  24160. })();
  24161. // ui/cellalignpicker.js
  24162. ///import core
  24163. ///import uicore
  24164. (function () {
  24165. var utils = baidu.editor.utils,
  24166. Popup = baidu.editor.ui.Popup,
  24167. Stateful = baidu.editor.ui.Stateful,
  24168. UIBase = baidu.editor.ui.UIBase;
  24169. /**
  24170. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24171. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24172. * @update 2013/4/2 hancong03@baidu.com
  24173. */
  24174. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24175. this.initOptions(options);
  24176. this.initSelected();
  24177. this.initCellAlignPicker();
  24178. };
  24179. CellAlignPicker.prototype = {
  24180. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24181. initSelected: function(){
  24182. var status = {
  24183. valign: {
  24184. top: 0,
  24185. middle: 1,
  24186. bottom: 2
  24187. },
  24188. align: {
  24189. left: 0,
  24190. center: 1,
  24191. right: 2
  24192. },
  24193. count: 3
  24194. },
  24195. result = -1;
  24196. if( this.selected ) {
  24197. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  24198. }
  24199. },
  24200. initCellAlignPicker:function () {
  24201. this.initUIBase();
  24202. this.Stateful_init();
  24203. },
  24204. getHtmlTpl:function () {
  24205. var alignType = [ 'left', 'center', 'right' ],
  24206. COUNT = 9,
  24207. tempClassName = null,
  24208. tempIndex = -1,
  24209. tmpl = [];
  24210. for( var i= 0; i<COUNT; i++ ) {
  24211. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24212. tempIndex = i % 3;
  24213. tempIndex === 0 && tmpl.push('<tr>');
  24214. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  24215. tempIndex === 2 && tmpl.push('</tr>');
  24216. }
  24217. return '<div id="##" class="edui-cellalignpicker %%">' +
  24218. '<div class="edui-cellalignpicker-body">' +
  24219. '<table onclick="$$._onClick(event);">' +
  24220. tmpl.join('') +
  24221. '</table>' +
  24222. '</div>' +
  24223. '</div>';
  24224. },
  24225. getStateDom: function (){
  24226. return this.target;
  24227. },
  24228. _onClick: function (evt){
  24229. var target= evt.target || evt.srcElement;
  24230. if(/icon/.test(target.className)){
  24231. this.items[target.parentNode.getAttribute("index")].onclick();
  24232. Popup.postHide(evt);
  24233. }
  24234. },
  24235. _UIBase_render:UIBase.prototype.render
  24236. };
  24237. utils.inherits(CellAlignPicker, UIBase);
  24238. utils.extend(CellAlignPicker.prototype, Stateful,true);
  24239. })();
  24240. // ui/pastepicker.js
  24241. ///import core
  24242. ///import uicore
  24243. (function () {
  24244. var utils = baidu.editor.utils,
  24245. Stateful = baidu.editor.ui.Stateful,
  24246. uiUtils = baidu.editor.ui.uiUtils,
  24247. UIBase = baidu.editor.ui.UIBase;
  24248. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24249. this.initOptions(options);
  24250. this.initPastePicker();
  24251. };
  24252. PastePicker.prototype = {
  24253. initPastePicker:function () {
  24254. this.initUIBase();
  24255. this.Stateful_init();
  24256. },
  24257. getHtmlTpl:function () {
  24258. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24259. '<div class="edui-pastecontainer">' +
  24260. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24261. '<div class="edui-button">' +
  24262. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24263. '<div class="edui-richtxticon"></div></div>' +
  24264. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24265. '<div class="edui-tagicon"></div></div>' +
  24266. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24267. '<div class="edui-plaintxticon"></div></div>' +
  24268. '</div>' +
  24269. '</div>' +
  24270. '</div>'
  24271. },
  24272. getStateDom:function () {
  24273. return this.target;
  24274. },
  24275. format:function (param) {
  24276. this.editor.ui._isTransfer = true;
  24277. this.editor.fireEvent('pasteTransfer', param);
  24278. },
  24279. _onClick:function (cur) {
  24280. var node = domUtils.getNextDomNode(cur),
  24281. screenHt = uiUtils.getViewportRect().height,
  24282. subPop = uiUtils.getClientRect(node);
  24283. if ((subPop.top + subPop.height) > screenHt)
  24284. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24285. else
  24286. node.style.top = "";
  24287. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24288. node.style.visibility = "visible";
  24289. domUtils.addClass(cur, "edui-state-opened");
  24290. } else {
  24291. node.style.visibility = "hidden";
  24292. domUtils.removeClasses(cur, "edui-state-opened")
  24293. }
  24294. },
  24295. _UIBase_render:UIBase.prototype.render
  24296. };
  24297. utils.inherits(PastePicker, UIBase);
  24298. utils.extend(PastePicker.prototype, Stateful, true);
  24299. })();
  24300. // ui/toolbar.js
  24301. (function (){
  24302. var utils = baidu.editor.utils,
  24303. uiUtils = baidu.editor.ui.uiUtils,
  24304. UIBase = baidu.editor.ui.UIBase,
  24305. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24306. this.initOptions(options);
  24307. this.initToolbar();
  24308. };
  24309. Toolbar.prototype = {
  24310. items: null,
  24311. initToolbar: function (){
  24312. this.items = this.items || [];
  24313. this.initUIBase();
  24314. },
  24315. add: function (item,index){
  24316. if(index === undefined){
  24317. this.items.push(item);
  24318. }else{
  24319. this.items.splice(index,0,item)
  24320. }
  24321. },
  24322. getHtmlTpl: function (){
  24323. var buff = [];
  24324. for (var i=0; i<this.items.length; i++) {
  24325. buff[i] = this.items[i].renderHtml();
  24326. }
  24327. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24328. buff.join('') +
  24329. '</div>'
  24330. },
  24331. postRender: function (){
  24332. var box = this.getDom();
  24333. for (var i=0; i<this.items.length; i++) {
  24334. this.items[i].postRender();
  24335. }
  24336. uiUtils.makeUnselectable(box);
  24337. },
  24338. _onMouseDown: function (e){
  24339. var target = e.target || e.srcElement,
  24340. tagName = target && target.tagName && target.tagName.toLowerCase();
  24341. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24342. return false;
  24343. }
  24344. }
  24345. };
  24346. utils.inherits(Toolbar, UIBase);
  24347. })();
  24348. // ui/menu.js
  24349. ///import core
  24350. ///import uicore
  24351. ///import ui\popup.js
  24352. ///import ui\stateful.js
  24353. (function () {
  24354. var utils = baidu.editor.utils,
  24355. domUtils = baidu.editor.dom.domUtils,
  24356. uiUtils = baidu.editor.ui.uiUtils,
  24357. UIBase = baidu.editor.ui.UIBase,
  24358. Popup = baidu.editor.ui.Popup,
  24359. Stateful = baidu.editor.ui.Stateful,
  24360. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24361. Menu = baidu.editor.ui.Menu = function (options) {
  24362. this.initOptions(options);
  24363. this.initMenu();
  24364. };
  24365. var menuSeparator = {
  24366. renderHtml:function () {
  24367. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24368. },
  24369. postRender:function () {
  24370. },
  24371. queryAutoHide:function () {
  24372. return true;
  24373. }
  24374. };
  24375. Menu.prototype = {
  24376. items:null,
  24377. uiName:'menu',
  24378. initMenu:function () {
  24379. this.items = this.items || [];
  24380. this.initPopup();
  24381. this.initItems();
  24382. },
  24383. initItems:function () {
  24384. for (var i = 0; i < this.items.length; i++) {
  24385. var item = this.items[i];
  24386. if (item == '-') {
  24387. this.items[i] = this.getSeparator();
  24388. } else if (!(item instanceof MenuItem)) {
  24389. item.editor = this.editor;
  24390. item.theme = this.editor.options.theme;
  24391. this.items[i] = this.createItem(item);
  24392. }
  24393. }
  24394. },
  24395. getSeparator:function () {
  24396. return menuSeparator;
  24397. },
  24398. createItem:function (item) {
  24399. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24400. item.menu = this;
  24401. return new MenuItem(item);
  24402. },
  24403. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24404. getContentHtmlTpl:function () {
  24405. if (this.items.length == 0) {
  24406. return this._Popup_getContentHtmlTpl();
  24407. }
  24408. var buff = [];
  24409. for (var i = 0; i < this.items.length; i++) {
  24410. var item = this.items[i];
  24411. buff[i] = item.renderHtml();
  24412. }
  24413. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24414. },
  24415. _Popup_postRender:Popup.prototype.postRender,
  24416. postRender:function () {
  24417. var me = this;
  24418. for (var i = 0; i < this.items.length; i++) {
  24419. var item = this.items[i];
  24420. item.ownerMenu = this;
  24421. item.postRender();
  24422. }
  24423. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24424. evt = evt || event;
  24425. var rel = evt.relatedTarget || evt.fromElement;
  24426. var el = me.getDom();
  24427. if (!uiUtils.contains(el, rel) && el !== rel) {
  24428. me.fireEvent('over');
  24429. }
  24430. });
  24431. this._Popup_postRender();
  24432. },
  24433. queryAutoHide:function (el) {
  24434. if (el) {
  24435. if (uiUtils.contains(this.getDom(), el)) {
  24436. return false;
  24437. }
  24438. for (var i = 0; i < this.items.length; i++) {
  24439. var item = this.items[i];
  24440. if (item.queryAutoHide(el) === false) {
  24441. return false;
  24442. }
  24443. }
  24444. }
  24445. },
  24446. clearItems:function () {
  24447. for (var i = 0; i < this.items.length; i++) {
  24448. var item = this.items[i];
  24449. clearTimeout(item._showingTimer);
  24450. clearTimeout(item._closingTimer);
  24451. if (item.subMenu) {
  24452. item.subMenu.destroy();
  24453. }
  24454. }
  24455. this.items = [];
  24456. },
  24457. destroy:function () {
  24458. if (this.getDom()) {
  24459. domUtils.remove(this.getDom());
  24460. }
  24461. this.clearItems();
  24462. },
  24463. dispose:function () {
  24464. this.destroy();
  24465. }
  24466. };
  24467. utils.inherits(Menu, Popup);
  24468. /**
  24469. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24470. * @type {Function}
  24471. */
  24472. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24473. this.initOptions(options);
  24474. this.initUIBase();
  24475. this.Stateful_init();
  24476. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24477. if (options.className && options.className.indexOf("aligntd") != -1) {
  24478. var me = this;
  24479. //获取单元格对齐初始状态
  24480. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24481. this.subMenu = new Popup({
  24482. content:new CellAlignPicker(this.subMenu),
  24483. parentMenu:me,
  24484. editor:me.editor,
  24485. destroy:function () {
  24486. if (this.getDom()) {
  24487. domUtils.remove(this.getDom());
  24488. }
  24489. }
  24490. });
  24491. this.subMenu.addListener("postRenderAfter", function () {
  24492. domUtils.on(this.getDom(), "mouseover", function () {
  24493. me.addState('opened');
  24494. });
  24495. });
  24496. } else {
  24497. this.subMenu = new Menu(this.subMenu);
  24498. }
  24499. }
  24500. };
  24501. MenuItem.prototype = {
  24502. label:'',
  24503. subMenu:null,
  24504. ownerMenu:null,
  24505. uiName:'menuitem',
  24506. alwalysHoverable:true,
  24507. getHtmlTpl:function () {
  24508. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24509. '<div class="%%-body">' +
  24510. this.renderLabelHtml() +
  24511. '</div>' +
  24512. '</div>';
  24513. },
  24514. postRender:function () {
  24515. var me = this;
  24516. this.addListener('over', function () {
  24517. me.ownerMenu.fireEvent('submenuover', me);
  24518. if (me.subMenu) {
  24519. me.delayShowSubMenu();
  24520. }
  24521. });
  24522. if (this.subMenu) {
  24523. this.getDom().className += ' edui-hassubmenu';
  24524. this.subMenu.render();
  24525. this.addListener('out', function () {
  24526. me.delayHideSubMenu();
  24527. });
  24528. this.subMenu.addListener('over', function () {
  24529. clearTimeout(me._closingTimer);
  24530. me._closingTimer = null;
  24531. me.addState('opened');
  24532. });
  24533. this.ownerMenu.addListener('hide', function () {
  24534. me.hideSubMenu();
  24535. });
  24536. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24537. if (subMenu !== me) {
  24538. me.delayHideSubMenu();
  24539. }
  24540. });
  24541. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24542. this.subMenu.queryAutoHide = function (el) {
  24543. if (el && uiUtils.contains(me.getDom(), el)) {
  24544. return false;
  24545. }
  24546. return this._bakQueryAutoHide(el);
  24547. };
  24548. }
  24549. this.getDom().style.tabIndex = '-1';
  24550. uiUtils.makeUnselectable(this.getDom());
  24551. this.Stateful_postRender();
  24552. },
  24553. delayShowSubMenu:function () {
  24554. var me = this;
  24555. if (!me.isDisabled()) {
  24556. me.addState('opened');
  24557. clearTimeout(me._showingTimer);
  24558. clearTimeout(me._closingTimer);
  24559. me._closingTimer = null;
  24560. me._showingTimer = setTimeout(function () {
  24561. me.showSubMenu();
  24562. }, 250);
  24563. }
  24564. },
  24565. delayHideSubMenu:function () {
  24566. var me = this;
  24567. if (!me.isDisabled()) {
  24568. me.removeState('opened');
  24569. clearTimeout(me._showingTimer);
  24570. if (!me._closingTimer) {
  24571. me._closingTimer = setTimeout(function () {
  24572. if (!me.hasState('opened')) {
  24573. me.hideSubMenu();
  24574. }
  24575. me._closingTimer = null;
  24576. }, 400);
  24577. }
  24578. }
  24579. },
  24580. renderLabelHtml:function () {
  24581. return '<div class="edui-arrow"></div>' +
  24582. '<div class="edui-box edui-icon"></div>' +
  24583. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24584. },
  24585. getStateDom:function () {
  24586. return this.getDom();
  24587. },
  24588. queryAutoHide:function (el) {
  24589. if (this.subMenu && this.hasState('opened')) {
  24590. return this.subMenu.queryAutoHide(el);
  24591. }
  24592. },
  24593. _onClick:function (event, this_) {
  24594. if (this.hasState('disabled')) return;
  24595. if (this.fireEvent('click', event, this_) !== false) {
  24596. if (this.subMenu) {
  24597. this.showSubMenu();
  24598. } else {
  24599. Popup.postHide(event);
  24600. }
  24601. }
  24602. },
  24603. showSubMenu:function () {
  24604. var rect = uiUtils.getClientRect(this.getDom());
  24605. rect.right -= 5;
  24606. rect.left += 2;
  24607. rect.width -= 7;
  24608. rect.top -= 4;
  24609. rect.bottom += 4;
  24610. rect.height += 8;
  24611. this.subMenu.showAnchorRect(rect, true, true);
  24612. },
  24613. hideSubMenu:function () {
  24614. this.subMenu.hide();
  24615. }
  24616. };
  24617. utils.inherits(MenuItem, UIBase);
  24618. utils.extend(MenuItem.prototype, Stateful, true);
  24619. })();
  24620. // ui/combox.js
  24621. ///import core
  24622. ///import uicore
  24623. ///import ui/menu.js
  24624. ///import ui/splitbutton.js
  24625. (function (){
  24626. // todo: menu和item提成通用list
  24627. var utils = baidu.editor.utils,
  24628. uiUtils = baidu.editor.ui.uiUtils,
  24629. Menu = baidu.editor.ui.Menu,
  24630. SplitButton = baidu.editor.ui.SplitButton,
  24631. Combox = baidu.editor.ui.Combox = function (options){
  24632. this.initOptions(options);
  24633. this.initCombox();
  24634. };
  24635. Combox.prototype = {
  24636. uiName: 'combox',
  24637. onbuttonclick:function () {
  24638. this.showPopup();
  24639. },
  24640. initCombox: function (){
  24641. var me = this;
  24642. this.items = this.items || [];
  24643. for (var i=0; i<this.items.length; i++) {
  24644. var item = this.items[i];
  24645. item.uiName = 'listitem';
  24646. item.index = i;
  24647. item.onclick = function (){
  24648. me.selectByIndex(this.index);
  24649. };
  24650. }
  24651. this.popup = new Menu({
  24652. items: this.items,
  24653. uiName: 'list',
  24654. editor:this.editor,
  24655. captureWheel: true,
  24656. combox: this
  24657. });
  24658. this.initSplitButton();
  24659. },
  24660. _SplitButton_postRender: SplitButton.prototype.postRender,
  24661. postRender: function (){
  24662. this._SplitButton_postRender();
  24663. this.setLabel(this.label || '');
  24664. this.setValue(this.initValue || '');
  24665. },
  24666. showPopup: function (){
  24667. var rect = uiUtils.getClientRect(this.getDom());
  24668. rect.top += 1;
  24669. rect.bottom -= 1;
  24670. rect.height -= 2;
  24671. this.popup.showAnchorRect(rect);
  24672. },
  24673. getValue: function (){
  24674. return this.value;
  24675. },
  24676. setValue: function (value){
  24677. var index = this.indexByValue(value);
  24678. if (index != -1) {
  24679. this.selectedIndex = index;
  24680. this.setLabel(this.items[index].label);
  24681. this.value = this.items[index].value;
  24682. } else {
  24683. this.selectedIndex = -1;
  24684. this.setLabel(this.getLabelForUnknowValue(value));
  24685. this.value = value;
  24686. }
  24687. },
  24688. setLabel: function (label){
  24689. this.getDom('button_body').innerHTML = label;
  24690. this.label = label;
  24691. },
  24692. getLabelForUnknowValue: function (value){
  24693. return value;
  24694. },
  24695. indexByValue: function (value){
  24696. for (var i=0; i<this.items.length; i++) {
  24697. if (value == this.items[i].value) {
  24698. return i;
  24699. }
  24700. }
  24701. return -1;
  24702. },
  24703. getItem: function (index){
  24704. return this.items[index];
  24705. },
  24706. selectByIndex: function (index){
  24707. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24708. this.selectedIndex = index;
  24709. this.value = this.items[index].value;
  24710. this.setLabel(this.items[index].label);
  24711. }
  24712. }
  24713. };
  24714. utils.inherits(Combox, SplitButton);
  24715. })();
  24716. // ui/dialog.js
  24717. ///import core
  24718. ///import uicore
  24719. ///import ui/mask.js
  24720. ///import ui/button.js
  24721. (function (){
  24722. var utils = baidu.editor.utils,
  24723. domUtils = baidu.editor.dom.domUtils,
  24724. uiUtils = baidu.editor.ui.uiUtils,
  24725. Mask = baidu.editor.ui.Mask,
  24726. UIBase = baidu.editor.ui.UIBase,
  24727. Button = baidu.editor.ui.Button,
  24728. Dialog = baidu.editor.ui.Dialog = function (options){
  24729. if(options.name){
  24730. var name = options.name;
  24731. var cssRules = options.cssRules;
  24732. if(!options.className){
  24733. options.className = 'edui-for-' + name;
  24734. }
  24735. if(cssRules){
  24736. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24737. }
  24738. }
  24739. this.initOptions(utils.extend({
  24740. autoReset: true,
  24741. draggable: true,
  24742. onok: function (){},
  24743. oncancel: function (){},
  24744. onclose: function (t, ok){
  24745. return ok ? this.onok() : this.oncancel();
  24746. },
  24747. //是否控制dialog中的scroll事件, 默认为不阻止
  24748. holdScroll: false
  24749. },options));
  24750. this.initDialog();
  24751. };
  24752. var modalMask;
  24753. var dragMask;
  24754. var activeDialog;
  24755. Dialog.prototype = {
  24756. draggable: false,
  24757. uiName: 'dialog',
  24758. initDialog: function (){
  24759. var me = this,
  24760. theme=this.editor.options.theme;
  24761. if(this.cssRules){
  24762. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24763. }
  24764. this.initUIBase();
  24765. this.modalMask = (modalMask || (modalMask = new Mask({
  24766. className: 'edui-dialog-modalmask',
  24767. theme:theme,
  24768. onclick: function (){
  24769. activeDialog && activeDialog.close(false);
  24770. }
  24771. })));
  24772. this.dragMask = (dragMask || (dragMask = new Mask({
  24773. className: 'edui-dialog-dragmask',
  24774. theme:theme
  24775. })));
  24776. this.closeButton = new Button({
  24777. className: 'edui-dialog-closebutton',
  24778. title: me.closeDialog,
  24779. theme:theme,
  24780. onclick: function (){
  24781. me.close(false);
  24782. }
  24783. });
  24784. this.fullscreen && this.initResizeEvent();
  24785. if (this.buttons) {
  24786. for (var i=0; i<this.buttons.length; i++) {
  24787. if (!(this.buttons[i] instanceof Button)) {
  24788. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24789. editor : this.editor
  24790. },true));
  24791. }
  24792. }
  24793. }
  24794. },
  24795. initResizeEvent: function () {
  24796. var me = this;
  24797. domUtils.on( window, "resize", function () {
  24798. if ( me._hidden || me._hidden === undefined ) {
  24799. return;
  24800. }
  24801. if ( me.__resizeTimer ) {
  24802. window.clearTimeout( me.__resizeTimer );
  24803. }
  24804. me.__resizeTimer = window.setTimeout( function () {
  24805. me.__resizeTimer = null;
  24806. var dialogWrapNode = me.getDom(),
  24807. contentNode = me.getDom('content'),
  24808. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24809. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24810. vpRect = uiUtils.getViewportRect();
  24811. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24812. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24813. dialogWrapNode.style.width = vpRect.width + "px";
  24814. dialogWrapNode.style.height = vpRect.height + "px";
  24815. me.fireEvent( "resize" );
  24816. }, 100 );
  24817. } );
  24818. },
  24819. fitSize: function (){
  24820. var popBodyEl = this.getDom('body');
  24821. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24822. // uiUtils.removeStyle(popBodyEl, 'width');
  24823. // uiUtils.removeStyle(popBodyEl, 'height');
  24824. // }
  24825. var size = this.mesureSize();
  24826. popBodyEl.style.width = size.width + 'px';
  24827. popBodyEl.style.height = size.height + 'px';
  24828. return size;
  24829. },
  24830. safeSetOffset: function (offset){
  24831. var me = this;
  24832. var el = me.getDom();
  24833. var vpRect = uiUtils.getViewportRect();
  24834. var rect = uiUtils.getClientRect(el);
  24835. var left = offset.left;
  24836. if (left + rect.width > vpRect.right) {
  24837. left = vpRect.right - rect.width;
  24838. }
  24839. var top = offset.top;
  24840. if (top + rect.height > vpRect.bottom) {
  24841. top = vpRect.bottom - rect.height;
  24842. }
  24843. el.style.left = Math.max(left, 0) + 'px';
  24844. el.style.top = Math.max(top, 0) + 'px';
  24845. },
  24846. showAtCenter: function (){
  24847. var vpRect = uiUtils.getViewportRect();
  24848. if ( !this.fullscreen ) {
  24849. this.getDom().style.display = '';
  24850. var popSize = this.fitSize();
  24851. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24852. var left = vpRect.width / 2 - popSize.width / 2;
  24853. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24854. var popEl = this.getDom();
  24855. this.safeSetOffset({
  24856. left: Math.max(left | 0, 0),
  24857. top: Math.max(top | 0, 0)
  24858. });
  24859. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24860. popEl.className += ' edui-state-centered';
  24861. }
  24862. } else {
  24863. var dialogWrapNode = this.getDom(),
  24864. contentNode = this.getDom('content');
  24865. dialogWrapNode.style.display = "block";
  24866. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24867. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24868. dialogWrapNode.style.left = "-100000px";
  24869. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24870. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24871. dialogWrapNode.style.width = vpRect.width + "px";
  24872. dialogWrapNode.style.height = vpRect.height + "px";
  24873. dialogWrapNode.style.left = 0;
  24874. //保存环境的overflow值
  24875. this._originalContext = {
  24876. html: {
  24877. overflowX: document.documentElement.style.overflowX,
  24878. overflowY: document.documentElement.style.overflowY
  24879. },
  24880. body: {
  24881. overflowX: document.body.style.overflowX,
  24882. overflowY: document.body.style.overflowY
  24883. }
  24884. };
  24885. document.documentElement.style.overflowX = 'hidden';
  24886. document.documentElement.style.overflowY = 'hidden';
  24887. document.body.style.overflowX = 'hidden';
  24888. document.body.style.overflowY = 'hidden';
  24889. }
  24890. this._show();
  24891. },
  24892. getContentHtml: function (){
  24893. var contentHtml = '';
  24894. if (typeof this.content == 'string') {
  24895. contentHtml = this.content;
  24896. } else if (this.iframeUrl) {
  24897. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24898. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24899. }
  24900. return contentHtml;
  24901. },
  24902. getHtmlTpl: function (){
  24903. var footHtml = '';
  24904. if (this.buttons) {
  24905. var buff = [];
  24906. for (var i=0; i<this.buttons.length; i++) {
  24907. buff[i] = this.buttons[i].renderHtml();
  24908. }
  24909. footHtml = '<div class="%%-foot">' +
  24910. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24911. '</div>';
  24912. }
  24913. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24914. '<div class="%%-shadow"></div>' +
  24915. '<div id="##_titlebar" class="%%-titlebar">' +
  24916. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24917. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24918. '</div>' +
  24919. this.closeButton.renderHtml() +
  24920. '</div>' +
  24921. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24922. footHtml +
  24923. '</div></div></div>';
  24924. },
  24925. postRender: function (){
  24926. // todo: 保持居中/记住上次关闭位置选项
  24927. if (!this.modalMask.getDom()) {
  24928. this.modalMask.render();
  24929. this.modalMask.hide();
  24930. }
  24931. if (!this.dragMask.getDom()) {
  24932. this.dragMask.render();
  24933. this.dragMask.hide();
  24934. }
  24935. var me = this;
  24936. this.addListener('show', function (){
  24937. me.modalMask.show(this.getDom().style.zIndex - 2);
  24938. });
  24939. this.addListener('hide', function (){
  24940. me.modalMask.hide();
  24941. });
  24942. if (this.buttons) {
  24943. for (var i=0; i<this.buttons.length; i++) {
  24944. this.buttons[i].postRender();
  24945. }
  24946. }
  24947. domUtils.on(window, 'resize', function (){
  24948. setTimeout(function (){
  24949. if (!me.isHidden()) {
  24950. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24951. }
  24952. });
  24953. });
  24954. //hold住scroll事件,防止dialog的滚动影响页面
  24955. // if( this.holdScroll ) {
  24956. //
  24957. // if( !me.iframeUrl ) {
  24958. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24959. // domUtils.preventDefault(e);
  24960. // } );
  24961. // } else {
  24962. // me.addListener('dialogafterreset', function(){
  24963. // window.setTimeout(function(){
  24964. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24965. //
  24966. // if( browser.ie ) {
  24967. //
  24968. // var timer = window.setInterval(function(){
  24969. //
  24970. // if( iframeWindow.document && iframeWindow.document.body ) {
  24971. // window.clearInterval( timer );
  24972. // timer = null;
  24973. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24974. // domUtils.preventDefault(e);
  24975. // } );
  24976. // }
  24977. //
  24978. // }, 100);
  24979. //
  24980. // } else {
  24981. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24982. // domUtils.preventDefault(e);
  24983. // } );
  24984. // }
  24985. //
  24986. // }, 1);
  24987. // });
  24988. // }
  24989. //
  24990. // }
  24991. this._hide();
  24992. },
  24993. mesureSize: function (){
  24994. var body = this.getDom('body');
  24995. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24996. var dialogBodyStyle = body.style;
  24997. dialogBodyStyle.width = width;
  24998. return uiUtils.getClientRect(body);
  24999. },
  25000. _onTitlebarMouseDown: function (evt, el){
  25001. if (this.draggable) {
  25002. var rect;
  25003. var vpRect = uiUtils.getViewportRect();
  25004. var me = this;
  25005. uiUtils.startDrag(evt, {
  25006. ondragstart: function (){
  25007. rect = uiUtils.getClientRect(me.getDom());
  25008. me.getDom('contmask').style.visibility = 'visible';
  25009. me.dragMask.show(me.getDom().style.zIndex - 1);
  25010. },
  25011. ondragmove: function (x, y){
  25012. var left = rect.left + x;
  25013. var top = rect.top + y;
  25014. me.safeSetOffset({
  25015. left: left,
  25016. top: top
  25017. });
  25018. },
  25019. ondragstop: function (){
  25020. me.getDom('contmask').style.visibility = 'hidden';
  25021. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  25022. me.dragMask.hide();
  25023. }
  25024. });
  25025. }
  25026. },
  25027. reset: function (){
  25028. this.getDom('content').innerHTML = this.getContentHtml();
  25029. this.fireEvent('dialogafterreset');
  25030. },
  25031. _show: function (){
  25032. if (this._hidden) {
  25033. this.getDom().style.display = '';
  25034. //要高过编辑器的zindxe
  25035. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  25036. this._hidden = false;
  25037. this.fireEvent('show');
  25038. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  25039. }
  25040. },
  25041. isHidden: function (){
  25042. return this._hidden;
  25043. },
  25044. _hide: function (){
  25045. if (!this._hidden) {
  25046. var wrapNode = this.getDom();
  25047. wrapNode.style.display = 'none';
  25048. wrapNode.style.zIndex = '';
  25049. wrapNode.style.width = '';
  25050. wrapNode.style.height = '';
  25051. this._hidden = true;
  25052. this.fireEvent('hide');
  25053. }
  25054. },
  25055. open: function (){
  25056. if (this.autoReset) {
  25057. //有可能还没有渲染
  25058. try{
  25059. this.reset();
  25060. }catch(e){
  25061. this.render();
  25062. this.open()
  25063. }
  25064. }
  25065. this.showAtCenter();
  25066. if (this.iframeUrl) {
  25067. try {
  25068. this.getDom('iframe').focus();
  25069. } catch(ex){}
  25070. }
  25071. activeDialog = this;
  25072. },
  25073. _onCloseButtonClick: function (evt, el){
  25074. this.close(false);
  25075. },
  25076. close: function (ok){
  25077. if (this.fireEvent('close', ok) !== false) {
  25078. //还原环境
  25079. if ( this.fullscreen ) {
  25080. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  25081. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  25082. document.body.style.overflowX = this._originalContext.body.overflowX;
  25083. document.body.style.overflowY = this._originalContext.body.overflowY;
  25084. delete this._originalContext;
  25085. }
  25086. this._hide();
  25087. //销毁content
  25088. var content = this.getDom('content');
  25089. var iframe = this.getDom('iframe');
  25090. if (content && iframe) {
  25091. var doc = iframe.contentDocument || iframe.contentWindow.document;
  25092. doc && (doc.body.innerHTML = '');
  25093. domUtils.remove(content);
  25094. }
  25095. }
  25096. }
  25097. };
  25098. utils.inherits(Dialog, UIBase);
  25099. })();
  25100. // ui/menubutton.js
  25101. ///import core
  25102. ///import uicore
  25103. ///import ui/menu.js
  25104. ///import ui/splitbutton.js
  25105. (function (){
  25106. var utils = baidu.editor.utils,
  25107. Menu = baidu.editor.ui.Menu,
  25108. SplitButton = baidu.editor.ui.SplitButton,
  25109. MenuButton = baidu.editor.ui.MenuButton = function (options){
  25110. this.initOptions(options);
  25111. this.initMenuButton();
  25112. };
  25113. MenuButton.prototype = {
  25114. initMenuButton: function (){
  25115. var me = this;
  25116. this.uiName = "menubutton";
  25117. this.popup = new Menu({
  25118. items: me.items,
  25119. className: me.className,
  25120. editor:me.editor
  25121. });
  25122. this.popup.addListener('show', function (){
  25123. var list = this;
  25124. for (var i=0; i<list.items.length; i++) {
  25125. list.items[i].removeState('checked');
  25126. if (list.items[i].value == me._value) {
  25127. list.items[i].addState('checked');
  25128. this.value = me._value;
  25129. }
  25130. }
  25131. });
  25132. this.initSplitButton();
  25133. },
  25134. setValue : function(value){
  25135. this._value = value;
  25136. }
  25137. };
  25138. utils.inherits(MenuButton, SplitButton);
  25139. })();
  25140. // ui/multiMenu.js
  25141. ///import core
  25142. ///import uicore
  25143. ///commands 表情
  25144. (function(){
  25145. var utils = baidu.editor.utils,
  25146. Popup = baidu.editor.ui.Popup,
  25147. SplitButton = baidu.editor.ui.SplitButton,
  25148. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25149. this.initOptions(options);
  25150. this.initMultiMenu();
  25151. };
  25152. MultiMenuPop.prototype = {
  25153. initMultiMenu: function (){
  25154. var me = this;
  25155. this.popup = new Popup({
  25156. content: '',
  25157. editor : me.editor,
  25158. iframe_rendered: false,
  25159. onshow: function (){
  25160. if (!this.iframe_rendered) {
  25161. this.iframe_rendered = true;
  25162. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25163. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25164. }
  25165. }
  25166. // canSideUp:false,
  25167. // canSideLeft:false
  25168. });
  25169. this.onbuttonclick = function(){
  25170. this.showPopup();
  25171. };
  25172. this.initSplitButton();
  25173. }
  25174. };
  25175. utils.inherits(MultiMenuPop, SplitButton);
  25176. })();
  25177. // ui/shortcutmenu.js
  25178. (function () {
  25179. var UI = baidu.editor.ui,
  25180. UIBase = UI.UIBase,
  25181. uiUtils = UI.uiUtils,
  25182. utils = baidu.editor.utils,
  25183. domUtils = baidu.editor.dom.domUtils;
  25184. var allMenus = [],//存储所有快捷菜单
  25185. timeID,
  25186. isSubMenuShow = false;//是否有子pop显示
  25187. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25188. this.initOptions (options);
  25189. this.initShortCutMenu ();
  25190. };
  25191. ShortCutMenu.postHide = hideAllMenu;
  25192. ShortCutMenu.prototype = {
  25193. isHidden : true ,
  25194. SPACE : 5 ,
  25195. initShortCutMenu : function () {
  25196. this.items = this.items || [];
  25197. this.initUIBase ();
  25198. this.initItems ();
  25199. this.initEvent ();
  25200. allMenus.push (this);
  25201. } ,
  25202. initEvent : function () {
  25203. var me = this,
  25204. doc = me.editor.document;
  25205. domUtils.on (doc , "mousemove" , function (e) {
  25206. if (me.isHidden === false) {
  25207. //有pop显示就不隐藏快捷菜单
  25208. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25209. var flag = true,
  25210. el = me.getDom (),
  25211. wt = el.offsetWidth,
  25212. ht = el.offsetHeight,
  25213. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25214. distanceY = ht / 2,//距离中心Y标准
  25215. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25216. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25217. clearTimeout (timeID);
  25218. timeID = setTimeout (function () {
  25219. if (y > 0 && y < distanceY) {
  25220. me.setOpacity (el , "1");
  25221. } else if (y > distanceY && y < distanceY + 70) {
  25222. me.setOpacity (el , "0.5");
  25223. flag = false;
  25224. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25225. me.hide ();
  25226. }
  25227. if (flag && x > 0 && x < distanceX) {
  25228. me.setOpacity (el , "1")
  25229. } else if (x > distanceX && x < distanceX + 70) {
  25230. me.setOpacity (el , "0.5")
  25231. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25232. me.hide ();
  25233. }
  25234. });
  25235. }
  25236. });
  25237. //ie\ff下 mouseout不准
  25238. if (browser.chrome) {
  25239. domUtils.on (doc , "mouseout" , function (e) {
  25240. var relatedTgt = e.relatedTarget || e.toElement;
  25241. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25242. me.hide ();
  25243. }
  25244. });
  25245. }
  25246. me.editor.addListener ("afterhidepop" , function () {
  25247. if (!me.isHidden) {
  25248. isSubMenuShow = true;
  25249. }
  25250. });
  25251. } ,
  25252. initItems : function () {
  25253. if (utils.isArray (this.items)) {
  25254. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25255. var item = this.items[i].toLowerCase ();
  25256. if (UI[item]) {
  25257. this.items[i] = new UI[item] (this.editor);
  25258. this.items[i].className += " edui-shortcutsubmenu ";
  25259. }
  25260. }
  25261. }
  25262. } ,
  25263. setOpacity : function (el , value) {
  25264. if (browser.ie && browser.version < 9) {
  25265. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25266. } else {
  25267. el.style.opacity = value;
  25268. }
  25269. } ,
  25270. getSubMenuMark : function () {
  25271. isSubMenuShow = false;
  25272. var layerEle = uiUtils.getFixedLayer ();
  25273. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25274. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25275. });
  25276. for (var i = 0, node ; node = list[i++] ;) {
  25277. if (node.style.display != "none") {
  25278. isSubMenuShow = true;
  25279. }
  25280. }
  25281. return isSubMenuShow;
  25282. } ,
  25283. show : function (e , hasContextmenu) {
  25284. var me = this,
  25285. offset = {},
  25286. el = this.getDom (),
  25287. fixedlayer = uiUtils.getFixedLayer ();
  25288. function setPos (offset) {
  25289. if (offset.left < 0) {
  25290. offset.left = 0;
  25291. }
  25292. if (offset.top < 0) {
  25293. offset.top = 0;
  25294. }
  25295. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25296. }
  25297. function setPosByCxtMenu (menu) {
  25298. if (!menu.tagName) {
  25299. menu = menu.getDom ();
  25300. }
  25301. offset.left = parseInt (menu.style.left);
  25302. offset.top = parseInt (menu.style.top);
  25303. offset.top -= el.offsetHeight + 15;
  25304. setPos (offset);
  25305. }
  25306. me.eventType = e.type;
  25307. el.style.cssText = "display:block;left:-9999px";
  25308. if (e.type == "contextmenu" && hasContextmenu) {
  25309. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25310. if (menu) {
  25311. setPosByCxtMenu (menu)
  25312. } else {
  25313. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25314. setPosByCxtMenu (menu);
  25315. });
  25316. }
  25317. } else {
  25318. offset = uiUtils.getViewportOffsetByEvent (e);
  25319. offset.top -= el.offsetHeight + me.SPACE;
  25320. offset.left += me.SPACE + 20;
  25321. setPos (offset);
  25322. me.setOpacity (el , 0.2);
  25323. }
  25324. me.isHidden = false;
  25325. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25326. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25327. if (me.editor) {
  25328. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25329. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25330. }
  25331. } ,
  25332. hide : function () {
  25333. if (this.getDom ()) {
  25334. this.getDom ().style.display = "none";
  25335. }
  25336. this.isHidden = true;
  25337. } ,
  25338. postRender : function () {
  25339. if (utils.isArray (this.items)) {
  25340. for (var i = 0, item ; item = this.items[i++] ;) {
  25341. item.postRender ();
  25342. }
  25343. }
  25344. } ,
  25345. getHtmlTpl : function () {
  25346. var buff;
  25347. if (utils.isArray (this.items)) {
  25348. buff = [];
  25349. for (var i = 0 ; i < this.items.length ; i++) {
  25350. buff[i] = this.items[i].renderHtml ();
  25351. }
  25352. buff = buff.join ("");
  25353. } else {
  25354. buff = this.items;
  25355. }
  25356. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25357. buff +
  25358. '</div>';
  25359. }
  25360. };
  25361. utils.inherits (ShortCutMenu , UIBase);
  25362. function hideAllMenu (e) {
  25363. var tgt = e.target || e.srcElement,
  25364. cur = domUtils.findParent (tgt , function (node) {
  25365. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25366. } , true);
  25367. if (!cur) {
  25368. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25369. menu.hide ()
  25370. }
  25371. }
  25372. }
  25373. domUtils.on (document , 'mousedown' , function (e) {
  25374. hideAllMenu (e);
  25375. });
  25376. domUtils.on (window , 'scroll' , function (e) {
  25377. hideAllMenu (e);
  25378. });
  25379. }) ();
  25380. // ui/breakline.js
  25381. (function (){
  25382. var utils = baidu.editor.utils,
  25383. UIBase = baidu.editor.ui.UIBase,
  25384. Breakline = baidu.editor.ui.Breakline = function (options){
  25385. this.initOptions(options);
  25386. this.initSeparator();
  25387. };
  25388. Breakline.prototype = {
  25389. uiName: 'Breakline',
  25390. initSeparator: function (){
  25391. this.initUIBase();
  25392. },
  25393. getHtmlTpl: function (){
  25394. return '<br/>';
  25395. }
  25396. };
  25397. utils.inherits(Breakline, UIBase);
  25398. })();
  25399. // ui/message.js
  25400. ///import core
  25401. ///import uicore
  25402. (function () {
  25403. var utils = baidu.editor.utils,
  25404. domUtils = baidu.editor.dom.domUtils,
  25405. UIBase = baidu.editor.ui.UIBase,
  25406. Message = baidu.editor.ui.Message = function (options){
  25407. this.initOptions(options);
  25408. this.initMessage();
  25409. };
  25410. Message.prototype = {
  25411. initMessage: function (){
  25412. this.initUIBase();
  25413. },
  25414. getHtmlTpl: function (){
  25415. return '<div id="##" class="edui-message %%">' +
  25416. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25417. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25418. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25419. ' <div class="edui-shadow"></div>' +
  25420. ' <div id="##_content" class="edui-message-content">' +
  25421. ' </div>' +
  25422. ' </div>' +
  25423. '</div>';
  25424. },
  25425. reset: function(opt){
  25426. var me = this;
  25427. if (!opt.keepshow) {
  25428. clearTimeout(this.timer);
  25429. me.timer = setTimeout(function(){
  25430. me.hide();
  25431. }, opt.timeout || 4000);
  25432. }
  25433. opt.content !== undefined && me.setContent(opt.content);
  25434. opt.type !== undefined && me.setType(opt.type);
  25435. me.show();
  25436. },
  25437. postRender: function(){
  25438. var me = this,
  25439. closer = this.getDom('closer');
  25440. closer && domUtils.on(closer, 'click', function(){
  25441. me.hide();
  25442. });
  25443. },
  25444. setContent: function(content){
  25445. this.getDom('content').innerHTML = content;
  25446. },
  25447. setType: function(type){
  25448. type = type || 'info';
  25449. var body = this.getDom('body');
  25450. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25451. },
  25452. getContent: function(){
  25453. return this.getDom('content').innerHTML;
  25454. },
  25455. getType: function(){
  25456. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25457. return arr ? arr[1]:'';
  25458. },
  25459. show: function (){
  25460. this.getDom().style.display = 'block';
  25461. },
  25462. hide: function (){
  25463. var dom = this.getDom();
  25464. if (dom) {
  25465. dom.style.display = 'none';
  25466. dom.parentNode && dom.parentNode.removeChild(dom);
  25467. }
  25468. }
  25469. };
  25470. utils.inherits(Message, UIBase);
  25471. })();
  25472. // adapter/editorui.js
  25473. //ui跟编辑器的适配層
  25474. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25475. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25476. (function () {
  25477. var utils = baidu.editor.utils;
  25478. var editorui = baidu.editor.ui;
  25479. var _Dialog = editorui.Dialog;
  25480. editorui.buttons = {};
  25481. editorui.Dialog = function (options) {
  25482. var dialog = new _Dialog(options);
  25483. dialog.addListener('hide', function () {
  25484. if (dialog.editor) {
  25485. var editor = dialog.editor;
  25486. try {
  25487. if (browser.gecko) {
  25488. var y = editor.window.scrollY,
  25489. x = editor.window.scrollX;
  25490. editor.body.focus();
  25491. editor.window.scrollTo(x, y);
  25492. } else {
  25493. editor.focus();
  25494. }
  25495. } catch (ex) {
  25496. }
  25497. }
  25498. });
  25499. return dialog;
  25500. };
  25501. var iframeUrlMap = {
  25502. 'anchor':'~/dialogs/anchor/anchor.html',
  25503. 'insertimage':'~/dialogs/image/image.html',
  25504. 'link':'~/dialogs/link/link.html',
  25505. 'spechars':'~/dialogs/spechars/spechars.html',
  25506. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25507. 'map':'~/dialogs/map/map.html',
  25508. 'gmap':'~/dialogs/gmap/gmap.html',
  25509. 'insertvideo':'~/dialogs/video/video.html',
  25510. 'help':'~/dialogs/help/help.html',
  25511. 'preview':'~/dialogs/preview/preview.html',
  25512. 'emotion':'~/dialogs/emotion/emotion.html',
  25513. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25514. 'attachment':'~/dialogs/attachment/attachment.html',
  25515. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25516. 'edittip':'~/dialogs/table/edittip.html',
  25517. 'edittable':'~/dialogs/table/edittable.html',
  25518. 'edittd':'~/dialogs/table/edittd.html',
  25519. 'webapp':'~/dialogs/webapp/webapp.html',
  25520. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25521. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25522. 'music':'~/dialogs/music/music.html',
  25523. 'template':'~/dialogs/template/template.html',
  25524. 'background':'~/dialogs/background/background.html',
  25525. 'charts': '~/dialogs/charts/charts.html'
  25526. };
  25527. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25528. var btnCmds = ['undo', 'redo', 'formatmatch',
  25529. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25530. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25531. 'blockquote', 'pasteplain', 'pagebreak',
  25532. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25533. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25534. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts','importword','titlepicbtn'];
  25535. for (var i = 0, ci; ci = btnCmds[i++];) {
  25536. ci = ci.toLowerCase();
  25537. editorui[ci] = function (cmd) {
  25538. return function (editor) {
  25539. var ui = new editorui.Button({
  25540. className:'edui-for-' + cmd,
  25541. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25542. onclick:function () {
  25543. editor.execCommand(cmd);
  25544. },
  25545. theme:editor.options.theme,
  25546. showText:false
  25547. });
  25548. editorui.buttons[cmd] = ui;
  25549. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25550. var state = editor.queryCommandState(cmd);
  25551. if (state == -1) {
  25552. ui.setDisabled(true);
  25553. ui.setChecked(false);
  25554. } else {
  25555. if (!uiReady) {
  25556. ui.setDisabled(false);
  25557. ui.setChecked(state);
  25558. }
  25559. }
  25560. });
  25561. return ui;
  25562. };
  25563. }(ci);
  25564. }
  25565. //清除文档
  25566. editorui.cleardoc = function (editor) {
  25567. var ui = new editorui.Button({
  25568. className:'edui-for-cleardoc',
  25569. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25570. theme:editor.options.theme,
  25571. onclick:function () {
  25572. if (confirm(editor.getLang("confirmClear"))) {
  25573. editor.execCommand('cleardoc');
  25574. }
  25575. }
  25576. });
  25577. editorui.buttons["cleardoc"] = ui;
  25578. editor.addListener('selectionchange', function () {
  25579. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25580. });
  25581. return ui;
  25582. };
  25583. //排版,图片排版,文字方向
  25584. var typeset = {
  25585. 'justify':['left', 'right', 'center', 'justify'],
  25586. 'imagefloat':['none', 'left', 'center', 'right'],
  25587. 'directionality':['ltr', 'rtl']
  25588. };
  25589. for (var p in typeset) {
  25590. (function (cmd, val) {
  25591. for (var i = 0, ci; ci = val[i++];) {
  25592. (function (cmd2) {
  25593. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25594. var ui = new editorui.Button({
  25595. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25596. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25597. theme:editor.options.theme,
  25598. onclick:function () {
  25599. editor.execCommand(cmd, cmd2);
  25600. }
  25601. });
  25602. editorui.buttons[cmd] = ui;
  25603. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25604. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25605. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25606. });
  25607. return ui;
  25608. };
  25609. })(ci)
  25610. }
  25611. })(p, typeset[p])
  25612. }
  25613. //字体颜色和背景颜色
  25614. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25615. editorui[ci] = function (cmd) {
  25616. return function (editor) {
  25617. var ui = new editorui.ColorButton({
  25618. className:'edui-for-' + cmd,
  25619. color:'default',
  25620. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25621. editor:editor,
  25622. onpickcolor:function (t, color) {
  25623. editor.execCommand(cmd, color);
  25624. },
  25625. onpicknocolor:function () {
  25626. editor.execCommand(cmd, 'default');
  25627. this.setColor('transparent');
  25628. this.color = 'default';
  25629. },
  25630. onbuttonclick:function () {
  25631. editor.execCommand(cmd, this.color);
  25632. }
  25633. });
  25634. editorui.buttons[cmd] = ui;
  25635. editor.addListener('selectionchange', function () {
  25636. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25637. });
  25638. return ui;
  25639. };
  25640. }(ci);
  25641. }
  25642. var dialogBtns = {
  25643. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25644. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25645. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25646. };
  25647. for (var p in dialogBtns) {
  25648. (function (type, vals) {
  25649. for (var i = 0, ci; ci = vals[i++];) {
  25650. //todo opera下存在问题
  25651. if (browser.opera && ci === "searchreplace") {
  25652. continue;
  25653. }
  25654. (function (cmd) {
  25655. editorui[cmd] = function (editor, iframeUrl, title) {
  25656. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25657. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25658. var dialog;
  25659. //没有iframeUrl不创建dialog
  25660. if (iframeUrl) {
  25661. dialog = new editorui.Dialog(utils.extend({
  25662. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25663. editor:editor,
  25664. className:'edui-for-' + cmd,
  25665. title:title,
  25666. holdScroll: cmd === 'insertimage',
  25667. fullscreen: /charts|preview/.test(cmd),
  25668. closeDialog:editor.getLang("closeDialog")
  25669. }, type == 'ok' ? {
  25670. buttons:[
  25671. {
  25672. className:'edui-okbutton',
  25673. label:editor.getLang("ok"),
  25674. editor:editor,
  25675. onclick:function () {
  25676. dialog.close(true);
  25677. }
  25678. },
  25679. {
  25680. className:'edui-cancelbutton',
  25681. label:editor.getLang("cancel"),
  25682. editor:editor,
  25683. onclick:function () {
  25684. dialog.close(false);
  25685. }
  25686. }
  25687. ]
  25688. } : {}));
  25689. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25690. }
  25691. var ui = new editorui.Button({
  25692. className:'edui-for-' + cmd,
  25693. title:title,
  25694. onclick:function () {
  25695. if (dialog) {
  25696. switch (cmd) {
  25697. case "wordimage":
  25698. var images = editor.execCommand("wordimage");
  25699. if (images && images.length) {
  25700. dialog.render();
  25701. dialog.open();
  25702. }
  25703. break;
  25704. case "scrawl":
  25705. if (editor.queryCommandState("scrawl") != -1) {
  25706. dialog.render();
  25707. dialog.open();
  25708. }
  25709. break;
  25710. default:
  25711. dialog.render();
  25712. dialog.open();
  25713. }
  25714. }
  25715. },
  25716. theme:editor.options.theme,
  25717. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25718. });
  25719. editorui.buttons[cmd] = ui;
  25720. editor.addListener('selectionchange', function () {
  25721. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25722. var unNeedCheckState = {'edittable':1};
  25723. if (cmd in unNeedCheckState)return;
  25724. var state = editor.queryCommandState(cmd);
  25725. if (ui.getDom()) {
  25726. ui.setDisabled(state == -1);
  25727. ui.setChecked(state);
  25728. }
  25729. });
  25730. return ui;
  25731. };
  25732. })(ci.toLowerCase())
  25733. }
  25734. })(p, dialogBtns[p]);
  25735. }
  25736. editorui.snapscreen = function (editor, iframeUrl, title) {
  25737. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25738. var ui = new editorui.Button({
  25739. className:'edui-for-snapscreen',
  25740. title:title,
  25741. onclick:function () {
  25742. editor.execCommand("snapscreen");
  25743. },
  25744. theme:editor.options.theme
  25745. });
  25746. editorui.buttons['snapscreen'] = ui;
  25747. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25748. if (iframeUrl) {
  25749. var dialog = new editorui.Dialog({
  25750. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25751. editor:editor,
  25752. className:'edui-for-snapscreen',
  25753. title:title,
  25754. buttons:[
  25755. {
  25756. className:'edui-okbutton',
  25757. label:editor.getLang("ok"),
  25758. editor:editor,
  25759. onclick:function () {
  25760. dialog.close(true);
  25761. }
  25762. },
  25763. {
  25764. className:'edui-cancelbutton',
  25765. label:editor.getLang("cancel"),
  25766. editor:editor,
  25767. onclick:function () {
  25768. dialog.close(false);
  25769. }
  25770. }
  25771. ]
  25772. });
  25773. dialog.render();
  25774. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25775. }
  25776. editor.addListener('selectionchange', function () {
  25777. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25778. });
  25779. return ui;
  25780. };
  25781. editorui.insertcode = function (editor, list, title) {
  25782. list = editor.options['insertcode'] || [];
  25783. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25784. // if (!list.length) return;
  25785. var items = [];
  25786. utils.each(list,function(key,val){
  25787. items.push({
  25788. label:key,
  25789. value:val,
  25790. theme:editor.options.theme,
  25791. renderLabelHtml:function () {
  25792. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25793. }
  25794. });
  25795. });
  25796. var ui = new editorui.Combox({
  25797. editor:editor,
  25798. items:items,
  25799. onselect:function (t, index) {
  25800. editor.execCommand('insertcode', this.items[index].value);
  25801. },
  25802. onbuttonclick:function () {
  25803. this.showPopup();
  25804. },
  25805. title:title,
  25806. initValue:title,
  25807. className:'edui-for-insertcode',
  25808. indexByValue:function (value) {
  25809. if (value) {
  25810. for (var i = 0, ci; ci = this.items[i]; i++) {
  25811. if (ci.value.indexOf(value) != -1)
  25812. return i;
  25813. }
  25814. }
  25815. return -1;
  25816. }
  25817. });
  25818. editorui.buttons['insertcode'] = ui;
  25819. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25820. if (!uiReady) {
  25821. var state = editor.queryCommandState('insertcode');
  25822. if (state == -1) {
  25823. ui.setDisabled(true);
  25824. } else {
  25825. ui.setDisabled(false);
  25826. var value = editor.queryCommandValue('insertcode');
  25827. if(!value){
  25828. ui.setValue(title);
  25829. return;
  25830. }
  25831. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25832. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25833. ui.setValue(value);
  25834. }
  25835. }
  25836. });
  25837. return ui;
  25838. };
  25839. editorui.fontfamily = function (editor, list, title) {
  25840. list = editor.options['fontfamily'] || [];
  25841. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25842. if (!list.length) return;
  25843. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25844. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25845. (function (key, val) {
  25846. items.push({
  25847. label:key,
  25848. value:val,
  25849. theme:editor.options.theme,
  25850. renderLabelHtml:function () {
  25851. return '<div class="edui-label %%-label" style="font-family:' +
  25852. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25853. }
  25854. });
  25855. })(ci.label || langLabel, ci.val)
  25856. }
  25857. var ui = new editorui.Combox({
  25858. editor:editor,
  25859. items:items,
  25860. onselect:function (t, index) {
  25861. editor.execCommand('FontFamily', this.items[index].value);
  25862. },
  25863. onbuttonclick:function () {
  25864. this.showPopup();
  25865. },
  25866. title:title,
  25867. initValue:title,
  25868. className:'edui-for-fontfamily',
  25869. indexByValue:function (value) {
  25870. if (value) {
  25871. for (var i = 0, ci; ci = this.items[i]; i++) {
  25872. if (ci.value.indexOf(value) != -1)
  25873. return i;
  25874. }
  25875. }
  25876. return -1;
  25877. }
  25878. });
  25879. editorui.buttons['fontfamily'] = ui;
  25880. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25881. if (!uiReady) {
  25882. var state = editor.queryCommandState('FontFamily');
  25883. if (state == -1) {
  25884. ui.setDisabled(true);
  25885. } else {
  25886. ui.setDisabled(false);
  25887. var value = editor.queryCommandValue('FontFamily');
  25888. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25889. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25890. ui.setValue(value);
  25891. }
  25892. }
  25893. });
  25894. return ui;
  25895. };
  25896. editorui.fontsize = function (editor, list, title) {
  25897. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25898. list = list || editor.options['fontsize'] || [];
  25899. if (!list.length) return;
  25900. var items = [];
  25901. for (var i = 0; i < list.length; i++) {
  25902. //var size = list[i] + 'px';
  25903. var item = list[i].split(':');
  25904. var sizeDesc = item[0];
  25905. var size = item[1]+ 'px';
  25906. items.push({
  25907. label:sizeDesc,
  25908. value:size,
  25909. theme:editor.options.theme,
  25910. renderLabelHtml:function () {
  25911. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25912. this.value + '">' + (this.label || '') + '</div>';
  25913. }
  25914. });
  25915. }
  25916. var ui = new editorui.Combox({
  25917. editor:editor,
  25918. items:items,
  25919. title:title,
  25920. initValue:title,
  25921. onselect:function (t, index) {
  25922. editor.execCommand('FontSize', this.items[index].value);
  25923. },
  25924. onbuttonclick:function () {
  25925. this.showPopup();
  25926. },
  25927. className:'edui-for-fontsize'
  25928. });
  25929. editorui.buttons['fontsize'] = ui;
  25930. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25931. if (!uiReady) {
  25932. var state = editor.queryCommandState('FontSize');
  25933. if (state == -1) {
  25934. ui.setDisabled(true);
  25935. } else {
  25936. ui.setDisabled(false);
  25937. ui.setValue(editor.queryCommandValue('FontSize'));
  25938. }
  25939. }
  25940. });
  25941. return ui;
  25942. };
  25943. editorui.paragraph = function (editor, list, title) {
  25944. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25945. list = editor.options['paragraph'] || [];
  25946. if (utils.isEmptyObject(list)) return;
  25947. var items = [];
  25948. for (var i in list) {
  25949. items.push({
  25950. value:i,
  25951. label:list[i] || editor.getLang("paragraph")[i],
  25952. theme:editor.options.theme,
  25953. renderLabelHtml:function () {
  25954. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25955. }
  25956. })
  25957. }
  25958. var ui = new editorui.Combox({
  25959. editor:editor,
  25960. items:items,
  25961. title:title,
  25962. initValue:title,
  25963. className:'edui-for-paragraph',
  25964. onselect:function (t, index) {
  25965. editor.execCommand('Paragraph', this.items[index].value);
  25966. },
  25967. onbuttonclick:function () {
  25968. this.showPopup();
  25969. }
  25970. });
  25971. editorui.buttons['paragraph'] = ui;
  25972. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25973. if (!uiReady) {
  25974. var state = editor.queryCommandState('Paragraph');
  25975. if (state == -1) {
  25976. ui.setDisabled(true);
  25977. } else {
  25978. ui.setDisabled(false);
  25979. var value = editor.queryCommandValue('Paragraph');
  25980. var index = ui.indexByValue(value);
  25981. if (index != -1) {
  25982. ui.setValue(value);
  25983. } else {
  25984. ui.setValue(ui.initValue);
  25985. }
  25986. }
  25987. }
  25988. });
  25989. return ui;
  25990. };
  25991. //自定义标题
  25992. editorui.customstyle = function (editor) {
  25993. var list = editor.options['customstyle'] || [],
  25994. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25995. if (!list.length)return;
  25996. var langCs = editor.getLang('customstyle');
  25997. for (var i = 0, items = [], t; t = list[i++];) {
  25998. (function (t) {
  25999. var ck = {};
  26000. ck.label = t.label ? t.label : langCs[t.name];
  26001. ck.style = t.style;
  26002. ck.className = t.className;
  26003. ck.tag = t.tag;
  26004. items.push({
  26005. label:ck.label,
  26006. value:ck,
  26007. theme:editor.options.theme,
  26008. renderLabelHtml:function () {
  26009. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  26010. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  26011. + '</div>';
  26012. }
  26013. });
  26014. })(t);
  26015. }
  26016. var ui = new editorui.Combox({
  26017. editor:editor,
  26018. items:items,
  26019. title:title,
  26020. initValue:title,
  26021. className:'edui-for-customstyle',
  26022. onselect:function (t, index) {
  26023. editor.execCommand('customstyle', this.items[index].value);
  26024. },
  26025. onbuttonclick:function () {
  26026. this.showPopup();
  26027. },
  26028. indexByValue:function (value) {
  26029. for (var i = 0, ti; ti = this.items[i++];) {
  26030. if (ti.label == value) {
  26031. return i - 1
  26032. }
  26033. }
  26034. return -1;
  26035. }
  26036. });
  26037. editorui.buttons['customstyle'] = ui;
  26038. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26039. if (!uiReady) {
  26040. var state = editor.queryCommandState('customstyle');
  26041. if (state == -1) {
  26042. ui.setDisabled(true);
  26043. } else {
  26044. ui.setDisabled(false);
  26045. var value = editor.queryCommandValue('customstyle');
  26046. var index = ui.indexByValue(value);
  26047. if (index != -1) {
  26048. ui.setValue(value);
  26049. } else {
  26050. ui.setValue(ui.initValue);
  26051. }
  26052. }
  26053. }
  26054. });
  26055. return ui;
  26056. };
  26057. editorui.inserttable = function (editor, iframeUrl, title) {
  26058. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  26059. var ui = new editorui.TableButton({
  26060. editor:editor,
  26061. title:title,
  26062. className:'edui-for-inserttable',
  26063. onpicktable:function (t, numCols, numRows) {
  26064. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  26065. },
  26066. onbuttonclick:function () {
  26067. this.showPopup();
  26068. }
  26069. });
  26070. editorui.buttons['inserttable'] = ui;
  26071. editor.addListener('selectionchange', function () {
  26072. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  26073. });
  26074. return ui;
  26075. };
  26076. editorui.lineheight = function (editor) {
  26077. var val = editor.options.lineheight || [];
  26078. if (!val.length)return;
  26079. for (var i = 0, ci, items = []; ci = val[i++];) {
  26080. items.push({
  26081. //todo:写死了
  26082. label:ci,
  26083. value:ci,
  26084. theme:editor.options.theme,
  26085. onclick:function () {
  26086. editor.execCommand("lineheight", this.value);
  26087. }
  26088. })
  26089. }
  26090. var ui = new editorui.MenuButton({
  26091. editor:editor,
  26092. className:'edui-for-lineheight',
  26093. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  26094. items:items,
  26095. onbuttonclick:function () {
  26096. var value = editor.queryCommandValue('LineHeight') || this.value;
  26097. editor.execCommand("LineHeight", value);
  26098. }
  26099. });
  26100. editorui.buttons['lineheight'] = ui;
  26101. editor.addListener('selectionchange', function () {
  26102. var state = editor.queryCommandState('LineHeight');
  26103. if (state == -1) {
  26104. ui.setDisabled(true);
  26105. } else {
  26106. ui.setDisabled(false);
  26107. var value = editor.queryCommandValue('LineHeight');
  26108. value && ui.setValue((value + '').replace(/cm/, ''));
  26109. ui.setChecked(state)
  26110. }
  26111. });
  26112. return ui;
  26113. };
  26114. var rowspacings = ['top', 'bottom'];
  26115. for (var r = 0, ri; ri = rowspacings[r++];) {
  26116. (function (cmd) {
  26117. editorui['rowspacing' + cmd] = function (editor) {
  26118. var val = editor.options['rowspacing' + cmd] || [];
  26119. if (!val.length) return null;
  26120. for (var i = 0, ci, items = []; ci = val[i++];) {
  26121. items.push({
  26122. label:ci,
  26123. value:ci,
  26124. theme:editor.options.theme,
  26125. onclick:function () {
  26126. editor.execCommand("rowspacing", this.value, cmd);
  26127. }
  26128. })
  26129. }
  26130. var ui = new editorui.MenuButton({
  26131. editor:editor,
  26132. className:'edui-for-rowspacing' + cmd,
  26133. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26134. items:items,
  26135. onbuttonclick:function () {
  26136. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26137. editor.execCommand("rowspacing", value, cmd);
  26138. }
  26139. });
  26140. editorui.buttons[cmd] = ui;
  26141. editor.addListener('selectionchange', function () {
  26142. var state = editor.queryCommandState('rowspacing', cmd);
  26143. if (state == -1) {
  26144. ui.setDisabled(true);
  26145. } else {
  26146. ui.setDisabled(false);
  26147. var value = editor.queryCommandValue('rowspacing', cmd);
  26148. value && ui.setValue((value + '').replace(/%/, ''));
  26149. ui.setChecked(state)
  26150. }
  26151. });
  26152. return ui;
  26153. }
  26154. })(ri)
  26155. }
  26156. //有序,无序列表
  26157. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26158. for (var l = 0, cl; cl = lists[l++];) {
  26159. (function (cmd) {
  26160. editorui[cmd] = function (editor) {
  26161. var vals = editor.options[cmd],
  26162. _onMenuClick = function () {
  26163. editor.execCommand(cmd, this.value);
  26164. }, items = [];
  26165. for (var i in vals) {
  26166. items.push({
  26167. label:vals[i] || editor.getLang()[cmd][i] || "",
  26168. value:i,
  26169. theme:editor.options.theme,
  26170. onclick:_onMenuClick
  26171. })
  26172. }
  26173. var ui = new editorui.MenuButton({
  26174. editor:editor,
  26175. className:'edui-for-' + cmd,
  26176. title:editor.getLang("labelMap." + cmd) || '',
  26177. 'items':items,
  26178. onbuttonclick:function () {
  26179. var value = editor.queryCommandValue(cmd) || this.value;
  26180. editor.execCommand(cmd, value);
  26181. }
  26182. });
  26183. editorui.buttons[cmd] = ui;
  26184. editor.addListener('selectionchange', function () {
  26185. var state = editor.queryCommandState(cmd);
  26186. if (state == -1) {
  26187. ui.setDisabled(true);
  26188. } else {
  26189. ui.setDisabled(false);
  26190. var value = editor.queryCommandValue(cmd);
  26191. ui.setValue(value);
  26192. ui.setChecked(state)
  26193. }
  26194. });
  26195. return ui;
  26196. };
  26197. })(cl)
  26198. }
  26199. editorui.fullscreen = function (editor, title) {
  26200. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26201. var ui = new editorui.Button({
  26202. className:'edui-for-fullscreen',
  26203. title:title,
  26204. theme:editor.options.theme,
  26205. onclick:function () {
  26206. if (editor.ui) {
  26207. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26208. }
  26209. this.setChecked(editor.ui.isFullScreen());
  26210. }
  26211. });
  26212. editorui.buttons['fullscreen'] = ui;
  26213. editor.addListener('selectionchange', function () {
  26214. var state = editor.queryCommandState('fullscreen');
  26215. ui.setDisabled(state == -1);
  26216. ui.setChecked(editor.ui.isFullScreen());
  26217. });
  26218. return ui;
  26219. };
  26220. // 表情
  26221. editorui["emotion"] = function (editor, iframeUrl) {
  26222. var cmd = "emotion";
  26223. var ui = new editorui.MultiMenuPop({
  26224. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26225. editor:editor,
  26226. className:'edui-for-' + cmd,
  26227. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26228. });
  26229. editorui.buttons[cmd] = ui;
  26230. editor.addListener('selectionchange', function () {
  26231. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26232. });
  26233. return ui;
  26234. };
  26235. editorui.autotypeset = function (editor) {
  26236. var ui = new editorui.AutoTypeSetButton({
  26237. editor:editor,
  26238. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26239. className:'edui-for-autotypeset',
  26240. onbuttonclick:function () {
  26241. editor.execCommand('autotypeset')
  26242. }
  26243. });
  26244. editorui.buttons['autotypeset'] = ui;
  26245. editor.addListener('selectionchange', function () {
  26246. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26247. });
  26248. return ui;
  26249. };
  26250. /* 简单上传插件 */
  26251. editorui["simpleupload"] = function (editor) {
  26252. var name = 'simpleupload',
  26253. ui = new editorui.Button({
  26254. className:'edui-for-' + name,
  26255. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26256. onclick:function () {},
  26257. theme:editor.options.theme,
  26258. showText:false
  26259. });
  26260. editorui.buttons[name] = ui;
  26261. editor.addListener('ready', function() {
  26262. var b = ui.getDom('body'),
  26263. iconSpan = b.children[0];
  26264. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26265. });
  26266. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26267. var state = editor.queryCommandState(name);
  26268. if (state == -1) {
  26269. ui.setDisabled(true);
  26270. ui.setChecked(false);
  26271. } else {
  26272. if (!uiReady) {
  26273. ui.setDisabled(false);
  26274. ui.setChecked(state);
  26275. }
  26276. }
  26277. });
  26278. return ui;
  26279. };
  26280. editorui["importword"] = function (editor) {
  26281. var name = 'importword',
  26282. ui = new editorui.Button({
  26283. className:'edui-for-' + name,
  26284. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26285. onclick:function () {},
  26286. theme:editor.options.theme,
  26287. showText:false
  26288. });
  26289. editorui.buttons[name] = ui;
  26290. editor.addListener('ready', function() {
  26291. var b = ui.getDom('body'),
  26292. iconSpan = b.children[0];
  26293. editor.fireEvent('importwordbtnready', iconSpan);
  26294. });
  26295. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26296. var state = editor.queryCommandState(name);
  26297. if (state == -1) {
  26298. ui.setDisabled(true);
  26299. ui.setChecked(false);
  26300. } else {
  26301. if (!uiReady) {
  26302. ui.setDisabled(false);
  26303. ui.setChecked(state);
  26304. }
  26305. }
  26306. });
  26307. return ui;
  26308. };
  26309. })();
  26310. // adapter/editor.js
  26311. ///import core
  26312. ///commands 全屏
  26313. ///commandsName FullScreen
  26314. ///commandsTitle 全屏
  26315. (function () {
  26316. var utils = baidu.editor.utils,
  26317. uiUtils = baidu.editor.ui.uiUtils,
  26318. UIBase = baidu.editor.ui.UIBase,
  26319. domUtils = baidu.editor.dom.domUtils;
  26320. var nodeStack = [];
  26321. function EditorUI(options) {
  26322. this.initOptions(options);
  26323. this.initEditorUI();
  26324. }
  26325. EditorUI.prototype = {
  26326. uiName:'editor',
  26327. initEditorUI:function () {
  26328. this.editor.ui = this;
  26329. this._dialogs = {};
  26330. this.initUIBase();
  26331. this._initToolbars();
  26332. var editor = this.editor,
  26333. me = this;
  26334. editor.addListener('ready', function () {
  26335. //提供getDialog方法
  26336. editor.getDialog = function (name) {
  26337. return editor.ui._dialogs[name + "Dialog"];
  26338. };
  26339. domUtils.on(editor.window, 'scroll', function (evt) {
  26340. baidu.editor.ui.Popup.postHide(evt);
  26341. });
  26342. //提供编辑器实时宽高(全屏时宽高不变化)
  26343. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26344. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26345. //display bottom-bar label based on config
  26346. if (editor.options.elementPathEnabled) {
  26347. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26348. }
  26349. if (editor.options.wordCount) {
  26350. function countFn() {
  26351. setCount(editor,me);
  26352. domUtils.un(editor.document, "click", arguments.callee);
  26353. }
  26354. domUtils.on(editor.document, "click", countFn);
  26355. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26356. }
  26357. editor.ui._scale();
  26358. if (editor.options.scaleEnabled) {
  26359. if (editor.autoHeightEnabled) {
  26360. editor.disableAutoHeight();
  26361. }
  26362. me.enableScale();
  26363. } else {
  26364. me.disableScale();
  26365. }
  26366. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26367. editor.ui.getDom('elementpath').style.display = "none";
  26368. editor.ui.getDom('wordcount').style.display = "none";
  26369. editor.ui.getDom('scale').style.display = "none";
  26370. }
  26371. if (!editor.selection.isFocus())return;
  26372. editor.fireEvent('selectionchange', false, true);
  26373. });
  26374. editor.addListener('mousedown', function (t, evt) {
  26375. var el = evt.target || evt.srcElement;
  26376. baidu.editor.ui.Popup.postHide(evt, el);
  26377. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26378. });
  26379. editor.addListener("delcells", function () {
  26380. if (UE.ui['edittip']) {
  26381. new UE.ui['edittip'](editor);
  26382. }
  26383. editor.getDialog('edittip').open();
  26384. });
  26385. var pastePop, isPaste = false, timer;
  26386. editor.addListener("afterpaste", function () {
  26387. if(editor.queryCommandState('pasteplain'))
  26388. return;
  26389. if(baidu.editor.ui.PastePicker){
  26390. pastePop = new baidu.editor.ui.Popup({
  26391. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26392. editor:editor,
  26393. className:'edui-wordpastepop'
  26394. });
  26395. pastePop.render();
  26396. }
  26397. isPaste = true;
  26398. });
  26399. editor.addListener("afterinserthtml", function () {
  26400. clearTimeout(timer);
  26401. timer = setTimeout(function () {
  26402. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26403. if(pastePop.isHidden()){
  26404. var span = domUtils.createElement(editor.document, 'span', {
  26405. 'style':"line-height:0px;",
  26406. 'innerHTML':'\ufeff'
  26407. }),
  26408. range = editor.selection.getRange();
  26409. range.insertNode(span);
  26410. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26411. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26412. domUtils.remove(span);
  26413. }else{
  26414. pastePop.show();
  26415. }
  26416. delete editor.ui._isTransfer;
  26417. isPaste = false;
  26418. }
  26419. }, 200)
  26420. });
  26421. editor.addListener('contextmenu', function (t, evt) {
  26422. baidu.editor.ui.Popup.postHide(evt);
  26423. });
  26424. editor.addListener('keydown', function (t, evt) {
  26425. if (pastePop) pastePop.dispose(evt);
  26426. var keyCode = evt.keyCode || evt.which;
  26427. if(evt.altKey&&keyCode==90){
  26428. UE.ui.buttons['fullscreen'].onclick();
  26429. }
  26430. });
  26431. editor.addListener('wordcount', function (type) {
  26432. setCount(this,me);
  26433. });
  26434. function setCount(editor,ui) {
  26435. editor.setOpt({
  26436. wordCount:true,
  26437. maximumWords:10000,
  26438. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26439. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26440. });
  26441. var opt = editor.options,
  26442. max = opt.maximumWords,
  26443. msg = opt.wordCountMsg ,
  26444. errMsg = opt.wordOverFlowMsg,
  26445. countDom = ui.getDom('wordcount');
  26446. if (!opt.wordCount) {
  26447. return;
  26448. }
  26449. var count = editor.getContentLength(true);
  26450. if (count > max) {
  26451. countDom.innerHTML = errMsg;
  26452. editor.fireEvent("wordcountoverflow");
  26453. } else {
  26454. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26455. }
  26456. }
  26457. editor.addListener('selectionchange', function () {
  26458. if (editor.options.elementPathEnabled) {
  26459. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26460. }
  26461. if (editor.options.scaleEnabled) {
  26462. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26463. }
  26464. });
  26465. var popup = new baidu.editor.ui.Popup({
  26466. editor:editor,
  26467. content:'',
  26468. className:'edui-bubble',
  26469. _onEditButtonClick:function () {
  26470. this.hide();
  26471. editor.ui._dialogs.linkDialog.open();
  26472. },
  26473. _onImgEditButtonClick:function (name) {
  26474. this.hide();
  26475. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26476. },
  26477. _onImgSetFloat:function (value) {
  26478. this.hide();
  26479. editor.execCommand("imagefloat", value);
  26480. },
  26481. _setIframeAlign:function (value) {
  26482. var frame = popup.anchorEl;
  26483. var newFrame = frame.cloneNode(true);
  26484. switch (value) {
  26485. case -2:
  26486. newFrame.setAttribute("align", "");
  26487. break;
  26488. case -1:
  26489. newFrame.setAttribute("align", "left");
  26490. break;
  26491. case 1:
  26492. newFrame.setAttribute("align", "right");
  26493. break;
  26494. }
  26495. frame.parentNode.insertBefore(newFrame, frame);
  26496. domUtils.remove(frame);
  26497. popup.anchorEl = newFrame;
  26498. popup.showAnchor(popup.anchorEl);
  26499. },
  26500. _updateIframe:function () {
  26501. var frame = editor._iframe = popup.anchorEl;
  26502. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26503. editor.selection.getRange().selectNode(frame).select();
  26504. editor.ui._dialogs.mapDialog.open();
  26505. popup.hide();
  26506. } else {
  26507. editor.ui._dialogs.insertframeDialog.open();
  26508. popup.hide();
  26509. }
  26510. },
  26511. _onRemoveButtonClick:function (cmdName) {
  26512. editor.execCommand(cmdName);
  26513. this.hide();
  26514. },
  26515. queryAutoHide:function (el) {
  26516. if (el && el.ownerDocument == editor.document) {
  26517. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26518. return el !== popup.anchorEl;
  26519. }
  26520. }
  26521. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26522. }
  26523. });
  26524. popup.render();
  26525. if (editor.options.imagePopup) {
  26526. editor.addListener('mouseover', function (t, evt) {
  26527. evt = evt || window.event;
  26528. var el = evt.target || evt.srcElement;
  26529. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26530. var html = popup.formatHtml(
  26531. '<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;' +
  26532. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26533. if (html) {
  26534. popup.getDom('content').innerHTML = html;
  26535. popup.anchorEl = el;
  26536. popup.showAnchor(popup.anchorEl);
  26537. } else {
  26538. popup.hide();
  26539. }
  26540. }
  26541. });
  26542. editor.addListener('selectionchange', function (t, causeByUi) {
  26543. if (!causeByUi) return;
  26544. var html = '', str = "",
  26545. img = editor.selection.getRange().getClosedNode(),
  26546. dialogs = editor.ui._dialogs;
  26547. if (img && img.tagName == 'IMG') {
  26548. var dialogName = 'insertimageDialog';
  26549. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26550. dialogName = "insertvideoDialog"
  26551. }
  26552. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26553. dialogName = "webappDialog"
  26554. }
  26555. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26556. dialogName = "mapDialog"
  26557. }
  26558. if (img.className.indexOf("edui-faked-music") != -1) {
  26559. dialogName = "musicDialog"
  26560. }
  26561. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26562. dialogName = "gmapDialog"
  26563. }
  26564. if (img.getAttribute("anchorname")) {
  26565. dialogName = "anchorDialog";
  26566. html = popup.formatHtml(
  26567. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26568. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26569. }
  26570. if (img.getAttribute("word_img")) {
  26571. //todo 放到dialog去做查询
  26572. editor.word_img = [img.getAttribute("word_img")];
  26573. dialogName = "wordimageDialog"
  26574. }
  26575. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26576. dialogName = "";
  26577. }
  26578. if (!dialogs[dialogName]) {
  26579. return;
  26580. }
  26581. str = '<nobr>' + editor.getLang("property") + ': '+
  26582. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26583. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26584. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26585. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26586. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26587. !html && (html = popup.formatHtml(str))
  26588. }
  26589. if (editor.ui._dialogs.linkDialog) {
  26590. var link = editor.queryCommandValue('link');
  26591. var url;
  26592. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26593. var txt = url;
  26594. if (url.length > 30) {
  26595. txt = url.substring(0, 20) + "...";
  26596. }
  26597. if (html) {
  26598. html += '<div style="height:5px;"></div>'
  26599. }
  26600. html += popup.formatHtml(
  26601. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26602. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26603. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26604. popup.showAnchor(link);
  26605. }
  26606. }
  26607. if (html) {
  26608. popup.getDom('content').innerHTML = html;
  26609. popup.anchorEl = img || link;
  26610. popup.showAnchor(popup.anchorEl);
  26611. } else {
  26612. popup.hide();
  26613. }
  26614. });
  26615. }
  26616. },
  26617. _initToolbars:function () {
  26618. var editor = this.editor;
  26619. var toolbars = this.toolbars || [];
  26620. var toolbarUis = [];
  26621. for (var i = 0; i < toolbars.length; i++) {
  26622. var toolbar = toolbars[i];
  26623. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26624. for (var j = 0; j < toolbar.length; j++) {
  26625. var toolbarItem = toolbar[j];
  26626. var toolbarItemUi = null;
  26627. if (typeof toolbarItem == 'string') {
  26628. toolbarItem = toolbarItem.toLowerCase();
  26629. if (toolbarItem == '|') {
  26630. toolbarItem = 'Separator';
  26631. }
  26632. if(toolbarItem == '||'){
  26633. toolbarItem = 'Breakline';
  26634. }
  26635. if (baidu.editor.ui[toolbarItem]) {
  26636. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26637. }
  26638. //fullscreen这里单独处理一下,放到首行去
  26639. if (toolbarItem == 'fullscreen') {
  26640. if (toolbarUis && toolbarUis[0]) {
  26641. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26642. } else {
  26643. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26644. }
  26645. continue;
  26646. }
  26647. } else {
  26648. toolbarItemUi = toolbarItem;
  26649. }
  26650. if (toolbarItemUi && toolbarItemUi.id) {
  26651. toolbarUi.add(toolbarItemUi);
  26652. }
  26653. }
  26654. toolbarUis[i] = toolbarUi;
  26655. }
  26656. //接受外部定制的UI
  26657. utils.each(UE._customizeUI,function(obj,key){
  26658. var itemUI,index;
  26659. if(obj.id && obj.id != editor.key){
  26660. return false;
  26661. }
  26662. itemUI = obj.execFn.call(editor,editor,key);
  26663. if(itemUI){
  26664. index = obj.index;
  26665. if(index === undefined){
  26666. index = toolbarUi.items.length;
  26667. }
  26668. toolbarUi.add(itemUI,index)
  26669. }
  26670. });
  26671. this.toolbars = toolbarUis;
  26672. },
  26673. getHtmlTpl:function () {
  26674. return '<div id="##" class="%%">' +
  26675. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26676. (this.toolbars.length ?
  26677. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26678. this.renderToolbarBoxHtml() +
  26679. '</div></div>' : '') +
  26680. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26681. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26682. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26683. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26684. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26685. '</div>' +
  26686. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26687. '</div>' +
  26688. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26689. '</div>' +
  26690. //modify wdcount by matao
  26691. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26692. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26693. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26694. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26695. '</tr></table></div>' +
  26696. '<div id="##_scalelayer"></div>' +
  26697. '</div>';
  26698. },
  26699. showWordImageDialog:function () {
  26700. this._dialogs['wordimageDialog'].open();
  26701. },
  26702. renderToolbarBoxHtml:function () {
  26703. var buff = [];
  26704. for (var i = 0; i < this.toolbars.length; i++) {
  26705. buff.push(this.toolbars[i].renderHtml());
  26706. }
  26707. return buff.join('');
  26708. },
  26709. setFullScreen:function (fullscreen) {
  26710. var editor = this.editor,
  26711. container = editor.container.parentNode.parentNode;
  26712. if (this._fullscreen != fullscreen) {
  26713. this._fullscreen = fullscreen;
  26714. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26715. if (baidu.editor.browser.gecko) {
  26716. var bk = editor.selection.getRange().createBookmark();
  26717. }
  26718. if (fullscreen) {
  26719. while (container.tagName != "BODY") {
  26720. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26721. nodeStack.push(position);
  26722. container.style.position = "static";
  26723. container = container.parentNode;
  26724. }
  26725. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26726. this._bakBodyOverflow = document.body.style.overflow;
  26727. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26728. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26729. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26730. if (this._bakAutoHeight) {
  26731. //当全屏时不能执行自动长高
  26732. editor.autoHeightEnabled = false;
  26733. this.editor.disableAutoHeight();
  26734. }
  26735. document.documentElement.style.overflow = 'hidden';
  26736. //修复,滚动条不收起的问题
  26737. window.scrollTo(0,window.scrollY);
  26738. this._bakCssText = this.getDom().style.cssText;
  26739. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26740. editor.iframe.parentNode.style.width = '';
  26741. this._updateFullScreen();
  26742. } else {
  26743. while (container.tagName != "BODY") {
  26744. container.style.position = nodeStack.shift();
  26745. container = container.parentNode;
  26746. }
  26747. this.getDom().style.cssText = this._bakCssText;
  26748. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26749. if (this._bakAutoHeight) {
  26750. editor.autoHeightEnabled = true;
  26751. this.editor.enableAutoHeight();
  26752. }
  26753. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26754. document.body.style.overflow = this._bakBodyOverflow;
  26755. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26756. window.scrollTo(0, this._bakScrollTop);
  26757. }
  26758. if (browser.gecko && editor.body.contentEditable === 'true') {
  26759. var input = document.createElement('input');
  26760. document.body.appendChild(input);
  26761. editor.body.contentEditable = false;
  26762. setTimeout(function () {
  26763. input.focus();
  26764. setTimeout(function () {
  26765. editor.body.contentEditable = true;
  26766. editor.fireEvent('fullscreenchanged', fullscreen);
  26767. editor.selection.getRange().moveToBookmark(bk).select(true);
  26768. baidu.editor.dom.domUtils.remove(input);
  26769. fullscreen && window.scroll(0, 0);
  26770. }, 0)
  26771. }, 0)
  26772. }
  26773. if(editor.body.contentEditable === 'true'){
  26774. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26775. this.triggerLayout();
  26776. }
  26777. }
  26778. },
  26779. _updateFullScreen:function () {
  26780. if (this._fullscreen) {
  26781. var vpRect = uiUtils.getViewportRect();
  26782. 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);
  26783. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26784. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26785. //不手动调一下,会导致全屏失效
  26786. if(browser.gecko){
  26787. try{
  26788. window.onresize();
  26789. }catch(e){
  26790. }
  26791. }
  26792. }
  26793. },
  26794. _updateElementPath:function () {
  26795. var bottom = this.getDom('elementpath'), list;
  26796. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26797. var buff = [];
  26798. for (var i = 0, ci; ci = list[i]; i++) {
  26799. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26800. }
  26801. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26802. } else {
  26803. bottom.style.display = 'none'
  26804. }
  26805. },
  26806. disableElementPath:function () {
  26807. var bottom = this.getDom('elementpath');
  26808. bottom.innerHTML = '';
  26809. bottom.style.display = 'none';
  26810. this.elementPathEnabled = false;
  26811. },
  26812. enableElementPath:function () {
  26813. var bottom = this.getDom('elementpath');
  26814. bottom.style.display = '';
  26815. this.elementPathEnabled = true;
  26816. this._updateElementPath();
  26817. },
  26818. _scale:function () {
  26819. var doc = document,
  26820. editor = this.editor,
  26821. editorHolder = editor.container,
  26822. editorDocument = editor.document,
  26823. toolbarBox = this.getDom("toolbarbox"),
  26824. bottombar = this.getDom("bottombar"),
  26825. scale = this.getDom("scale"),
  26826. scalelayer = this.getDom("scalelayer");
  26827. var isMouseMove = false,
  26828. position = null,
  26829. minEditorHeight = 0,
  26830. minEditorWidth = editor.options.minFrameWidth,
  26831. pageX = 0,
  26832. pageY = 0,
  26833. scaleWidth = 0,
  26834. scaleHeight = 0;
  26835. function down() {
  26836. position = domUtils.getXY(editorHolder);
  26837. if (!minEditorHeight) {
  26838. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26839. }
  26840. 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:"
  26841. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26842. domUtils.on(doc, "mousemove", move);
  26843. domUtils.on(editorDocument, "mouseup", up);
  26844. domUtils.on(doc, "mouseup", up);
  26845. }
  26846. var me = this;
  26847. //by xuheng 全屏时关掉缩放
  26848. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26849. if (fullScreen) {
  26850. me.disableScale();
  26851. } else {
  26852. if (me.editor.options.scaleEnabled) {
  26853. me.enableScale();
  26854. var tmpNode = me.editor.document.createElement('span');
  26855. me.editor.body.appendChild(tmpNode);
  26856. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26857. domUtils.remove(tmpNode)
  26858. }
  26859. }
  26860. });
  26861. function move(event) {
  26862. clearSelection();
  26863. var e = event || window.event;
  26864. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26865. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26866. scaleWidth = pageX - position.x;
  26867. scaleHeight = pageY - position.y;
  26868. if (scaleWidth >= minEditorWidth) {
  26869. isMouseMove = true;
  26870. scalelayer.style.width = scaleWidth + 'px';
  26871. }
  26872. if (scaleHeight >= minEditorHeight) {
  26873. isMouseMove = true;
  26874. scalelayer.style.height = scaleHeight + "px";
  26875. }
  26876. }
  26877. function up() {
  26878. if (isMouseMove) {
  26879. isMouseMove = false;
  26880. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26881. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26882. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26883. }
  26884. if (scalelayer) {
  26885. scalelayer.style.display = "none";
  26886. }
  26887. clearSelection();
  26888. domUtils.un(doc, "mousemove", move);
  26889. domUtils.un(editorDocument, "mouseup", up);
  26890. domUtils.un(doc, "mouseup", up);
  26891. }
  26892. function clearSelection() {
  26893. if (browser.ie)
  26894. doc.selection.clear();
  26895. else
  26896. window.getSelection().removeAllRanges();
  26897. }
  26898. this.enableScale = function () {
  26899. //trace:2868
  26900. if (editor.queryCommandState("source") == 1) return;
  26901. scale.style.display = "";
  26902. this.scaleEnabled = true;
  26903. domUtils.on(scale, "mousedown", down);
  26904. };
  26905. this.disableScale = function () {
  26906. scale.style.display = "none";
  26907. this.scaleEnabled = false;
  26908. domUtils.un(scale, "mousedown", down);
  26909. };
  26910. },
  26911. isFullScreen:function () {
  26912. return this._fullscreen;
  26913. },
  26914. postRender:function () {
  26915. UIBase.prototype.postRender.call(this);
  26916. for (var i = 0; i < this.toolbars.length; i++) {
  26917. this.toolbars[i].postRender();
  26918. }
  26919. var me = this;
  26920. var timerId,
  26921. domUtils = baidu.editor.dom.domUtils,
  26922. updateFullScreenTime = function () {
  26923. clearTimeout(timerId);
  26924. timerId = setTimeout(function () {
  26925. me._updateFullScreen();
  26926. });
  26927. };
  26928. domUtils.on(window, 'resize', updateFullScreenTime);
  26929. me.addListener('destroy', function () {
  26930. domUtils.un(window, 'resize', updateFullScreenTime);
  26931. clearTimeout(timerId);
  26932. })
  26933. },
  26934. showToolbarMsg:function (msg, flag) {
  26935. this.getDom('toolbarmsg_label').innerHTML = msg;
  26936. this.getDom('toolbarmsg').style.display = '';
  26937. //
  26938. if (!flag) {
  26939. var w = this.getDom('upload_dialog');
  26940. w.style.display = 'none';
  26941. }
  26942. },
  26943. hideToolbarMsg:function () {
  26944. this.getDom('toolbarmsg').style.display = 'none';
  26945. },
  26946. mapUrl:function (url) {
  26947. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26948. },
  26949. triggerLayout:function () {
  26950. var dom = this.getDom();
  26951. if (dom.style.zoom == '1') {
  26952. dom.style.zoom = '100%';
  26953. } else {
  26954. dom.style.zoom = '1';
  26955. }
  26956. }
  26957. };
  26958. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26959. var instances = {};
  26960. UE.ui.Editor = function (options) {
  26961. var editor = new UE.Editor(options);
  26962. editor.options.editor = editor;
  26963. utils.loadFile(document, {
  26964. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26965. tag:"link",
  26966. type:"text/css",
  26967. rel:"stylesheet"
  26968. });
  26969. var oldRender = editor.render;
  26970. editor.render = function (holder) {
  26971. if (holder.constructor === String) {
  26972. editor.key = holder;
  26973. instances[holder] = editor;
  26974. }
  26975. utils.domReady(function () {
  26976. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26977. function renderUI() {
  26978. editor.setOpt({
  26979. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26980. });
  26981. new EditorUI(editor.options);
  26982. if (holder) {
  26983. if (holder.constructor === String) {
  26984. holder = document.getElementById(holder);
  26985. }
  26986. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26987. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26988. var newDiv = document.createElement('div');
  26989. holder.parentNode.insertBefore(newDiv, holder);
  26990. var cont = holder.value || holder.innerHTML;
  26991. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26992. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26993. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26994. .replace(/>[\n\r\t]+</g, '><');
  26995. holder.className && (newDiv.className = holder.className);
  26996. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26997. if (/textarea/i.test(holder.tagName)) {
  26998. editor.textarea = holder;
  26999. editor.textarea.style.display = 'none';
  27000. } else {
  27001. holder.parentNode.removeChild(holder);
  27002. }
  27003. if(holder.id){
  27004. newDiv.id = holder.id;
  27005. domUtils.removeAttributes(holder,'id');
  27006. }
  27007. holder = newDiv;
  27008. holder.innerHTML = '';
  27009. }
  27010. }
  27011. domUtils.addClass(holder, "edui-" + editor.options.theme);
  27012. editor.ui.render(holder);
  27013. var opt = editor.options;
  27014. //给实例添加一个编辑器的容器引用
  27015. editor.container = editor.ui.getDom();
  27016. var parents = domUtils.findParents(holder,true);
  27017. var displays = [];
  27018. for(var i = 0 ,ci;ci=parents[i];i++){
  27019. displays[i] = ci.style.display;
  27020. ci.style.display = 'block'
  27021. }
  27022. if (opt.initialFrameWidth) {
  27023. opt.minFrameWidth = opt.initialFrameWidth;
  27024. } else {
  27025. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  27026. var styleWidth = holder.style.width;
  27027. if(/%$/.test(styleWidth)) {
  27028. opt.initialFrameWidth = styleWidth;
  27029. }
  27030. }
  27031. if (opt.initialFrameHeight) {
  27032. opt.minFrameHeight = opt.initialFrameHeight;
  27033. } else {
  27034. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  27035. }
  27036. for(var i = 0 ,ci;ci=parents[i];i++){
  27037. ci.style.display = displays[i]
  27038. }
  27039. //编辑器最外容器设置了高度,会导致,编辑器不占位
  27040. //todo 先去掉,没有找到原因
  27041. if(holder.style.height){
  27042. holder.style.height = ''
  27043. }
  27044. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  27045. editor.container.style.zIndex = opt.zIndex;
  27046. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  27047. editor.fireEvent("afteruiready");
  27048. }
  27049. })
  27050. };
  27051. return editor;
  27052. };
  27053. /**
  27054. * @file
  27055. * @name UE
  27056. * @short UE
  27057. * @desc UEditor的顶部命名空间
  27058. */
  27059. /**
  27060. * @name getEditor
  27061. * @since 1.2.4+
  27062. * @grammar UE.getEditor(id,[opt]) => Editor实例
  27063. * @desc 提供一个全局的方法得到编辑器实例
  27064. *
  27065. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  27066. * * ''opt'' 编辑器的可选参数
  27067. * @example
  27068. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  27069. * this.setContent('hello')
  27070. * }});
  27071. * UE.getEditor('containerId'); //返回刚创建的实例
  27072. *
  27073. */
  27074. UE.getEditor = function (id, opt) {
  27075. var editor = instances[id];
  27076. if (!editor) {
  27077. editor = instances[id] = new UE.ui.Editor(opt);
  27078. editor.render(id);
  27079. }
  27080. return editor;
  27081. };
  27082. UE.delEditor = function (id) {
  27083. var editor;
  27084. if (editor = instances[id]) {
  27085. editor.key && editor.destroy();
  27086. delete instances[id]
  27087. }
  27088. };
  27089. UE.registerUI = function(uiName,fn,index,editorId){
  27090. utils.each(uiName.split(/\s+/), function (name) {
  27091. UE._customizeUI[name] = {
  27092. id : editorId,
  27093. execFn:fn,
  27094. index:index
  27095. };
  27096. })
  27097. }
  27098. })();
  27099. // adapter/message.js
  27100. UE.registerUI('message', function(editor) {
  27101. var editorui = baidu.editor.ui;
  27102. var Message = editorui.Message;
  27103. var holder;
  27104. var _messageItems = [];
  27105. var me = editor;
  27106. me.addListener('ready', function(){
  27107. holder = document.getElementById(me.ui.id + '_message_holder');
  27108. updateHolderPos();
  27109. setTimeout(function(){
  27110. updateHolderPos();
  27111. }, 500);
  27112. });
  27113. me.addListener('showmessage', function(type, opt){
  27114. opt = utils.isString(opt) ? {
  27115. 'content': opt
  27116. } : opt;
  27117. var message = new Message({
  27118. 'timeout': opt.timeout,
  27119. 'type': opt.type,
  27120. 'content': opt.content,
  27121. 'keepshow': opt.keepshow,
  27122. 'editor': me
  27123. }),
  27124. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27125. message.render(holder);
  27126. _messageItems[mid] = message;
  27127. message.reset(opt);
  27128. updateHolderPos();
  27129. return mid;
  27130. });
  27131. me.addListener('updatemessage',function(type, id, opt){
  27132. opt = utils.isString(opt) ? {
  27133. 'content': opt
  27134. } : opt;
  27135. var message = _messageItems[id];
  27136. message.render(holder);
  27137. message && message.reset(opt);
  27138. });
  27139. me.addListener('hidemessage',function(type, id){
  27140. var message = _messageItems[id];
  27141. message && message.hide();
  27142. });
  27143. function updateHolderPos(){
  27144. var toolbarbox = me.ui.getDom('toolbarbox');
  27145. if (toolbarbox) {
  27146. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27147. }
  27148. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27149. }
  27150. });
  27151. // adapter/autosave.js
  27152. UE.registerUI('autosave', function(editor) {
  27153. var timer = null,uid = null;
  27154. editor.on('afterautosave',function(){
  27155. clearTimeout(timer);
  27156. timer = setTimeout(function(){
  27157. if(uid){
  27158. editor.trigger('hidemessage',uid);
  27159. }
  27160. uid = editor.trigger('showmessage',{
  27161. content : editor.getLang('autosave.success'),
  27162. timeout : 2000
  27163. });
  27164. },2000)
  27165. })
  27166. });
  27167. })();