bf435880a65452df6a7d226f6307f8b580c6cbb4.svn-base 861 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021
  1. (function(){
  2. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  3. var baidu = window.baidu || {};
  4. window.baidu = baidu;
  5. window.UE = baidu.editor = {};
  6. UE.plugins = {};
  7. UE.commands = {};
  8. UE.instants = {};
  9. UE.I18N = {};
  10. UE.version = "1.2.6.1";
  11. var dom = UE.dom = {};
  12. /**
  13. * @file
  14. * @name UE.browser
  15. * @short Browser
  16. * @desc UEditor中采用的浏览器判断模块
  17. */
  18. var browser = UE.browser = function(){
  19. var agent = navigator.userAgent.toLowerCase(),
  20. opera = window.opera,
  21. browser = {
  22. /**
  23. * 检测浏览器是否为IE
  24. * @name ie
  25. * @grammar UE.browser.ie => true|false
  26. */
  27. ie : !!window.ActiveXObject,
  28. /**
  29. * 检测浏览器是否为Opera
  30. * @name opera
  31. * @grammar UE.browser.opera => true|false
  32. */
  33. opera : ( !!opera && opera.version ),
  34. /**
  35. * 检测浏览器是否为webkit内核
  36. * @name webkit
  37. * @grammar UE.browser.webkit => true|false
  38. */
  39. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  40. /**
  41. * 检测浏览器是否为mac系统下的浏览器
  42. * @name mac
  43. * @grammar UE.browser.mac => true|false
  44. */
  45. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  46. /**
  47. * 检测浏览器是否处于怪异模式
  48. * @name quirks
  49. * @grammar UE.browser.quirks => true|false
  50. */
  51. quirks : ( document.compatMode == 'BackCompat' )
  52. };
  53. /**
  54. * 检测浏览器是否处为gecko内核
  55. * @name gecko
  56. * @grammar UE.browser.gecko => true|false
  57. */
  58. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera );
  59. var version = 0;
  60. // Internet Explorer 6.0+
  61. if ( browser.ie ){
  62. version = parseFloat( agent.match( /msie (\d+)/ )[1] );
  63. /**
  64. * 检测浏览器是否为 IE9 模式
  65. * @name ie9Compat
  66. * @grammar UE.browser.ie9Compat => true|false
  67. */
  68. browser.ie9Compat = document.documentMode == 9;
  69. /**
  70. * 检测浏览器是否为 IE8 浏览器
  71. * @name ie8
  72. * @grammar UE.browser.ie8 => true|false
  73. */
  74. browser.ie8 = !!document.documentMode;
  75. /**
  76. * 检测浏览器是否为 IE8 模式
  77. * @name ie8Compat
  78. * @grammar UE.browser.ie8Compat => true|false
  79. */
  80. browser.ie8Compat = document.documentMode == 8;
  81. /**
  82. * 检测浏览器是否运行在 兼容IE7模式
  83. * @name ie7Compat
  84. * @grammar UE.browser.ie7Compat => true|false
  85. */
  86. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  87. || document.documentMode == 7 );
  88. /**
  89. * 检测浏览器是否IE6模式或怪异模式
  90. * @name ie6Compat
  91. * @grammar UE.browser.ie6Compat => true|false
  92. */
  93. browser.ie6Compat = ( version < 7 || browser.quirks );
  94. browser.ie9above = version > 8;
  95. browser.ie9under = version < 9;
  96. }
  97. // Gecko.
  98. if ( browser.gecko ){
  99. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  100. if ( geckoRelease )
  101. {
  102. geckoRelease = geckoRelease[1].split( '.' );
  103. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  104. }
  105. }
  106. /**
  107. * 检测浏览器是否为chrome
  108. * @name chrome
  109. * @grammar UE.browser.chrome => true|false
  110. */
  111. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  112. browser.chrome = + RegExp['\x241'];
  113. }
  114. /**
  115. * 检测浏览器是否为safari
  116. * @name safari
  117. * @grammar UE.browser.safari => true|false
  118. */
  119. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  120. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  121. }
  122. // Opera 9.50+
  123. if ( browser.opera )
  124. version = parseFloat( opera.version() );
  125. // WebKit 522+ (Safari 3+)
  126. if ( browser.webkit )
  127. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  128. /**
  129. * 浏览器版本判断
  130. * IE系列返回值为5,6,7,8,9,10等
  131. * gecko系列会返回10900,158900等.
  132. * webkit系列会返回其build号 (如 522等).
  133. * @name version
  134. * @grammar UE.browser.version => number
  135. * @example
  136. * if ( UE.browser.ie && UE.browser.version == 6 ){
  137. * alert( "Ouch!居然是万恶的IE6!" );
  138. * }
  139. */
  140. browser.version = version;
  141. /**
  142. * 是否是兼容模式的浏览器
  143. * @name isCompatible
  144. * @grammar UE.browser.isCompatible => true|false
  145. * @example
  146. * if ( UE.browser.isCompatible ){
  147. * alert( "你的浏览器相当不错哦!" );
  148. * }
  149. */
  150. browser.isCompatible =
  151. !browser.mobile && (
  152. ( browser.ie && version >= 6 ) ||
  153. ( browser.gecko && version >= 10801 ) ||
  154. ( browser.opera && version >= 9.5 ) ||
  155. ( browser.air && version >= 1 ) ||
  156. ( browser.webkit && version >= 522 ) ||
  157. false );
  158. return browser;
  159. }();
  160. //快捷方式
  161. var ie = browser.ie,
  162. webkit = browser.webkit,
  163. gecko = browser.gecko,
  164. opera = browser.opera;
  165. /**
  166. * @file
  167. * @name UE.Utils
  168. * @short Utils
  169. * @desc UEditor封装使用的静态工具函数
  170. * @import editor.js
  171. */
  172. var utils = UE.utils = {
  173. /**
  174. * 遍历数组,对象,nodeList
  175. * @name each
  176. * @grammar UE.utils.each(obj,iterator,[context])
  177. * @since 1.2.4+
  178. * @desc
  179. * * obj 要遍历的对象
  180. * * iterator 遍历的方法,方法的第一个是遍历的值,第二个是索引,第三个是obj
  181. * * context iterator的上下文
  182. * @example
  183. * UE.utils.each([1,2],function(v,i){
  184. * console.log(v)//值
  185. * console.log(i)//索引
  186. * })
  187. * UE.utils.each(document.getElementsByTagName('*'),function(n){
  188. * console.log(n.tagName)
  189. * })
  190. */
  191. each : function(obj, iterator, context) {
  192. if (obj == null) return;
  193. if (obj.length === +obj.length) {
  194. for (var i = 0, l = obj.length; i < l; i++) {
  195. if(iterator.call(context, obj[i], i, obj) === false)
  196. return false;
  197. }
  198. } else {
  199. for (var key in obj) {
  200. if (obj.hasOwnProperty(key)) {
  201. if(iterator.call(context, obj[key], key, obj) === false)
  202. return false;
  203. }
  204. }
  205. }
  206. },
  207. makeInstance:function (obj) {
  208. var noop = new Function();
  209. noop.prototype = obj;
  210. obj = new noop;
  211. noop.prototype = null;
  212. return obj;
  213. },
  214. /**
  215. * 将source对象中的属性扩展到target对象上
  216. * @name extend
  217. * @grammar UE.utils.extend(target,source) => Object //覆盖扩展
  218. * @grammar UE.utils.extend(target,source,true) ==> Object //保留扩展
  219. */
  220. extend:function (t, s, b) {
  221. if (s) {
  222. for (var k in s) {
  223. if (!b || !t.hasOwnProperty(k)) {
  224. t[k] = s[k];
  225. }
  226. }
  227. }
  228. return t;
  229. },
  230. extend2:function (t) {
  231. var a = arguments;
  232. for (var i = 1; i < a.length; i++) {
  233. var x = a[i];
  234. for (var k in x) {
  235. if (!t.hasOwnProperty(k)) {
  236. t[k] = x[k];
  237. }
  238. }
  239. }
  240. return t;
  241. },
  242. /**
  243. * 模拟继承机制,subClass继承superClass
  244. * @name inherits
  245. * @grammar UE.utils.inherits(subClass,superClass) => subClass
  246. * @example
  247. * function SuperClass(){
  248. * this.name = "小李";
  249. * }
  250. * SuperClass.prototype = {
  251. * hello:function(str){
  252. * console.log(this.name + str);
  253. * }
  254. * }
  255. * function SubClass(){
  256. * this.name = "小张";
  257. * }
  258. * UE.utils.inherits(SubClass,SuperClass);
  259. * var sub = new SubClass();
  260. * sub.hello("早上好!"); ==> "小张早上好!"
  261. */
  262. inherits:function (subClass, superClass) {
  263. var oldP = subClass.prototype,
  264. newP = utils.makeInstance(superClass.prototype);
  265. utils.extend(newP, oldP, true);
  266. subClass.prototype = newP;
  267. return (newP.constructor = subClass);
  268. },
  269. /**
  270. * 用指定的context作为fn上下文,也就是this
  271. * @name bind
  272. * @grammar UE.utils.bind(fn,context) => fn
  273. */
  274. bind:function (fn, context) {
  275. return function () {
  276. return fn.apply(context, arguments);
  277. };
  278. },
  279. /**
  280. * 创建延迟delay执行的函数fn
  281. * @name defer
  282. * @grammar UE.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn
  283. * @grammar UE.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn
  284. * @example
  285. * function test(){
  286. * console.log("延迟输出!");
  287. * }
  288. * //非互斥延迟执行
  289. * var testDefer = UE.utils.defer(test,1000);
  290. * testDefer(); => "延迟输出!";
  291. * testDefer(); => "延迟输出!";
  292. * //互斥延迟执行
  293. * var testDefer1 = UE.utils.defer(test,1000,true);
  294. * testDefer1(); => //本次不执行
  295. * testDefer1(); => "延迟输出!";
  296. */
  297. defer:function (fn, delay, exclusion) {
  298. var timerID;
  299. return function () {
  300. if (exclusion) {
  301. clearTimeout(timerID);
  302. }
  303. timerID = setTimeout(fn, delay);
  304. };
  305. },
  306. /**
  307. * 查找元素item在数组array中的索引, 若找不到返回-1
  308. * @name indexOf
  309. * @grammar UE.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索
  310. * @grammar UE.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置
  311. */
  312. indexOf:function (array, item, start) {
  313. var index = -1;
  314. start = this.isNumber(start) ? start : 0;
  315. this.each(array, function (v, i) {
  316. if (i >= start && v === item) {
  317. index = i;
  318. return false;
  319. }
  320. });
  321. return index;
  322. },
  323. /**
  324. * 移除数组array中的元素item
  325. * @name removeItem
  326. * @grammar UE.utils.removeItem(array,item)
  327. */
  328. removeItem:function (array, item) {
  329. for (var i = 0, l = array.length; i < l; i++) {
  330. if (array[i] === item) {
  331. array.splice(i, 1);
  332. i--;
  333. }
  334. }
  335. },
  336. /**
  337. * 删除字符串str的首尾空格
  338. * @name trim
  339. * @grammar UE.utils.trim(str) => String
  340. */
  341. trim:function (str) {
  342. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  343. },
  344. /**
  345. * 将字符串list(以','分隔)或者数组list转成哈希对象
  346. * @name listToMap
  347. * @grammar UE.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1}
  348. */
  349. listToMap:function (list) {
  350. if (!list)return {};
  351. list = utils.isArray(list) ? list : list.split(',');
  352. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  353. obj[ci.toUpperCase()] = obj[ci] = 1;
  354. }
  355. return obj;
  356. },
  357. /**
  358. * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符
  359. * @name unhtml
  360. * @grammar UE.utils.unhtml(str); => String
  361. * @grammar UE.utils.unhtml(str,reg) => String
  362. * @example
  363. * var html = '<body>You say:"你好!Baidu & UEditor!"</body>';
  364. * UE.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt;
  365. * UE.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt;
  366. */
  367. unhtml:function (str, reg) {
  368. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  369. if (b) {
  370. return a;
  371. } else {
  372. return {
  373. '<':'&lt;',
  374. '&':'&amp;',
  375. '"':'&quot;',
  376. '>':'&gt;',
  377. "'":'&#39;'
  378. }[a]
  379. }
  380. }) : '';
  381. },
  382. /**
  383. * 将str中的转义字符还原成html字符
  384. * @name html
  385. * @grammar UE.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code>
  386. */
  387. html:function (str) {
  388. return str ? str.replace(/&((g|l|quo)t|amp|#39);/g, function (m) {
  389. return {
  390. '&lt;':'<',
  391. '&amp;':'&',
  392. '&quot;':'"',
  393. '&gt;':'>',
  394. '&#39;':"'"
  395. }[m]
  396. }) : '';
  397. },
  398. /**
  399. * 将css样式转换为驼峰的形式。如font-size => fontSize
  400. * @name cssStyleToDomStyle
  401. * @grammar UE.utils.cssStyleToDomStyle(cssName) => String
  402. */
  403. cssStyleToDomStyle:function () {
  404. var test = document.createElement('div').style,
  405. cache = {
  406. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  407. };
  408. return function (cssName) {
  409. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  410. return match.charAt(1).toUpperCase();
  411. }));
  412. };
  413. }(),
  414. /**
  415. * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn
  416. * @name loadFile
  417. * @grammar UE.utils.loadFile(doc,obj)
  418. * @grammar UE.utils.loadFile(doc,obj,fn)
  419. * @example
  420. * //指定加载到当前document中一个script文件,加载成功后执行function
  421. * utils.loadFile( document, {
  422. * src:"test.js",
  423. * tag:"script",
  424. * type:"text/javascript",
  425. * defer:"defer"
  426. * }, function () {
  427. * console.log('加载成功!')
  428. * });
  429. */
  430. loadFile:function () {
  431. var tmpList = [];
  432. function getItem(doc, obj) {
  433. try {
  434. for (var i = 0, ci; ci = tmpList[i++];) {
  435. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  436. return ci;
  437. }
  438. }
  439. } catch (e) {
  440. return null;
  441. }
  442. }
  443. return function (doc, obj, fn) {
  444. var item = getItem(doc, obj);
  445. if (item) {
  446. if (item.ready) {
  447. fn && fn();
  448. } else {
  449. item.funs.push(fn)
  450. }
  451. return;
  452. }
  453. tmpList.push({
  454. doc:doc,
  455. url:obj.src || obj.href,
  456. funs:[fn]
  457. });
  458. if (!doc.body) {
  459. var html = [];
  460. for (var p in obj) {
  461. if (p == 'tag')continue;
  462. html.push(p + '="' + obj[p] + '"')
  463. }
  464. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  465. return;
  466. }
  467. if (obj.id && doc.getElementById(obj.id)) {
  468. return;
  469. }
  470. var element = doc.createElement(obj.tag);
  471. delete obj.tag;
  472. for (var p in obj) {
  473. element.setAttribute(p, obj[p]);
  474. }
  475. element.onload = element.onreadystatechange = function () {
  476. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  477. item = getItem(doc, obj);
  478. if (item.funs.length > 0) {
  479. item.ready = 1;
  480. for (var fi; fi = item.funs.pop();) {
  481. fi();
  482. }
  483. }
  484. element.onload = element.onreadystatechange = null;
  485. }
  486. };
  487. element.onerror = function () {
  488. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  489. };
  490. doc.getElementsByTagName("head")[0].appendChild(element);
  491. }
  492. }(),
  493. /**
  494. * 判断obj对象是否为空
  495. * @name isEmptyObject
  496. * @grammar UE.utils.isEmptyObject(obj) => true|false
  497. * @example
  498. * UE.utils.isEmptyObject({}) ==>true
  499. * UE.utils.isEmptyObject([]) ==>true
  500. * UE.utils.isEmptyObject("") ==>true
  501. */
  502. isEmptyObject:function (obj) {
  503. if (obj == null) return true;
  504. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  505. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  506. return true;
  507. },
  508. /**
  509. * 统一将颜色值使用16进制形式表示
  510. * @name fixColor
  511. * @grammar UE.utils.fixColor(name,value) => value
  512. * @example
  513. * rgb(255,255,255) => "#ffffff"
  514. */
  515. fixColor:function (name, value) {
  516. if (/color/i.test(name) && /rgba?/.test(value)) {
  517. var array = value.split(",");
  518. if (array.length > 3)
  519. return "";
  520. value = "#";
  521. for (var i = 0, color; color = array[i++];) {
  522. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  523. value += color.length == 1 ? "0" + color : color;
  524. }
  525. value = value.toUpperCase();
  526. }
  527. return value;
  528. },
  529. /**
  530. * 只针对border,padding,margin做了处理,因为性能问题
  531. * @public
  532. * @function
  533. * @param {String} val style字符串
  534. */
  535. optCss:function (val) {
  536. var padding, margin, border;
  537. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  538. if (val.split(' ').length == 1) {
  539. switch (key) {
  540. case 'padding':
  541. !padding && (padding = {});
  542. padding[name] = val;
  543. return '';
  544. case 'margin':
  545. !margin && (margin = {});
  546. margin[name] = val;
  547. return '';
  548. case 'border':
  549. return val == 'initial' ? '' : str;
  550. }
  551. }
  552. return str;
  553. });
  554. function opt(obj, name) {
  555. if (!obj) {
  556. return '';
  557. }
  558. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  559. if (!t || !l || !b || !r) {
  560. for (var p in obj) {
  561. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  562. }
  563. } else {
  564. val += ';' + name + ':' +
  565. (t == b && b == l && l == r ? t :
  566. t == b && l == r ? (t + ' ' + l) :
  567. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  568. }
  569. return val;
  570. }
  571. val += opt(padding, 'padding') + opt(margin, 'margin');
  572. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  573. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  574. return b ? b + ";;" : ';'
  575. });
  576. },
  577. /**
  578. * 深度克隆对象,从source到target
  579. * @name clone
  580. * @grammar UE.utils.clone(source) => anthorObj 新的对象是完整的source的副本
  581. * @grammar UE.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖
  582. */
  583. clone:function (source, target) {
  584. var tmp;
  585. target = target || {};
  586. for (var i in source) {
  587. if (source.hasOwnProperty(i)) {
  588. tmp = source[i];
  589. if (typeof tmp == 'object') {
  590. target[i] = utils.isArray(tmp) ? [] : {};
  591. utils.clone(source[i], target[i])
  592. } else {
  593. target[i] = tmp;
  594. }
  595. }
  596. }
  597. return target;
  598. },
  599. /**
  600. * 转换cm/pt到px
  601. * @name transUnitToPx
  602. * @grammar UE.utils.transUnitToPx('20pt') => '27px'
  603. * @grammar UE.utils.transUnitToPx('0pt') => '0'
  604. */
  605. transUnitToPx:function (val) {
  606. if (!/(pt|cm)/.test(val)) {
  607. return val
  608. }
  609. var unit;
  610. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  611. val = v;
  612. unit = u;
  613. });
  614. switch (unit) {
  615. case 'cm':
  616. val = parseFloat(val) * 25;
  617. break;
  618. case 'pt':
  619. val = Math.round(parseFloat(val) * 96 / 72);
  620. }
  621. return val + (val ? 'px' : '');
  622. },
  623. /**
  624. * DomReady方法,回调函数将在dom树ready完成后执行
  625. * @name domReady
  626. * @grammar UE.utils.domReady(fn) => fn //返回一个延迟执行的方法
  627. */
  628. domReady:function () {
  629. var fnArr = [];
  630. function doReady(doc) {
  631. //确保onready只执行一次
  632. doc.isReady = true;
  633. for (var ci; ci = fnArr.pop(); ci()) {
  634. }
  635. }
  636. return function (onready, win) {
  637. win = win || window;
  638. var doc = win.document;
  639. onready && fnArr.push(onready);
  640. if (doc.readyState === "complete") {
  641. doReady(doc);
  642. } else {
  643. doc.isReady && doReady(doc);
  644. if (browser.ie) {
  645. (function () {
  646. if (doc.isReady) return;
  647. try {
  648. doc.documentElement.doScroll("left");
  649. } catch (error) {
  650. setTimeout(arguments.callee, 0);
  651. return;
  652. }
  653. doReady(doc);
  654. })();
  655. win.attachEvent('onload', function () {
  656. doReady(doc)
  657. });
  658. } else {
  659. doc.addEventListener("DOMContentLoaded", function () {
  660. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  661. doReady(doc);
  662. }, false);
  663. win.addEventListener('load', function () {
  664. doReady(doc)
  665. }, false);
  666. }
  667. }
  668. }
  669. }(),
  670. /**
  671. * 动态添加css样式
  672. * @name cssRule
  673. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  674. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  675. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  676. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  677. */
  678. cssRule:browser.ie ? function (key, style, doc) {
  679. var indexList, index;
  680. doc = doc || document;
  681. if (doc.indexList) {
  682. indexList = doc.indexList;
  683. } else {
  684. indexList = doc.indexList = {};
  685. }
  686. var sheetStyle;
  687. if (!indexList[key]) {
  688. if (style === undefined) {
  689. return ''
  690. }
  691. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  692. indexList[key] = index;
  693. } else {
  694. sheetStyle = doc.styleSheets[indexList[key]];
  695. }
  696. if (style === undefined) {
  697. return sheetStyle.cssText
  698. }
  699. sheetStyle.cssText = style || ''
  700. } : function (key, style, doc) {
  701. doc = doc || document;
  702. var head = doc.getElementsByTagName('head')[0], node;
  703. if (!(node = doc.getElementById(key))) {
  704. if (style === undefined) {
  705. return ''
  706. }
  707. node = doc.createElement('style');
  708. node.id = key;
  709. head.appendChild(node)
  710. }
  711. if (style === undefined) {
  712. return node.innerHTML
  713. }
  714. if (style !== '') {
  715. node.innerHTML = style;
  716. } else {
  717. head.removeChild(node)
  718. }
  719. },
  720. sort:function(array,compareFn){
  721. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  722. for(var i= 0,len = array.length; i<len; i++){
  723. for(var j = i,length = array.length; j<length; j++){
  724. if(compareFn(array[i], array[j]) > 0){
  725. var t = array[i];
  726. array[i] = array[j];
  727. array[j] = t;
  728. }
  729. }
  730. }
  731. return array;
  732. }
  733. };
  734. /**
  735. * 判断str是否为字符串
  736. * @name isString
  737. * @grammar UE.utils.isString(str) => true|false
  738. */
  739. /**
  740. * 判断array是否为数组
  741. * @name isArray
  742. * @grammar UE.utils.isArray(obj) => true|false
  743. */
  744. /**
  745. * 判断obj对象是否为方法
  746. * @name isFunction
  747. * @grammar UE.utils.isFunction(obj) => true|false
  748. */
  749. /**
  750. * 判断obj对象是否为数字
  751. * @name isNumber
  752. * @grammar UE.utils.isNumber(obj) => true|false
  753. */
  754. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) {
  755. UE.utils['is' + v] = function (obj) {
  756. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  757. }
  758. });
  759. /**
  760. * @file
  761. * @name UE.EventBase
  762. * @short EventBase
  763. * @import editor.js,core/utils.js
  764. * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  765. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  766. */
  767. var EventBase = UE.EventBase = function () {};
  768. EventBase.prototype = {
  769. /**
  770. * 注册事件监听器
  771. * @name addListener
  772. * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔
  773. * @example
  774. * editor.addListener('selectionchange',function(){
  775. * console.log("选区已经变化!");
  776. * })
  777. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  778. * if(type == 'beforegetcontent'){
  779. * //do something
  780. * }else{
  781. * //do something
  782. * }
  783. * console.log(this.getContent) // this是注册的事件的编辑器实例
  784. * })
  785. */
  786. addListener:function (types, listener) {
  787. types = utils.trim(types).split(' ');
  788. for (var i = 0, ti; ti = types[i++];) {
  789. getListener(this, ti, true).push(listener);
  790. }
  791. },
  792. /**
  793. * 移除事件监听器
  794. * @name removeListener
  795. * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔
  796. * @example
  797. * //changeCallback为方法体
  798. * editor.removeListener("selectionchange",changeCallback);
  799. */
  800. removeListener:function (types, listener) {
  801. types = utils.trim(types).split(' ');
  802. for (var i = 0, ti; ti = types[i++];) {
  803. utils.removeItem(getListener(this, ti) || [], listener);
  804. }
  805. },
  806. /**
  807. * 触发事件
  808. * @name fireEvent
  809. * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔
  810. * @example
  811. * editor.fireEvent("selectionchange");
  812. */
  813. fireEvent:function () {
  814. var types = arguments[0];
  815. types = utils.trim(types).split(' ');
  816. for (var i = 0, ti; ti = types[i++];) {
  817. var listeners = getListener(this, ti),
  818. r, t, k;
  819. if (listeners) {
  820. k = listeners.length;
  821. while (k--) {
  822. if(!listeners[k])continue;
  823. t = listeners[k].apply(this, arguments);
  824. if(t === true){
  825. return t;
  826. }
  827. if (t !== undefined) {
  828. r = t;
  829. }
  830. }
  831. }
  832. if (t = this['on' + ti.toLowerCase()]) {
  833. r = t.apply(this, arguments);
  834. }
  835. }
  836. return r;
  837. }
  838. };
  839. /**
  840. * 获得对象所拥有监听类型的所有监听器
  841. * @public
  842. * @function
  843. * @param {Object} obj 查询监听器的对象
  844. * @param {String} type 事件类型
  845. * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  846. * @returns {Array} 监听器数组
  847. */
  848. function getListener(obj, type, force) {
  849. var allListeners;
  850. type = type.toLowerCase();
  851. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  852. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  853. }
  854. ///import editor.js
  855. ///import core/dom/dom.js
  856. ///import core/utils.js
  857. /**
  858. * dtd html语义化的体现类
  859. * @constructor
  860. * @namespace dtd
  861. */
  862. var dtd = dom.dtd = (function() {
  863. function _( s ) {
  864. for (var k in s) {
  865. s[k.toUpperCase()] = s[k];
  866. }
  867. return s;
  868. }
  869. var X = utils.extend2;
  870. var A = _({isindex:1,fieldset:1}),
  871. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  872. C = X( _({a:1}), B ),
  873. D = X( {iframe:1}, C ),
  874. 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}),
  875. F = _({ins:1,del:1,script:1,style:1}),
  876. 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 ),
  877. 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 ),
  878. I = X( _({p:1}), H ),
  879. J = X( _({iframe:1}), H, B ),
  880. 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}),
  881. L = X( _({a:0}), J ),//a不能被切开,所以把他
  882. M = _({tr:1}),
  883. N = _({'#':1}),
  884. O = X( _({param:1}), K ),
  885. P = X( _({form:1}), A, D, E, I ),
  886. Q = _({li:1,ol:1,ul:1}),
  887. R = _({style:1,script:1}),
  888. S = _({base:1,link:1,meta:1,title:1}),
  889. T = X( S, R ),
  890. U = _({head:1,body:1}),
  891. V = _({html:1});
  892. 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}),
  893. 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});
  894. return _({
  895. // $ 表示自定的属性
  896. // body外的元素列表.
  897. $nonBodyContent: X( V, U, S ),
  898. //块结构元素列表
  899. $block : block,
  900. //内联元素列表
  901. $inline : L,
  902. $inlineWithA : X(_({a:1}),L),
  903. $body : X( _({script:1,style:1}), block ),
  904. $cdata : _({script:1,style:1}),
  905. //自闭和元素
  906. $empty : empty,
  907. //不是自闭合,但不能让range选中里边
  908. $nonChild : _({iframe:1,textarea:1}),
  909. //列表元素列表
  910. $listItem : _({dd:1,dt:1,li:1}),
  911. //列表根元素列表
  912. $list: _({ul:1,ol:1,dl:1}),
  913. //不能认为是空的元素
  914. $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}),
  915. //如果没有子节点就可以删除的元素列表,像span,a
  916. $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}),
  917. $removeEmptyBlock : _({'p':1,'div':1}),
  918. //在table元素里的元素列表
  919. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  920. //不转换的标签
  921. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  922. html: U,
  923. head: T,
  924. style: N,
  925. script: N,
  926. body: P,
  927. base: {},
  928. link: {},
  929. meta: {},
  930. title: N,
  931. col : {},
  932. tr : _({td:1,th:1}),
  933. img : {},
  934. embed: {},
  935. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  936. noscript : P,
  937. td : P,
  938. br : {},
  939. th : P,
  940. center : P,
  941. kbd : L,
  942. button : X( I, E ),
  943. basefont : {},
  944. h5 : L,
  945. h4 : L,
  946. samp : L,
  947. h6 : L,
  948. ol : Q,
  949. h1 : L,
  950. h3 : L,
  951. option : N,
  952. h2 : L,
  953. form : X( A, D, E, I ),
  954. select : _({optgroup:1,option:1}),
  955. font : L,
  956. ins : L,
  957. menu : Q,
  958. abbr : L,
  959. label : L,
  960. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  961. code : L,
  962. tfoot : M,
  963. cite : L,
  964. li : P,
  965. input : {},
  966. iframe : P,
  967. strong : L,
  968. textarea : N,
  969. noframes : P,
  970. big : L,
  971. small : L,
  972. //trace:
  973. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  974. hr : L,
  975. dt : L,
  976. sub : L,
  977. optgroup : _({option:1}),
  978. param : {},
  979. bdo : L,
  980. 'var' : L,
  981. div : P,
  982. object : O,
  983. sup : L,
  984. dd : P,
  985. strike : L,
  986. area : {},
  987. dir : Q,
  988. map : X( _({area:1,form:1,p:1}), A, F, E ),
  989. applet : O,
  990. dl : _({dt:1,dd:1}),
  991. del : L,
  992. isindex : {},
  993. fieldset : X( _({legend:1}), K ),
  994. thead : M,
  995. ul : Q,
  996. acronym : L,
  997. b : L,
  998. a : X( _({a:1}), J ),
  999. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1000. caption : L,
  1001. i : L,
  1002. u : L,
  1003. tbody : M,
  1004. s : L,
  1005. address : X( D, I ),
  1006. tt : L,
  1007. legend : L,
  1008. q : L,
  1009. pre : X( G, C ),
  1010. p : X(_({'a':1}),L),
  1011. em :L,
  1012. dfn : L
  1013. });
  1014. })();
  1015. /**
  1016. * @file
  1017. * @name UE.dom.domUtils
  1018. * @short DomUtils
  1019. * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js
  1020. * @desc UEditor封装的底层dom操作库
  1021. */
  1022. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1023. var tmpNode = startFromChild && node[start],
  1024. parent;
  1025. !tmpNode && (tmpNode = node[ltr]);
  1026. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1027. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1028. return null;
  1029. }
  1030. tmpNode = parent[ltr];
  1031. }
  1032. if (tmpNode && fn && !fn(tmpNode)) {
  1033. return getDomNode(tmpNode, start, ltr, false, fn);
  1034. }
  1035. return tmpNode;
  1036. }
  1037. var attrFix = ie && browser.version < 9 ? {
  1038. tabindex:"tabIndex",
  1039. readonly:"readOnly",
  1040. "for":"htmlFor",
  1041. "class":"className",
  1042. maxlength:"maxLength",
  1043. cellspacing:"cellSpacing",
  1044. cellpadding:"cellPadding",
  1045. rowspan:"rowSpan",
  1046. colspan:"colSpan",
  1047. usemap:"useMap",
  1048. frameborder:"frameBorder"
  1049. } : {
  1050. tabindex:"tabIndex",
  1051. readonly:"readOnly"
  1052. },
  1053. styleBlock = utils.listToMap([
  1054. '-webkit-box', '-moz-box', 'block' ,
  1055. 'list-item' , 'table' , 'table-row-group' ,
  1056. 'table-header-group', 'table-footer-group' ,
  1057. 'table-row' , 'table-column-group' , 'table-column' ,
  1058. 'table-cell' , 'table-caption'
  1059. ]);
  1060. var domUtils = dom.domUtils = {
  1061. //节点常量
  1062. NODE_ELEMENT:1,
  1063. NODE_DOCUMENT:9,
  1064. NODE_TEXT:3,
  1065. NODE_COMMENT:8,
  1066. NODE_DOCUMENT_FRAGMENT:11,
  1067. //位置关系
  1068. POSITION_IDENTICAL:0,
  1069. POSITION_DISCONNECTED:1,
  1070. POSITION_FOLLOWING:2,
  1071. POSITION_PRECEDING:4,
  1072. POSITION_IS_CONTAINED:8,
  1073. POSITION_CONTAINS:16,
  1074. //ie6使用其他的会有一段空白出现
  1075. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1076. //-------------------------Node部分--------------------------------
  1077. keys:{
  1078. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1079. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1080. 37:1, 38:1, 39:1, 40:1,
  1081. 13:1 /*enter*/
  1082. },
  1083. /**
  1084. * 获取节点A相对于节点B的位置关系
  1085. * @name getPosition
  1086. * @grammar UE.dom.domUtils.getPosition(nodeA,nodeB) => Number
  1087. * @example
  1088. * switch (returnValue) {
  1089. * case 0: //相等,同一节点
  1090. * case 1: //无关,节点不相连
  1091. * case 2: //跟随,即节点A头部位于节点B头部的后面
  1092. * case 4: //前置,即节点A头部位于节点B头部的前面
  1093. * case 8: //被包含,即节点A被节点B包含
  1094. * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。
  1095. * case 16://包含,即节点A包含节点B
  1096. * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况
  1097. * }
  1098. */
  1099. getPosition:function (nodeA, nodeB) {
  1100. // 如果两个节点是同一个节点
  1101. if (nodeA === nodeB) {
  1102. // domUtils.POSITION_IDENTICAL
  1103. return 0;
  1104. }
  1105. var node,
  1106. parentsA = [nodeA],
  1107. parentsB = [nodeB];
  1108. node = nodeA;
  1109. while (node = node.parentNode) {
  1110. // 如果nodeB是nodeA的祖先节点
  1111. if (node === nodeB) {
  1112. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1113. return 10;
  1114. }
  1115. parentsA.push(node);
  1116. }
  1117. node = nodeB;
  1118. while (node = node.parentNode) {
  1119. // 如果nodeA是nodeB的祖先节点
  1120. if (node === nodeA) {
  1121. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1122. return 20;
  1123. }
  1124. parentsB.push(node);
  1125. }
  1126. parentsA.reverse();
  1127. parentsB.reverse();
  1128. if (parentsA[0] !== parentsB[0]) {
  1129. // domUtils.POSITION_DISCONNECTED
  1130. return 1;
  1131. }
  1132. var i = -1;
  1133. while (i++, parentsA[i] === parentsB[i]) {
  1134. }
  1135. nodeA = parentsA[i];
  1136. nodeB = parentsB[i];
  1137. while (nodeA = nodeA.nextSibling) {
  1138. if (nodeA === nodeB) {
  1139. // domUtils.POSITION_PRECEDING
  1140. return 4
  1141. }
  1142. }
  1143. // domUtils.POSITION_FOLLOWING
  1144. return 2;
  1145. },
  1146. /**
  1147. * 返回节点node在父节点中的索引位置
  1148. * @name getNodeIndex
  1149. * @grammar UE.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始
  1150. */
  1151. getNodeIndex:function (node, ignoreTextNode) {
  1152. var preNode = node,
  1153. i = 0;
  1154. while (preNode = preNode.previousSibling) {
  1155. if (ignoreTextNode && preNode.nodeType == 3) {
  1156. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1157. i++;
  1158. }
  1159. continue;
  1160. }
  1161. i++;
  1162. }
  1163. return i;
  1164. },
  1165. /**
  1166. * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含
  1167. * @name inDoc
  1168. * @grammar UE.dom.domUtils.inDoc(node,doc) => true|false
  1169. */
  1170. inDoc:function (node, doc) {
  1171. return domUtils.getPosition(node, doc) == 10;
  1172. },
  1173. /**
  1174. * 查找node节点的祖先节点
  1175. * @name findParent
  1176. * @grammar UE.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点
  1177. * @grammar UE.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回
  1178. * @grammar UE.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身
  1179. */
  1180. findParent:function (node, filterFn, includeSelf) {
  1181. if (node && !domUtils.isBody(node)) {
  1182. node = includeSelf ? node : node.parentNode;
  1183. while (node) {
  1184. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1185. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1186. }
  1187. node = node.parentNode;
  1188. }
  1189. }
  1190. return null;
  1191. },
  1192. /**
  1193. * 通过tagName查找node节点的祖先节点
  1194. * @name findParentByTagName
  1195. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写
  1196. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身
  1197. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点
  1198. */
  1199. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1200. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1201. return domUtils.findParent(node, function (node) {
  1202. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1203. }, includeSelf);
  1204. },
  1205. /**
  1206. * 查找节点node的祖先节点集合
  1207. * @name findParents
  1208. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1209. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1210. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1211. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1212. */
  1213. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1214. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1215. while (node = domUtils.findParent(node, filterFn)) {
  1216. parents.push(node);
  1217. }
  1218. return closerFirst ? parents : parents.reverse();
  1219. },
  1220. /**
  1221. * 在节点node后面插入新节点newNode
  1222. * @name insertAfter
  1223. * @grammar UE.dom.domUtils.insertAfter(node,newNode) => newNode
  1224. */
  1225. insertAfter:function (node, newNode) {
  1226. return node.parentNode.insertBefore(newNode, node.nextSibling);
  1227. },
  1228. /**
  1229. * 删除节点node,并根据keepChildren指定是否保留子节点
  1230. * @name remove
  1231. * @grammar UE.dom.domUtils.remove(node) => node
  1232. * @grammar UE.dom.domUtils.remove(node,keepChildren) => node
  1233. */
  1234. remove:function (node, keepChildren) {
  1235. var parent = node.parentNode,
  1236. child;
  1237. if (parent) {
  1238. if (keepChildren && node.hasChildNodes()) {
  1239. while (child = node.firstChild) {
  1240. parent.insertBefore(child, node);
  1241. }
  1242. }
  1243. parent.removeChild(node);
  1244. }
  1245. return node;
  1246. },
  1247. /**
  1248. * 取得node节点在dom树上的下一个节点,即多叉树遍历
  1249. * @name getNextDomNode
  1250. * @grammar UE.dom.domUtils.getNextDomNode(node) => Element
  1251. * @example
  1252. */
  1253. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  1254. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  1255. },
  1256. /**
  1257. * 检测节点node是否属于bookmark节点
  1258. * @name isBookmarkNode
  1259. * @grammar UE.dom.domUtils.isBookmarkNode(node) => true|false
  1260. */
  1261. isBookmarkNode:function (node) {
  1262. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  1263. },
  1264. /**
  1265. * 获取节点node所在的window对象
  1266. * @name getWindow
  1267. * @grammar UE.dom.domUtils.getWindow(node) => window对象
  1268. */
  1269. getWindow:function (node) {
  1270. var doc = node.ownerDocument || node;
  1271. return doc.defaultView || doc.parentWindow;
  1272. },
  1273. /**
  1274. * 得到nodeA与nodeB公共的祖先节点
  1275. * @name getCommonAncestor
  1276. * @grammar UE.dom.domUtils.getCommonAncestor(nodeA,nodeB) => Element
  1277. */
  1278. getCommonAncestor:function (nodeA, nodeB) {
  1279. if (nodeA === nodeB)
  1280. return nodeA;
  1281. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  1282. while (parent = parent.parentNode) {
  1283. if (parent === nodeB) {
  1284. return parent;
  1285. }
  1286. parentsA.push(parent);
  1287. }
  1288. parent = nodeB;
  1289. while (parent = parent.parentNode) {
  1290. if (parent === nodeA)
  1291. return parent;
  1292. parentsB.push(parent);
  1293. }
  1294. parentsA.reverse();
  1295. parentsB.reverse();
  1296. while (i++, parentsA[i] === parentsB[i]) {
  1297. }
  1298. return i == 0 ? null : parentsA[i - 1];
  1299. },
  1300. /**
  1301. * 清除node节点左右兄弟为空的inline节点
  1302. * @name clearEmptySibling
  1303. * @grammar UE.dom.domUtils.clearEmptySibling(node)
  1304. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  1305. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  1306. * @example
  1307. * <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b>
  1308. */
  1309. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  1310. function clear(next, dir) {
  1311. var tmpNode;
  1312. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  1313. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  1314. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  1315. tmpNode = next[dir];
  1316. domUtils.remove(next);
  1317. next = tmpNode;
  1318. }
  1319. }
  1320. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  1321. !ignorePre && clear(node.previousSibling, 'previousSibling');
  1322. },
  1323. /**
  1324. * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置
  1325. * @name split
  1326. * @grammar UE.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点
  1327. */
  1328. split:function (node, offset) {
  1329. var doc = node.ownerDocument;
  1330. if (browser.ie && offset == node.nodeValue.length) {
  1331. var next = doc.createTextNode('');
  1332. return domUtils.insertAfter(node, next);
  1333. }
  1334. var retval = node.splitText(offset);
  1335. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  1336. if (browser.ie8) {
  1337. var tmpNode = doc.createTextNode('');
  1338. domUtils.insertAfter(retval, tmpNode);
  1339. domUtils.remove(tmpNode);
  1340. }
  1341. return retval;
  1342. },
  1343. /**
  1344. * 检测节点node是否为空节点(包括空格、换行、占位符等字符)
  1345. * @name isWhitespace
  1346. * @grammar UE.dom.domUtils.isWhitespace(node) => true|false
  1347. */
  1348. isWhitespace:function (node) {
  1349. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  1350. },
  1351. /**
  1352. * 获取元素element相对于viewport的位置坐标
  1353. * @name getXY
  1354. * @grammar UE.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top}
  1355. */
  1356. getXY:function (element) {
  1357. var x = 0, y = 0;
  1358. while (element.offsetParent) {
  1359. y += element.offsetTop;
  1360. x += element.offsetLeft;
  1361. element = element.offsetParent;
  1362. }
  1363. return { 'x':x, 'y':y};
  1364. },
  1365. /**
  1366. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  1367. * @name on
  1368. * @grammar UE.dom.domUtils.on(element,type,handler) //type支持数组传入
  1369. * @example
  1370. * UE.dom.domUtils.on(document.body,"click",function(e){
  1371. * //e为事件对象,this为被点击元素对戏那个
  1372. * })
  1373. * @example
  1374. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  1375. * //evt为事件对象,this为被点击元素对象
  1376. * })
  1377. */
  1378. on:function (element, type, handler) {
  1379. var types = utils.isArray(type) ? type : [type],
  1380. k = types.length;
  1381. if (k) while (k--) {
  1382. type = types[k];
  1383. if (element.addEventListener) {
  1384. element.addEventListener(type, handler, false);
  1385. } else {
  1386. if (!handler._d) {
  1387. handler._d = {
  1388. els : []
  1389. };
  1390. }
  1391. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  1392. if (!handler._d[key] || index == -1) {
  1393. if(index == -1){
  1394. handler._d.els.push(element);
  1395. }
  1396. if(!handler._d[key]){
  1397. handler._d[key] = function (evt) {
  1398. return handler.call(evt.srcElement, evt || window.event);
  1399. };
  1400. }
  1401. element.attachEvent('on' + type, handler._d[key]);
  1402. }
  1403. }
  1404. }
  1405. element = null;
  1406. },
  1407. /**
  1408. * 解除原生DOM事件绑定
  1409. * @name un
  1410. * @grammar UE.dom.donUtils.un(element,type,handler) //参见<code><a href="#on">on</a></code>
  1411. */
  1412. un:function (element, type, handler) {
  1413. var types = utils.isArray(type) ? type : [type],
  1414. k = types.length;
  1415. if (k) while (k--) {
  1416. type = types[k];
  1417. if (element.removeEventListener) {
  1418. element.removeEventListener(type, handler, false);
  1419. } else {
  1420. var key = type + handler.toString();
  1421. try{
  1422. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  1423. }catch(e){}
  1424. if (handler._d && handler._d[key]) {
  1425. var index = utils.indexOf(handler._d.els,element);
  1426. if(index!=-1){
  1427. handler._d.els.splice(index,1);
  1428. }
  1429. handler._d.els.length == 0 && delete handler._d[key];
  1430. }
  1431. }
  1432. }
  1433. },
  1434. /**
  1435. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  1436. * @name isSameElement
  1437. * @grammar UE.dom.domUtils.isSameElement(nodeA,nodeB) => true|false
  1438. * @example
  1439. * <span style="font-size:12px">ssss</span> and <span style="font-size:12px">bbbbb</span> => true
  1440. * <span style="font-size:13px">ssss</span> and <span style="font-size:12px">bbbbb</span> => false
  1441. */
  1442. isSameElement:function (nodeA, nodeB) {
  1443. if (nodeA.tagName != nodeB.tagName) {
  1444. return false;
  1445. }
  1446. var thisAttrs = nodeA.attributes,
  1447. otherAttrs = nodeB.attributes;
  1448. if (!ie && thisAttrs.length != otherAttrs.length) {
  1449. return false;
  1450. }
  1451. var attrA, attrB, al = 0, bl = 0;
  1452. for (var i = 0; attrA = thisAttrs[i++];) {
  1453. if (attrA.nodeName == 'style') {
  1454. if (attrA.specified) {
  1455. al++;
  1456. }
  1457. if (domUtils.isSameStyle(nodeA, nodeB)) {
  1458. continue;
  1459. } else {
  1460. return false;
  1461. }
  1462. }
  1463. if (ie) {
  1464. if (attrA.specified) {
  1465. al++;
  1466. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  1467. } else {
  1468. continue;
  1469. }
  1470. } else {
  1471. attrB = nodeB.attributes[attrA.nodeName];
  1472. }
  1473. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  1474. return false;
  1475. }
  1476. }
  1477. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  1478. if (ie) {
  1479. for (i = 0; attrB = otherAttrs[i++];) {
  1480. if (attrB.specified) {
  1481. bl++;
  1482. }
  1483. }
  1484. if (al != bl) {
  1485. return false;
  1486. }
  1487. }
  1488. return true;
  1489. },
  1490. /**
  1491. * 判断节点nodeA与节点nodeB的元素属性是否一致
  1492. * @name isSameStyle
  1493. * @grammar UE.dom.domUtils.isSameStyle(nodeA,nodeB) => true|false
  1494. */
  1495. isSameStyle:function (nodeA, nodeB) {
  1496. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  1497. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  1498. if (browser.opera) {
  1499. styleA = nodeA.style;
  1500. styleB = nodeB.style;
  1501. if (styleA.length != styleB.length)
  1502. return false;
  1503. for (var p in styleA) {
  1504. if (/^(\d+|csstext)$/i.test(p)) {
  1505. continue;
  1506. }
  1507. if (styleA[p] != styleB[p]) {
  1508. return false;
  1509. }
  1510. }
  1511. return true;
  1512. }
  1513. if (!styleA || !styleB) {
  1514. return styleA == styleB;
  1515. }
  1516. styleA = styleA.split(';');
  1517. styleB = styleB.split(';');
  1518. if (styleA.length != styleB.length) {
  1519. return false;
  1520. }
  1521. for (var i = 0, ci; ci = styleA[i++];) {
  1522. if (utils.indexOf(styleB, ci) == -1) {
  1523. return false;
  1524. }
  1525. }
  1526. return true;
  1527. },
  1528. /**
  1529. * 检查节点node是否为块元素
  1530. * @name isBlockElm
  1531. * @grammar UE.dom.domUtils.isBlockElm(node) => true|false
  1532. */
  1533. isBlockElm:function (node) {
  1534. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  1535. },
  1536. /**
  1537. * 检测node节点是否为body节点
  1538. * @name isBody
  1539. * @grammar UE.dom.domUtils.isBody(node) => true|false
  1540. */
  1541. isBody:function (node) {
  1542. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  1543. },
  1544. /**
  1545. * 以node节点为中心,将该节点的指定祖先节点parent拆分成2块
  1546. * @name breakParent
  1547. * @grammar UE.dom.domUtils.breakParent(node,parent) => node
  1548. * @desc
  1549. * <code type="html"><b>ooo</b>是node节点
  1550. * <p>xxxx<b>ooo</b>xxx</p> ==> <p>xxx</p><b>ooo</b><p>xxx</p>
  1551. * <p>xxxxx<span>xxxx<b>ooo</b>xxxxxx</span></p> => <p>xxxxx<span>xxxx</span></p><b>ooo</b><p><span>xxxxxx</span></p></code>
  1552. */
  1553. breakParent:function (node, parent) {
  1554. var tmpNode,
  1555. parentClone = node,
  1556. clone = node,
  1557. leftNodes,
  1558. rightNodes;
  1559. do {
  1560. parentClone = parentClone.parentNode;
  1561. if (leftNodes) {
  1562. tmpNode = parentClone.cloneNode(false);
  1563. tmpNode.appendChild(leftNodes);
  1564. leftNodes = tmpNode;
  1565. tmpNode = parentClone.cloneNode(false);
  1566. tmpNode.appendChild(rightNodes);
  1567. rightNodes = tmpNode;
  1568. } else {
  1569. leftNodes = parentClone.cloneNode(false);
  1570. rightNodes = leftNodes.cloneNode(false);
  1571. }
  1572. while (tmpNode = clone.previousSibling) {
  1573. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  1574. }
  1575. while (tmpNode = clone.nextSibling) {
  1576. rightNodes.appendChild(tmpNode);
  1577. }
  1578. clone = parentClone;
  1579. } while (parent !== parentClone);
  1580. tmpNode = parent.parentNode;
  1581. tmpNode.insertBefore(leftNodes, parent);
  1582. tmpNode.insertBefore(rightNodes, parent);
  1583. tmpNode.insertBefore(node, rightNodes);
  1584. domUtils.remove(parent);
  1585. return node;
  1586. },
  1587. /**
  1588. * 检查节点node是否是空inline节点
  1589. * @name isEmptyInlineElement
  1590. * @grammar UE.dom.domUtils.isEmptyInlineElement(node) => 1|0
  1591. * @example
  1592. * <b><i></i></b> => 1
  1593. * <b><i></i><u></u></b> => 1
  1594. * <b></b> => 1
  1595. * <b>xx<i></i></b> => 0
  1596. */
  1597. isEmptyInlineElement:function (node) {
  1598. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  1599. return 0;
  1600. }
  1601. node = node.firstChild;
  1602. while (node) {
  1603. //如果是创建的bookmark就跳过
  1604. if (domUtils.isBookmarkNode(node)) {
  1605. return 0;
  1606. }
  1607. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  1608. node.nodeType == 3 && !domUtils.isWhitespace(node)
  1609. ) {
  1610. return 0;
  1611. }
  1612. node = node.nextSibling;
  1613. }
  1614. return 1;
  1615. },
  1616. /**
  1617. * 删除node节点下的左右空白文本子节点
  1618. * @name trimWhiteTextNode
  1619. * @grammar UE.dom.domUtils.trimWhiteTextNode(node)
  1620. */
  1621. trimWhiteTextNode:function (node) {
  1622. function remove(dir) {
  1623. var child;
  1624. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  1625. node.removeChild(child);
  1626. }
  1627. }
  1628. remove('firstChild');
  1629. remove('lastChild');
  1630. },
  1631. /**
  1632. * 合并node节点下相同的子节点
  1633. * @name mergeChild
  1634. * @desc
  1635. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  1636. * @example
  1637. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  1638. * ==> UE.dom.domUtils.mergeChild(node,'span')
  1639. * <p><span style="font-size:12px;">xxaaxx</span></p>
  1640. */
  1641. mergeChild:function (node, tagName, attrs) {
  1642. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  1643. for (var i = 0, ci; ci = list[i++];) {
  1644. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  1645. continue;
  1646. }
  1647. //span单独处理
  1648. if (ci.tagName.toLowerCase() == 'span') {
  1649. if (node === ci.parentNode) {
  1650. domUtils.trimWhiteTextNode(node);
  1651. if (node.childNodes.length == 1) {
  1652. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  1653. domUtils.remove(ci, true);
  1654. continue;
  1655. }
  1656. }
  1657. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  1658. if (attrs) {
  1659. var style = attrs.style;
  1660. if (style) {
  1661. style = style.split(';');
  1662. for (var j = 0, s; s = style[j++];) {
  1663. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  1664. }
  1665. }
  1666. }
  1667. if (domUtils.isSameStyle(ci, node)) {
  1668. domUtils.remove(ci, true);
  1669. }
  1670. continue;
  1671. }
  1672. if (domUtils.isSameElement(node, ci)) {
  1673. domUtils.remove(ci, true);
  1674. }
  1675. }
  1676. },
  1677. /**
  1678. * 原生方法getElementsByTagName的封装
  1679. * @name getElementsByTagName
  1680. * @grammar UE.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组
  1681. */
  1682. getElementsByTagName:function (node, name,filter) {
  1683. if(filter && utils.isString(filter)){
  1684. var className = filter;
  1685. filter = function(node){return domUtils.hasClass(node,className)}
  1686. }
  1687. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  1688. var arr = [];
  1689. for(var n = 0,ni;ni=name[n++];){
  1690. var list = node.getElementsByTagName(ni);
  1691. for (var i = 0, ci; ci = list[i++];) {
  1692. if(!filter || filter(ci))
  1693. arr.push(ci);
  1694. }
  1695. }
  1696. return arr;
  1697. },
  1698. /**
  1699. * 将节点node合并到父节点上
  1700. * @name mergeToParent
  1701. * @grammar UE.dom.domUtils.mergeToParent(node)
  1702. * @example
  1703. * <span style="color:#fff"><span style="font-size:12px">xxx</span></span> ==> <span style="color:#fff;font-size:12px">xxx</span>
  1704. */
  1705. mergeToParent:function (node) {
  1706. var parent = node.parentNode;
  1707. while (parent && dtd.$removeEmpty[parent.tagName]) {
  1708. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  1709. domUtils.trimWhiteTextNode(parent);
  1710. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  1711. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  1712. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  1713. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  1714. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  1715. parent = parent.parentNode;
  1716. continue;
  1717. } else {
  1718. parent.style.cssText += ";" + node.style.cssText;
  1719. //trace:952 a标签要保持下划线
  1720. if (parent.tagName == 'A') {
  1721. parent.style.textDecoration = 'underline';
  1722. }
  1723. }
  1724. }
  1725. if (parent.tagName != 'A') {
  1726. parent === node.parentNode && domUtils.remove(node, true);
  1727. break;
  1728. }
  1729. }
  1730. parent = parent.parentNode;
  1731. }
  1732. },
  1733. /**
  1734. * 合并节点node的左右兄弟节点
  1735. * @name mergeSibling
  1736. * @grammar UE.dom.domUtils.mergeSibling(node)
  1737. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre) //ignorePre指定是否忽略左兄弟
  1738. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre,ignoreNext) //ignoreNext指定是否忽略右兄弟
  1739. * @example
  1740. * <b>xxxx</b><b>ooo</b><b>xxxx</b> ==> <b>xxxxoooxxxx</b>
  1741. */
  1742. mergeSibling:function (node, ignorePre, ignoreNext) {
  1743. function merge(rtl, start, node) {
  1744. var next;
  1745. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  1746. while (next.firstChild) {
  1747. if (start == 'firstChild') {
  1748. node.insertBefore(next.lastChild, node.firstChild);
  1749. } else {
  1750. node.appendChild(next.firstChild);
  1751. }
  1752. }
  1753. domUtils.remove(next);
  1754. }
  1755. }
  1756. !ignorePre && merge('previousSibling', 'firstChild', node);
  1757. !ignoreNext && merge('nextSibling', 'lastChild', node);
  1758. },
  1759. /**
  1760. * 设置节点node及其子节点不会被选中
  1761. * @name unSelectable
  1762. * @grammar UE.dom.domUtils.unSelectable(node)
  1763. */
  1764. unSelectable:ie || browser.opera ? function (node) {
  1765. //for ie9
  1766. node.onselectstart = function () {
  1767. return false;
  1768. };
  1769. node.onclick = node.onkeyup = node.onkeydown = function () {
  1770. return false;
  1771. };
  1772. node.unselectable = 'on';
  1773. node.setAttribute("unselectable", "on");
  1774. for (var i = 0, ci; ci = node.all[i++];) {
  1775. switch (ci.tagName.toLowerCase()) {
  1776. case 'iframe' :
  1777. case 'textarea' :
  1778. case 'input' :
  1779. case 'select' :
  1780. break;
  1781. default :
  1782. ci.unselectable = 'on';
  1783. node.setAttribute("unselectable", "on");
  1784. }
  1785. }
  1786. } : function (node) {
  1787. node.style.MozUserSelect =
  1788. node.style.webkitUserSelect =
  1789. node.style.KhtmlUserSelect = 'none';
  1790. },
  1791. /**
  1792. * 删除节点node上的属性attrNames,attrNames为属性名称数组
  1793. * @name removeAttributes
  1794. * @grammar UE.dom.domUtils.removeAttributes(node,attrNames)
  1795. * @example
  1796. * //Before remove
  1797. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  1798. * //Remove
  1799. * UE.dom.domUtils.removeAttributes(node,["id","name"]);
  1800. * //After remove
  1801. * <span style="font-size:14px;">xxxxx</span>
  1802. */
  1803. removeAttributes:function (node, attrNames) {
  1804. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  1805. for (var i = 0, ci; ci = attrNames[i++];) {
  1806. ci = attrFix[ci] || ci;
  1807. switch (ci) {
  1808. case 'className':
  1809. node[ci] = '';
  1810. break;
  1811. case 'style':
  1812. node.style.cssText = '';
  1813. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  1814. }
  1815. node.removeAttribute(ci);
  1816. }
  1817. },
  1818. /**
  1819. * 在doc下创建一个标签名为tag,属性为attrs的元素
  1820. * @name createElement
  1821. * @grammar UE.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点
  1822. */
  1823. createElement:function (doc, tag, attrs) {
  1824. return domUtils.setAttributes(doc.createElement(tag), attrs)
  1825. },
  1826. /**
  1827. * 为节点node添加属性attrs,attrs为属性键值对
  1828. * @name setAttributes
  1829. * @grammar UE.dom.domUtils.setAttributes(node,attrs) => node
  1830. */
  1831. setAttributes:function (node, attrs) {
  1832. for (var attr in attrs) {
  1833. if(attrs.hasOwnProperty(attr)){
  1834. var value = attrs[attr];
  1835. switch (attr) {
  1836. case 'class':
  1837. //ie下要这样赋值,setAttribute不起作用
  1838. node.className = value;
  1839. break;
  1840. case 'style' :
  1841. node.style.cssText = node.style.cssText + ";" + value;
  1842. break;
  1843. case 'innerHTML':
  1844. node[attr] = value;
  1845. break;
  1846. case 'value':
  1847. node.value = value;
  1848. break;
  1849. default:
  1850. node.setAttribute(attrFix[attr] || attr, value);
  1851. }
  1852. }
  1853. }
  1854. return node;
  1855. },
  1856. /**
  1857. * 获取元素element的计算样式
  1858. * @name getComputedStyle
  1859. * @grammar UE.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值
  1860. * @example
  1861. * getComputedStyle(document.body,"font-size") => "15px"
  1862. * getComputedStyle(form,"color") => "#ffccdd"
  1863. */
  1864. getComputedStyle:function (element, styleName) {
  1865. //一下的属性单独处理
  1866. var pros = 'width height top left';
  1867. if(pros.indexOf(styleName) > -1){
  1868. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  1869. }
  1870. //忽略文本节点
  1871. if (element.nodeType == 3) {
  1872. element = element.parentNode;
  1873. }
  1874. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  1875. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  1876. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  1877. var span = element.ownerDocument.createElement('span');
  1878. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  1879. span.innerHTML = '.';
  1880. element.appendChild(span);
  1881. var result = span.offsetHeight;
  1882. element.removeChild(span);
  1883. span = null;
  1884. return result + 'px';
  1885. }
  1886. try {
  1887. var value = domUtils.getStyle(element, styleName) ||
  1888. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  1889. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  1890. } catch (e) {
  1891. return "";
  1892. }
  1893. return utils.transUnitToPx(utils.fixColor(styleName, value));
  1894. },
  1895. /**
  1896. * 在元素element上删除classNames,支持同时删除多个
  1897. * @name removeClasses
  1898. * @grammar UE.dom.domUtils.removeClasses(element,classNames)
  1899. * @example
  1900. * //执行方法前的dom结构
  1901. * <span class="test1 test2 test3">xxx</span>
  1902. * //执行方法
  1903. * UE.dom.domUtils.removeClasses(element,["test1","test3"])
  1904. * //执行方法后的dom结构
  1905. * <span class="test2">xxx</span>
  1906. */
  1907. removeClasses:function (elm, classNames) {
  1908. classNames = utils.isArray(classNames) ? classNames :
  1909. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1910. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1911. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  1912. }
  1913. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  1914. if(cls){
  1915. elm.className = cls;
  1916. }else{
  1917. domUtils.removeAttributes(elm,['class']);
  1918. }
  1919. },
  1920. /**
  1921. * 在元素element上增加一个样式类className,支持以空格分开的多个类名
  1922. * 如果相同的类名将不会添加
  1923. * @name addClass
  1924. * @grammar UE.dom.domUtils.addClass(element,classNames)
  1925. */
  1926. addClass:function (elm, classNames) {
  1927. if(!elm)return;
  1928. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1929. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1930. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  1931. elm.className += ' ' + ci;
  1932. }
  1933. }
  1934. },
  1935. /**
  1936. * 判断元素element是否包含样式类名className,支持以空格分开的多个类名,多个类名顺序不同也可以比较
  1937. * @name hasClass
  1938. * @grammar UE.dom.domUtils.hasClass(element,className) =>true|false
  1939. */
  1940. hasClass:function (element, className) {
  1941. if(utils.isRegExp(className)){
  1942. return className.test(element.className)
  1943. }
  1944. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  1945. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  1946. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  1947. return false;
  1948. }
  1949. }
  1950. return i - 1 == className.length;
  1951. },
  1952. /**
  1953. * 阻止事件默认行为
  1954. * @param {Event} evt 需要组织的事件对象
  1955. */
  1956. preventDefault:function (evt) {
  1957. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  1958. },
  1959. /**
  1960. * 删除元素element的样式
  1961. * @grammar UE.dom.domUtils.removeStyle(element,name) 删除的样式名称
  1962. */
  1963. removeStyle:function (element, name) {
  1964. if(browser.ie ){
  1965. //针对color先单独处理一下
  1966. if(name == 'color'){
  1967. name = '(^|;)' + name;
  1968. }
  1969. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  1970. }else{
  1971. if (element.style.removeProperty) {
  1972. element.style.removeProperty (name);
  1973. }else {
  1974. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  1975. }
  1976. }
  1977. if (!element.style.cssText) {
  1978. domUtils.removeAttributes(element, ['style']);
  1979. }
  1980. },
  1981. /**
  1982. * 获取元素element的某个样式值
  1983. * @name getStyle
  1984. * @grammar UE.dom.domUtils.getStyle(element,name) => String
  1985. */
  1986. getStyle:function (element, name) {
  1987. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  1988. return utils.fixColor(name, value);
  1989. },
  1990. /**
  1991. * 为元素element设置样式属性值
  1992. * @name setStyle
  1993. * @grammar UE.dom.domUtils.setStyle(element,name,value)
  1994. */
  1995. setStyle:function (element, name, value) {
  1996. element.style[utils.cssStyleToDomStyle(name)] = value;
  1997. if(!utils.trim(element.style.cssText)){
  1998. this.removeAttributes(element,'style')
  1999. }
  2000. },
  2001. /**
  2002. * 为元素element设置样式属性值
  2003. * @name setStyles
  2004. * @grammar UE.dom.domUtils.setStyle(element,styles) //styles为样式键值对
  2005. */
  2006. setStyles:function (element, styles) {
  2007. for (var name in styles) {
  2008. if (styles.hasOwnProperty(name)) {
  2009. domUtils.setStyle(element, name, styles[name]);
  2010. }
  2011. }
  2012. },
  2013. /**
  2014. * 删除_moz_dirty属性
  2015. * @function
  2016. */
  2017. removeDirtyAttr:function (node) {
  2018. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  2019. ci.removeAttribute('_moz_dirty');
  2020. }
  2021. node.removeAttribute('_moz_dirty');
  2022. },
  2023. /**
  2024. * 返回子节点的数量
  2025. * @function
  2026. * @param {Node} node 父节点
  2027. * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量
  2028. * @return {Number} 符合条件子节点的数量
  2029. */
  2030. getChildCount:function (node, fn) {
  2031. var count = 0, first = node.firstChild;
  2032. fn = fn || function () {
  2033. return 1;
  2034. };
  2035. while (first) {
  2036. if (fn(first)) {
  2037. count++;
  2038. }
  2039. first = first.nextSibling;
  2040. }
  2041. return count;
  2042. },
  2043. /**
  2044. * 判断是否为空节点
  2045. * @function
  2046. * @param {Node} node 节点
  2047. * @return {Boolean} 是否为空节点
  2048. */
  2049. isEmptyNode:function (node) {
  2050. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  2051. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  2052. }) == 0
  2053. },
  2054. /**
  2055. * 清空节点所有的className
  2056. * @function
  2057. * @param {Array} nodes 节点数组
  2058. */
  2059. clearSelectedArr:function (nodes) {
  2060. var node;
  2061. while (node = nodes.pop()) {
  2062. domUtils.removeAttributes(node, ['class']);
  2063. }
  2064. },
  2065. /**
  2066. * 将显示区域滚动到显示节点的位置
  2067. * @function
  2068. * @param {Node} node 节点
  2069. * @param {window} win window对象
  2070. * @param {Number} offsetTop 距离上方的偏移量
  2071. */
  2072. scrollToView:function (node, win, offsetTop) {
  2073. var getViewPaneSize = function () {
  2074. var doc = win.document,
  2075. mode = doc.compatMode == 'CSS1Compat';
  2076. return {
  2077. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  2078. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  2079. };
  2080. },
  2081. getScrollPosition = function (win) {
  2082. if ('pageXOffset' in win) {
  2083. return {
  2084. x:win.pageXOffset || 0,
  2085. y:win.pageYOffset || 0
  2086. };
  2087. }
  2088. else {
  2089. var doc = win.document;
  2090. return {
  2091. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  2092. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  2093. };
  2094. }
  2095. };
  2096. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  2097. offset += (node.offsetHeight || 0);
  2098. var elementPosition = domUtils.getXY(node);
  2099. offset += elementPosition.y;
  2100. var currentScroll = getScrollPosition(win).y;
  2101. // offset += 50;
  2102. if (offset > currentScroll || offset < currentScroll - winHeight) {
  2103. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  2104. }
  2105. },
  2106. /**
  2107. * 判断节点是否为br
  2108. * @function
  2109. * @param {Node} node 节点
  2110. */
  2111. isBr:function (node) {
  2112. return node.nodeType == 1 && node.tagName == 'BR';
  2113. },
  2114. isFillChar:function (node,isInStart) {
  2115. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  2116. },
  2117. isStartInblock:function (range) {
  2118. var tmpRange = range.cloneRange(),
  2119. flag = 0,
  2120. start = tmpRange.startContainer,
  2121. tmp;
  2122. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  2123. start = start.childNodes[tmpRange.startOffset];
  2124. var pre = start.previousSibling;
  2125. while(pre && domUtils.isFillChar(pre)){
  2126. start = pre;
  2127. pre = pre.previousSibling;
  2128. }
  2129. }
  2130. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  2131. tmpRange.setStartBefore(start);
  2132. start = tmpRange.startContainer;
  2133. }
  2134. while (start && domUtils.isFillChar(start)) {
  2135. tmp = start;
  2136. start = start.previousSibling
  2137. }
  2138. if (tmp) {
  2139. tmpRange.setStartBefore(tmp);
  2140. start = tmpRange.startContainer;
  2141. }
  2142. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  2143. tmpRange.setStart(start, 0).collapse(true);
  2144. }
  2145. while (!tmpRange.startOffset) {
  2146. start = tmpRange.startContainer;
  2147. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  2148. flag = 1;
  2149. break;
  2150. }
  2151. var pre = tmpRange.startContainer.previousSibling,
  2152. tmpNode;
  2153. if (!pre) {
  2154. tmpRange.setStartBefore(tmpRange.startContainer);
  2155. } else {
  2156. while (pre && domUtils.isFillChar(pre)) {
  2157. tmpNode = pre;
  2158. pre = pre.previousSibling;
  2159. }
  2160. if (tmpNode) {
  2161. tmpRange.setStartBefore(tmpNode);
  2162. } else {
  2163. tmpRange.setStartBefore(tmpRange.startContainer);
  2164. }
  2165. }
  2166. }
  2167. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  2168. },
  2169. isEmptyBlock:function (node,reg) {
  2170. if(node.nodeType != 1)
  2171. return 0;
  2172. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  2173. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  2174. return 0;
  2175. }
  2176. for (var n in dtd.$isNotEmpty) {
  2177. if (node.getElementsByTagName(n).length) {
  2178. return 0;
  2179. }
  2180. }
  2181. return 1;
  2182. },
  2183. setViewportOffset:function (element, offset) {
  2184. var left = parseInt(element.style.left) | 0;
  2185. var top = parseInt(element.style.top) | 0;
  2186. var rect = element.getBoundingClientRect();
  2187. var offsetLeft = offset.left - rect.left;
  2188. var offsetTop = offset.top - rect.top;
  2189. if (offsetLeft) {
  2190. element.style.left = left + offsetLeft + 'px';
  2191. }
  2192. if (offsetTop) {
  2193. element.style.top = top + offsetTop + 'px';
  2194. }
  2195. },
  2196. fillNode:function (doc, node) {
  2197. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  2198. node.innerHTML = '';
  2199. node.appendChild(tmpNode);
  2200. },
  2201. moveChild:function (src, tag, dir) {
  2202. while (src.firstChild) {
  2203. if (dir && tag.firstChild) {
  2204. tag.insertBefore(src.lastChild, tag.firstChild);
  2205. } else {
  2206. tag.appendChild(src.firstChild);
  2207. }
  2208. }
  2209. },
  2210. //判断是否有额外属性
  2211. hasNoAttributes:function (node) {
  2212. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  2213. },
  2214. //判断是否是编辑器自定义的参数
  2215. isCustomeNode:function (node) {
  2216. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  2217. },
  2218. isTagNode:function (node, tagName) {
  2219. return node.nodeType == 1 && new RegExp('^' + node.tagName + '$','i').test(tagName)
  2220. },
  2221. /**
  2222. * 对于nodelist用filter进行过滤
  2223. * @name filterNodeList
  2224. * @since 1.2.4+
  2225. * @grammar UE.dom.domUtils.filterNodeList(nodelist,filter,onlyFirst) => 节点
  2226. * @example
  2227. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'div p') //返回第一个是div或者p的节点
  2228. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),function(n){return n.getAttribute('src')})
  2229. * //返回第一个带src属性的节点
  2230. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'i',true) //返回数组,里边都是i节点
  2231. */
  2232. filterNodeList : function(nodelist,filter,forAll){
  2233. var results = [];
  2234. if(!utils .isFunction(filter)){
  2235. var str = filter;
  2236. filter = function(n){
  2237. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  2238. };
  2239. }
  2240. utils.each(nodelist,function(n){
  2241. filter(n) && results.push(n)
  2242. });
  2243. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  2244. },
  2245. isInNodeEndBoundary : function (rng,node){
  2246. var start = rng.startContainer;
  2247. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  2248. return 0;
  2249. }
  2250. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  2251. return 0;
  2252. }
  2253. while(start !== node){
  2254. if(start.nextSibling){
  2255. return 0
  2256. };
  2257. start = start.parentNode;
  2258. }
  2259. return 1;
  2260. },
  2261. isBoundaryNode : function (node,dir){
  2262. var tmp;
  2263. while(!domUtils.isBody(node)){
  2264. tmp = node;
  2265. node = node.parentNode;
  2266. if(tmp !== node[dir]){
  2267. return false;
  2268. }
  2269. }
  2270. return true;
  2271. }
  2272. };
  2273. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  2274. ///import editor.js
  2275. ///import core/utils.js
  2276. ///import core/browser.js
  2277. ///import core/dom/dom.js
  2278. ///import core/dom/dtd.js
  2279. ///import core/dom/domUtils.js
  2280. /**
  2281. * @file
  2282. * @name UE.dom.Range
  2283. * @anthor zhanyi
  2284. * @short Range
  2285. * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js
  2286. * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性
  2287. */
  2288. (function () {
  2289. var guid = 0,
  2290. fillChar = domUtils.fillChar,
  2291. fillData;
  2292. /**
  2293. * 更新range的collapse状态
  2294. * @param {Range} range range对象
  2295. */
  2296. function updateCollapse(range) {
  2297. range.collapsed =
  2298. range.startContainer && range.endContainer &&
  2299. range.startContainer === range.endContainer &&
  2300. range.startOffset == range.endOffset;
  2301. }
  2302. function selectOneNode(rng){
  2303. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  2304. }
  2305. function setEndPoint(toStart, node, offset, range) {
  2306. //如果node是自闭合标签要处理
  2307. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  2308. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  2309. node = node.parentNode;
  2310. }
  2311. if (toStart) {
  2312. range.startContainer = node;
  2313. range.startOffset = offset;
  2314. if (!range.endContainer) {
  2315. range.collapse(true);
  2316. }
  2317. } else {
  2318. range.endContainer = node;
  2319. range.endOffset = offset;
  2320. if (!range.startContainer) {
  2321. range.collapse(false);
  2322. }
  2323. }
  2324. updateCollapse(range);
  2325. return range;
  2326. }
  2327. function execContentsAction(range, action) {
  2328. //调整边界
  2329. //range.includeBookmark();
  2330. var start = range.startContainer,
  2331. end = range.endContainer,
  2332. startOffset = range.startOffset,
  2333. endOffset = range.endOffset,
  2334. doc = range.document,
  2335. frag = doc.createDocumentFragment(),
  2336. tmpStart, tmpEnd;
  2337. if (start.nodeType == 1) {
  2338. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  2339. }
  2340. if (end.nodeType == 1) {
  2341. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  2342. }
  2343. if (start === end && start.nodeType == 3) {
  2344. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  2345. //is not clone
  2346. if (action) {
  2347. start.deleteData(startOffset, endOffset - startOffset);
  2348. range.collapse(true);
  2349. }
  2350. return frag;
  2351. }
  2352. var current, currentLevel, clone = frag,
  2353. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  2354. for (var i = 0; startParents[i] == endParents[i];) {
  2355. i++;
  2356. }
  2357. for (var j = i, si; si = startParents[j]; j++) {
  2358. current = si.nextSibling;
  2359. if (si == start) {
  2360. if (!tmpStart) {
  2361. if (range.startContainer.nodeType == 3) {
  2362. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  2363. //is not clone
  2364. if (action) {
  2365. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  2366. }
  2367. } else {
  2368. clone.appendChild(!action ? start.cloneNode(true) : start);
  2369. }
  2370. }
  2371. } else {
  2372. currentLevel = si.cloneNode(false);
  2373. clone.appendChild(currentLevel);
  2374. }
  2375. while (current) {
  2376. if (current === end || current === endParents[j]) {
  2377. break;
  2378. }
  2379. si = current.nextSibling;
  2380. clone.appendChild(!action ? current.cloneNode(true) : current);
  2381. current = si;
  2382. }
  2383. clone = currentLevel;
  2384. }
  2385. clone = frag;
  2386. if (!startParents[i]) {
  2387. clone.appendChild(startParents[i - 1].cloneNode(false));
  2388. clone = clone.firstChild;
  2389. }
  2390. for (var j = i, ei; ei = endParents[j]; j++) {
  2391. current = ei.previousSibling;
  2392. if (ei == end) {
  2393. if (!tmpEnd && range.endContainer.nodeType == 3) {
  2394. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  2395. //is not clone
  2396. if (action) {
  2397. end.deleteData(0, endOffset);
  2398. }
  2399. }
  2400. } else {
  2401. currentLevel = ei.cloneNode(false);
  2402. clone.appendChild(currentLevel);
  2403. }
  2404. //如果两端同级,右边第一次已经被开始做了
  2405. if (j != i || !startParents[i]) {
  2406. while (current) {
  2407. if (current === start) {
  2408. break;
  2409. }
  2410. ei = current.previousSibling;
  2411. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  2412. current = ei;
  2413. }
  2414. }
  2415. clone = currentLevel;
  2416. }
  2417. if (action) {
  2418. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  2419. }
  2420. tmpStart && domUtils.remove(tmpStart);
  2421. tmpEnd && domUtils.remove(tmpEnd);
  2422. return frag;
  2423. }
  2424. /**
  2425. * @name Range
  2426. * @grammar new UE.dom.Range(document) => Range 实例
  2427. * @desc 创建一个跟document绑定的空的Range实例
  2428. * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode
  2429. * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2430. * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode
  2431. * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2432. * - ***document*** 跟range关联的document对象
  2433. * - ***collapsed*** 是否是闭合状态
  2434. */
  2435. var Range = dom.Range = function (document) {
  2436. var me = this;
  2437. me.startContainer =
  2438. me.startOffset =
  2439. me.endContainer =
  2440. me.endOffset = null;
  2441. me.document = document;
  2442. me.collapsed = true;
  2443. };
  2444. /**
  2445. * 删除fillData
  2446. * @param doc
  2447. * @param excludeNode
  2448. */
  2449. function removeFillData(doc, excludeNode) {
  2450. try {
  2451. if (fillData && domUtils.inDoc(fillData, doc)) {
  2452. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  2453. var tmpNode = fillData.parentNode;
  2454. domUtils.remove(fillData);
  2455. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  2456. //safari的contains有bug
  2457. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  2458. ) {
  2459. fillData = tmpNode.parentNode;
  2460. domUtils.remove(tmpNode);
  2461. tmpNode = fillData;
  2462. }
  2463. } else {
  2464. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  2465. }
  2466. }
  2467. } catch (e) {
  2468. }
  2469. }
  2470. /**
  2471. *
  2472. * @param node
  2473. * @param dir
  2474. */
  2475. function mergeSibling(node, dir) {
  2476. var tmpNode;
  2477. node = node[dir];
  2478. while (node && domUtils.isFillChar(node)) {
  2479. tmpNode = node[dir];
  2480. domUtils.remove(node);
  2481. node = tmpNode;
  2482. }
  2483. }
  2484. Range.prototype = {
  2485. /**
  2486. * @name cloneContents
  2487. * @grammar range.cloneContents() => DocumentFragment
  2488. * @desc 克隆选中的内容到一个fragment里,如果选区是空的将返回null
  2489. */
  2490. cloneContents:function () {
  2491. return this.collapsed ? null : execContentsAction(this, 0);
  2492. },
  2493. /**
  2494. * @name deleteContents
  2495. * @grammar range.deleteContents() => Range
  2496. * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态
  2497. * @example
  2498. * DOM Element :
  2499. * <b>x<i>x[x<i>xx]x</b>
  2500. * //执行方法后
  2501. * <b>x<i>x<i>|x</b>
  2502. * 注意range改变了
  2503. * range.startContainer => b
  2504. * range.startOffset => 2
  2505. * range.endContainer => b
  2506. * range.endOffset => 2
  2507. * range.collapsed => true
  2508. */
  2509. deleteContents:function () {
  2510. var txt;
  2511. if (!this.collapsed) {
  2512. execContentsAction(this, 1);
  2513. }
  2514. if (browser.webkit) {
  2515. txt = this.startContainer;
  2516. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  2517. this.setStartBefore(txt).collapse(true);
  2518. domUtils.remove(txt);
  2519. }
  2520. }
  2521. return this;
  2522. },
  2523. /**
  2524. * @name extractContents
  2525. * @grammar range.extractContents() => DocumentFragment
  2526. * @desc 将当前的内容放到一个fragment里并返回这个fragment,这时的range已经变成了闭合状态
  2527. * @example
  2528. * DOM Element :
  2529. * <b>x<i>x[x<i>xx]x</b>
  2530. * //执行方法后
  2531. * 返回的fragment里的 dom结构是
  2532. * <i>x<i>xx
  2533. * dom树上的结构是
  2534. * <b>x<i>x<i>|x</b>
  2535. * 注意range改变了
  2536. * range.startContainer => b
  2537. * range.startOffset => 2
  2538. * range.endContainer => b
  2539. * range.endOffset => 2
  2540. * range.collapsed => true
  2541. */
  2542. extractContents:function () {
  2543. return this.collapsed ? null : execContentsAction(this, 2);
  2544. },
  2545. /**
  2546. * @name setStart
  2547. * @grammar range.setStart(node,offset) => Range
  2548. * @desc 设置range的开始位置位于node节点内,偏移量为offset
  2549. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2550. */
  2551. setStart:function (node, offset) {
  2552. return setEndPoint(true, node, offset, this);
  2553. },
  2554. /**
  2555. * 设置range的结束位置位于node节点,偏移量为offset
  2556. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2557. * @name setEnd
  2558. * @grammar range.setEnd(node,offset) => Range
  2559. */
  2560. setEnd:function (node, offset) {
  2561. return setEndPoint(false, node, offset, this);
  2562. },
  2563. /**
  2564. * 将Range开始位置设置到node节点之后
  2565. * @name setStartAfter
  2566. * @grammar range.setStartAfter(node) => Range
  2567. * @example
  2568. * <b>xx<i>x|x</i>x</b>
  2569. * 执行setStartAfter(i)后
  2570. * range.startContainer =>b
  2571. * range.startOffset =>2
  2572. */
  2573. setStartAfter:function (node) {
  2574. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2575. },
  2576. /**
  2577. * 将Range开始位置设置到node节点之前
  2578. * @name setStartBefore
  2579. * @grammar range.setStartBefore(node) => Range
  2580. * @example
  2581. * <b>xx<i>x|x</i>x</b>
  2582. * 执行setStartBefore(i)后
  2583. * range.startContainer =>b
  2584. * range.startOffset =>1
  2585. */
  2586. setStartBefore:function (node) {
  2587. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  2588. },
  2589. /**
  2590. * 将Range结束位置设置到node节点之后
  2591. * @name setEndAfter
  2592. * @grammar range.setEndAfter(node) => Range
  2593. * @example
  2594. * <b>xx<i>x|x</i>x</b>
  2595. * setEndAfter(i)后
  2596. * range.endContainer =>b
  2597. * range.endtOffset =>2
  2598. */
  2599. setEndAfter:function (node) {
  2600. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2601. },
  2602. /**
  2603. * 将Range结束位置设置到node节点之前
  2604. * @name setEndBefore
  2605. * @grammar range.setEndBefore(node) => Range
  2606. * @example
  2607. * <b>xx<i>x|x</i>x</b>
  2608. * 执行setEndBefore(i)后
  2609. * range.endContainer =>b
  2610. * range.endtOffset =>1
  2611. */
  2612. setEndBefore:function (node) {
  2613. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  2614. },
  2615. /**
  2616. * 将Range开始位置设置到node节点内的开始位置
  2617. * @name setStartAtFirst
  2618. * @grammar range.setStartAtFirst(node) => Range
  2619. */
  2620. setStartAtFirst:function (node) {
  2621. return this.setStart(node, 0);
  2622. },
  2623. /**
  2624. * 将Range开始位置设置到node节点内的结束位置
  2625. * @name setStartAtLast
  2626. * @grammar range.setStartAtLast(node) => Range
  2627. */
  2628. setStartAtLast:function (node) {
  2629. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2630. },
  2631. /**
  2632. * 将Range结束位置设置到node节点内的开始位置
  2633. * @name setEndAtFirst
  2634. * @grammar range.setEndAtFirst(node) => Range
  2635. */
  2636. setEndAtFirst:function (node) {
  2637. return this.setEnd(node, 0);
  2638. },
  2639. /**
  2640. * 将Range结束位置设置到node节点内的结束位置
  2641. * @name setEndAtLast
  2642. * @grammar range.setEndAtLast(node) => Range
  2643. */
  2644. setEndAtLast:function (node) {
  2645. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2646. },
  2647. /**
  2648. * 选中完整的指定节点,并返回包含该节点的range
  2649. * @name selectNode
  2650. * @grammar range.selectNode(node) => Range
  2651. */
  2652. selectNode:function (node) {
  2653. return this.setStartBefore(node).setEndAfter(node);
  2654. },
  2655. /**
  2656. * 选中node内部的所有节点,并返回对应的range
  2657. * @name selectNodeContents
  2658. * @grammar range.selectNodeContents(node) => Range
  2659. * @example
  2660. * <b>xx[x<i>xxx</i>]xxx</b>
  2661. * 执行后
  2662. * <b>[xxx<i>xxx</i>xxx]</b>
  2663. * range.startContainer =>b
  2664. * range.startOffset =>0
  2665. * range.endContainer =>b
  2666. * range.endOffset =>3
  2667. */
  2668. selectNodeContents:function (node) {
  2669. return this.setStart(node, 0).setEndAtLast(node);
  2670. },
  2671. /**
  2672. * 克隆一个新的range对象
  2673. * @name cloneRange
  2674. * @grammar range.cloneRange() => Range
  2675. */
  2676. cloneRange:function () {
  2677. var me = this;
  2678. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  2679. },
  2680. /**
  2681. * 让选区闭合到尾部,若toStart为真,则闭合到头部
  2682. * @name collapse
  2683. * @grammar range.collapse() => Range
  2684. * @grammar range.collapse(true) => Range //闭合选区到头部
  2685. */
  2686. collapse:function (toStart) {
  2687. var me = this;
  2688. if (toStart) {
  2689. me.endContainer = me.startContainer;
  2690. me.endOffset = me.startOffset;
  2691. } else {
  2692. me.startContainer = me.endContainer;
  2693. me.startOffset = me.endOffset;
  2694. }
  2695. me.collapsed = true;
  2696. return me;
  2697. },
  2698. /**
  2699. * 调整range的边界,使其"收缩"到最小的位置
  2700. * @name shrinkBoundary
  2701. * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code>
  2702. * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置
  2703. * @example
  2704. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2705. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i>
  2706. * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b>
  2707. */
  2708. shrinkBoundary:function (ignoreEnd) {
  2709. var me = this, child,
  2710. collapsed = me.collapsed;
  2711. function check(node){
  2712. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  2713. }
  2714. while (me.startContainer.nodeType == 1 //是element
  2715. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  2716. && check(child)) {
  2717. me.setStart(child, 0);
  2718. }
  2719. if (collapsed) {
  2720. return me.collapse(true);
  2721. }
  2722. if (!ignoreEnd) {
  2723. while (me.endContainer.nodeType == 1//是element
  2724. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  2725. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  2726. && check(child)) {
  2727. me.setEnd(child, child.childNodes.length);
  2728. }
  2729. }
  2730. return me;
  2731. },
  2732. /**
  2733. * 获取当前range所在位置的公共祖先节点,当前range位置可以位于文本节点内,也可以包含整个元素节点,也可以位于两个节点之间
  2734. * @name getCommonAncestor
  2735. * @grammar range.getCommonAncestor([includeSelf, ignoreTextNode]) => Element
  2736. * @example
  2737. * <b>xx[xx<i>xx]x</i>xxx</b> ==>getCommonAncestor() ==> b
  2738. * <b>[<img/>]</b>
  2739. * range.startContainer ==> b
  2740. * range.startOffset ==> 0
  2741. * range.endContainer ==> b
  2742. * range.endOffset ==> 1
  2743. * range.getCommonAncestor() ==> b
  2744. * range.getCommonAncestor(true) ==> img
  2745. * <b>xxx|xx</b>
  2746. * range.startContainer ==> textNode
  2747. * range.startOffset ==> 3
  2748. * range.endContainer ==> textNode
  2749. * range.endOffset ==> 3
  2750. * range.getCommonAncestor() ==> textNode
  2751. * range.getCommonAncestor(null,true) ==> b
  2752. */
  2753. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  2754. var me = this,
  2755. start = me.startContainer,
  2756. end = me.endContainer;
  2757. if (start === end) {
  2758. if (includeSelf && selectOneNode(this)) {
  2759. start = start.childNodes[me.startOffset];
  2760. if(start.nodeType == 1)
  2761. return start;
  2762. }
  2763. //只有在上来就相等的情况下才会出现是文本的情况
  2764. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  2765. }
  2766. return domUtils.getCommonAncestor(start, end);
  2767. },
  2768. /**
  2769. * 调整边界容器,如果是textNode,就调整到elementNode上
  2770. * @name trimBoundary
  2771. * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界
  2772. * @example
  2773. * DOM Element :
  2774. * <b>|xxx</b>
  2775. * startContainer = xxx; startOffset = 0
  2776. * //执行后本方法后
  2777. * startContainer = <b>; startOffset = 0
  2778. * @example
  2779. * Dom Element :
  2780. * <b>xx|x</b>
  2781. * startContainer = xxx; startOffset = 2
  2782. * //执行本方法后,xxx被实实在在地切分成两个TextNode
  2783. * startContainer = <b>; startOffset = 1
  2784. */
  2785. trimBoundary:function (ignoreEnd) {
  2786. this.txtToElmBoundary();
  2787. var start = this.startContainer,
  2788. offset = this.startOffset,
  2789. collapsed = this.collapsed,
  2790. end = this.endContainer;
  2791. if (start.nodeType == 3) {
  2792. if (offset == 0) {
  2793. this.setStartBefore(start);
  2794. } else {
  2795. if (offset >= start.nodeValue.length) {
  2796. this.setStartAfter(start);
  2797. } else {
  2798. var textNode = domUtils.split(start, offset);
  2799. //跟新结束边界
  2800. if (start === end) {
  2801. this.setEnd(textNode, this.endOffset - offset);
  2802. } else if (start.parentNode === end) {
  2803. this.endOffset += 1;
  2804. }
  2805. this.setStartBefore(textNode);
  2806. }
  2807. }
  2808. if (collapsed) {
  2809. return this.collapse(true);
  2810. }
  2811. }
  2812. if (!ignoreEnd) {
  2813. offset = this.endOffset;
  2814. end = this.endContainer;
  2815. if (end.nodeType == 3) {
  2816. if (offset == 0) {
  2817. this.setEndBefore(end);
  2818. } else {
  2819. offset < end.nodeValue.length && domUtils.split(end, offset);
  2820. this.setEndAfter(end);
  2821. }
  2822. }
  2823. }
  2824. return this;
  2825. },
  2826. /**
  2827. * 如果选区在文本的边界上,就扩展选区到文本的父节点上
  2828. * @name txtToElmBoundary
  2829. * @example
  2830. * Dom Element :
  2831. * <b> |xxx</b>
  2832. * startContainer = xxx; startOffset = 0
  2833. * //本方法执行后
  2834. * startContainer = <b>; startOffset = 0
  2835. * @example
  2836. * Dom Element :
  2837. * <b> xxx| </b>
  2838. * startContainer = xxx; startOffset = 3
  2839. * //本方法执行后
  2840. * startContainer = <b>; startOffset = 1
  2841. */
  2842. txtToElmBoundary:function (ignoreCollapsed) {
  2843. function adjust(r, c) {
  2844. var container = r[c + 'Container'],
  2845. offset = r[c + 'Offset'];
  2846. if (container.nodeType == 3) {
  2847. if (!offset) {
  2848. r['set' + c.replace(/(\w)/, function (a) {
  2849. return a.toUpperCase();
  2850. }) + 'Before'](container);
  2851. } else if (offset >= container.nodeValue.length) {
  2852. r['set' + c.replace(/(\w)/, function (a) {
  2853. return a.toUpperCase();
  2854. }) + 'After' ](container);
  2855. }
  2856. }
  2857. }
  2858. if (ignoreCollapsed || !this.collapsed) {
  2859. adjust(this, 'start');
  2860. adjust(this, 'end');
  2861. }
  2862. return this;
  2863. },
  2864. /**
  2865. * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边
  2866. * @name insertNode
  2867. * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment
  2868. * @example
  2869. * Range :
  2870. * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2871. * 待插入Node :
  2872. * <p>ssss</p>
  2873. * 执行本方法后的Range :
  2874. * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2875. */
  2876. insertNode:function (node) {
  2877. var first = node, length = 1;
  2878. if (node.nodeType == 11) {
  2879. first = node.firstChild;
  2880. length = node.childNodes.length;
  2881. }
  2882. this.trimBoundary(true);
  2883. var start = this.startContainer,
  2884. offset = this.startOffset;
  2885. var nextNode = start.childNodes[ offset ];
  2886. if (nextNode) {
  2887. start.insertBefore(node, nextNode);
  2888. } else {
  2889. start.appendChild(node);
  2890. }
  2891. if (first.parentNode === this.endContainer) {
  2892. this.endOffset = this.endOffset + length;
  2893. }
  2894. return this.setStartBefore(first);
  2895. },
  2896. /**
  2897. * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾
  2898. * @name setCursor
  2899. * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾
  2900. */
  2901. setCursor:function (toEnd, noFillData) {
  2902. return this.collapse(!toEnd).select(noFillData);
  2903. },
  2904. /**
  2905. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  2906. * @name createBookmark
  2907. * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用
  2908. */
  2909. createBookmark:function (serialize, same) {
  2910. var endNode,
  2911. startNode = this.document.createElement('span');
  2912. startNode.style.cssText = 'display:none;line-height:0px;';
  2913. startNode.appendChild(this.document.createTextNode('\u200D'));
  2914. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  2915. if (!this.collapsed) {
  2916. endNode = startNode.cloneNode(true);
  2917. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  2918. }
  2919. this.insertNode(startNode);
  2920. if (endNode) {
  2921. this.collapse().insertNode(endNode).setEndBefore(endNode);
  2922. }
  2923. this.setStartAfter(startNode);
  2924. return {
  2925. start:serialize ? startNode.id : startNode,
  2926. end:endNode ? serialize ? endNode.id : endNode : null,
  2927. id:serialize
  2928. }
  2929. },
  2930. /**
  2931. * 移动边界到书签位置,并删除插入的书签节点
  2932. * @name moveToBookmark
  2933. * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的
  2934. */
  2935. moveToBookmark:function (bookmark) {
  2936. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  2937. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  2938. this.setStartBefore(start);
  2939. domUtils.remove(start);
  2940. if (end) {
  2941. this.setEndBefore(end);
  2942. domUtils.remove(end);
  2943. } else {
  2944. this.collapse(true);
  2945. }
  2946. return this;
  2947. },
  2948. /**
  2949. * 调整range的边界,使其"放大"到最近的父block节点
  2950. * @name enlarge
  2951. * @grammar range.enlarge() => Range
  2952. * @example
  2953. * <p><span>xxx</span><b>x[x</b>xxxxx]</p><p>xxx</p> ==> [<p><span>xxx</span><b>xx</b>xxxxx</p>]<p>xxx</p>
  2954. */
  2955. enlarge:function (toBlock, stopFn) {
  2956. var isBody = domUtils.isBody,
  2957. pre, node, tmp = this.document.createTextNode('');
  2958. if (toBlock) {
  2959. node = this.startContainer;
  2960. if (node.nodeType == 1) {
  2961. if (node.childNodes[this.startOffset]) {
  2962. pre = node = node.childNodes[this.startOffset]
  2963. } else {
  2964. node.appendChild(tmp);
  2965. pre = node = tmp;
  2966. }
  2967. } else {
  2968. pre = node;
  2969. }
  2970. while (1) {
  2971. if (domUtils.isBlockElm(node)) {
  2972. node = pre;
  2973. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  2974. node = pre;
  2975. }
  2976. this.setStartBefore(node);
  2977. break;
  2978. }
  2979. pre = node;
  2980. node = node.parentNode;
  2981. }
  2982. node = this.endContainer;
  2983. if (node.nodeType == 1) {
  2984. if (pre = node.childNodes[this.endOffset]) {
  2985. node.insertBefore(tmp, pre);
  2986. } else {
  2987. node.appendChild(tmp);
  2988. }
  2989. pre = node = tmp;
  2990. } else {
  2991. pre = node;
  2992. }
  2993. while (1) {
  2994. if (domUtils.isBlockElm(node)) {
  2995. node = pre;
  2996. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  2997. node = pre;
  2998. }
  2999. this.setEndAfter(node);
  3000. break;
  3001. }
  3002. pre = node;
  3003. node = node.parentNode;
  3004. }
  3005. if (tmp.parentNode === this.endContainer) {
  3006. this.endOffset--;
  3007. }
  3008. domUtils.remove(tmp);
  3009. }
  3010. // 扩展边界到最大
  3011. if (!this.collapsed) {
  3012. while (this.startOffset == 0) {
  3013. if (stopFn && stopFn(this.startContainer)) {
  3014. break;
  3015. }
  3016. if (isBody(this.startContainer)) {
  3017. break;
  3018. }
  3019. this.setStartBefore(this.startContainer);
  3020. }
  3021. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  3022. if (stopFn && stopFn(this.endContainer)) {
  3023. break;
  3024. }
  3025. if (isBody(this.endContainer)) {
  3026. break;
  3027. }
  3028. this.setEndAfter(this.endContainer);
  3029. }
  3030. }
  3031. return this;
  3032. },
  3033. /**
  3034. * 调整Range的边界,使其"缩小"到最合适的位置
  3035. * @name adjustmentBoundary
  3036. * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code>
  3037. * @example
  3038. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  3039. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i>
  3040. */
  3041. adjustmentBoundary:function () {
  3042. if (!this.collapsed) {
  3043. while (!domUtils.isBody(this.startContainer) &&
  3044. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  3045. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  3046. ) {
  3047. this.setStartAfter(this.startContainer);
  3048. }
  3049. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  3050. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  3051. ) {
  3052. this.setEndBefore(this.endContainer);
  3053. }
  3054. }
  3055. return this;
  3056. },
  3057. /**
  3058. * 给range选区中的内容添加给定的标签,主要用于inline标签
  3059. * @name applyInlineStyle
  3060. * @grammar range.applyInlineStyle(tagName) => Range //tagName为需要添加的样式标签名
  3061. * @grammar range.applyInlineStyle(tagName,attrs) => Range //attrs为属性json对象
  3062. * @desc
  3063. * <code type="html"><p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  3064. * <p>xx[dd<strong>yyyy</strong>]x</p> ==> range.applyInlineStyle("strong") ==> <p>xx[<strong>ddyyyy</strong>]x</p>
  3065. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong",{"style":"font-size:12px"}) ==> <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p></code>
  3066. */
  3067. applyInlineStyle:function (tagName, attrs, list) {
  3068. if (this.collapsed)return this;
  3069. this.trimBoundary().enlarge(false,
  3070. function (node) {
  3071. return node.nodeType == 1 && domUtils.isBlockElm(node)
  3072. }).adjustmentBoundary();
  3073. var bookmark = this.createBookmark(),
  3074. end = bookmark.end,
  3075. filterFn = function (node) {
  3076. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  3077. },
  3078. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  3079. node,
  3080. pre,
  3081. range = this.cloneRange();
  3082. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  3083. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  3084. range.setStartBefore(current);
  3085. node = current;
  3086. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  3087. pre = node;
  3088. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  3089. return dtd[tagName][parent.tagName];
  3090. });
  3091. }
  3092. var frag = range.setEndAfter(pre).extractContents(), elm;
  3093. if (list && list.length > 0) {
  3094. var level, top;
  3095. top = level = list[0].cloneNode(false);
  3096. for (var i = 1, ci; ci = list[i++];) {
  3097. level.appendChild(ci.cloneNode(false));
  3098. level = level.firstChild;
  3099. }
  3100. elm = level;
  3101. } else {
  3102. elm = range.document.createElement(tagName);
  3103. }
  3104. if (attrs) {
  3105. domUtils.setAttributes(elm, attrs);
  3106. }
  3107. elm.appendChild(frag);
  3108. range.insertNode(list ? top : elm);
  3109. //处理下滑线在a上的情况
  3110. var aNode;
  3111. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  3112. domUtils.setAttributes(aNode, attrs);
  3113. domUtils.remove(elm, true);
  3114. elm = aNode;
  3115. } else {
  3116. domUtils.mergeSibling(elm);
  3117. domUtils.clearEmptySibling(elm);
  3118. }
  3119. //去除子节点相同的
  3120. domUtils.mergeChild(elm, attrs);
  3121. current = domUtils.getNextDomNode(elm, false, filterFn);
  3122. domUtils.mergeToParent(elm);
  3123. if (node === end) {
  3124. break;
  3125. }
  3126. } else {
  3127. current = domUtils.getNextDomNode(current, true, filterFn);
  3128. }
  3129. }
  3130. return this.moveToBookmark(bookmark);
  3131. },
  3132. /**
  3133. * 对当前range选中的节点,去掉给定的标签节点,但标签中的内容保留,主要用于处理inline元素
  3134. * @name removeInlineStyle
  3135. * @grammar range.removeInlineStyle(tagNames) => Range //tagNames 为需要去掉的样式标签名,支持"b"或者["b","i","u"]
  3136. * @desc
  3137. * <code type="html">xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span></code>
  3138. */
  3139. removeInlineStyle:function (tagNames) {
  3140. if (this.collapsed)return this;
  3141. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  3142. this.shrinkBoundary().adjustmentBoundary();
  3143. var start = this.startContainer, end = this.endContainer;
  3144. while (1) {
  3145. if (start.nodeType == 1) {
  3146. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  3147. break;
  3148. }
  3149. if (start.tagName.toLowerCase() == 'body') {
  3150. start = null;
  3151. break;
  3152. }
  3153. }
  3154. start = start.parentNode;
  3155. }
  3156. while (1) {
  3157. if (end.nodeType == 1) {
  3158. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  3159. break;
  3160. }
  3161. if (end.tagName.toLowerCase() == 'body') {
  3162. end = null;
  3163. break;
  3164. }
  3165. }
  3166. end = end.parentNode;
  3167. }
  3168. var bookmark = this.createBookmark(),
  3169. frag,
  3170. tmpRange;
  3171. if (start) {
  3172. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  3173. frag = tmpRange.extractContents();
  3174. tmpRange.insertNode(frag);
  3175. domUtils.clearEmptySibling(start, true);
  3176. start.parentNode.insertBefore(bookmark.start, start);
  3177. }
  3178. if (end) {
  3179. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  3180. frag = tmpRange.extractContents();
  3181. tmpRange.insertNode(frag);
  3182. domUtils.clearEmptySibling(end, false, true);
  3183. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  3184. }
  3185. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  3186. return node.nodeType == 1;
  3187. }), next;
  3188. while (current && current !== bookmark.end) {
  3189. next = domUtils.getNextDomNode(current, true, function (node) {
  3190. return node.nodeType == 1;
  3191. });
  3192. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  3193. domUtils.remove(current, true);
  3194. }
  3195. current = next;
  3196. }
  3197. return this.moveToBookmark(bookmark);
  3198. },
  3199. /**
  3200. * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点
  3201. * @name getClosedNode
  3202. * @grammar range.getClosedNode() => node|null
  3203. * @example
  3204. * <b>xxxx[<img />]xxx</b>
  3205. */
  3206. getClosedNode:function () {
  3207. var node;
  3208. if (!this.collapsed) {
  3209. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  3210. if (selectOneNode(range)) {
  3211. var child = range.startContainer.childNodes[range.startOffset];
  3212. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  3213. node = child;
  3214. }
  3215. }
  3216. }
  3217. return node;
  3218. },
  3219. /**
  3220. * 根据当前range选中内容节点(在页面上表现为反白显示)
  3221. * @name select
  3222. * @grammar range.select(); => Range
  3223. */
  3224. select:browser.ie ? function (noFillData, textRange) {
  3225. var nativeRange;
  3226. if (!this.collapsed)
  3227. this.shrinkBoundary();
  3228. var node = this.getClosedNode();
  3229. if (node && !textRange) {
  3230. try {
  3231. nativeRange = this.document.body.createControlRange();
  3232. nativeRange.addElement(node);
  3233. nativeRange.select();
  3234. } catch (e) {}
  3235. return this;
  3236. }
  3237. var bookmark = this.createBookmark(),
  3238. start = bookmark.start,
  3239. end;
  3240. nativeRange = this.document.body.createTextRange();
  3241. nativeRange.moveToElementText(start);
  3242. nativeRange.moveStart('character', 1);
  3243. if (!this.collapsed) {
  3244. var nativeRangeEnd = this.document.body.createTextRange();
  3245. end = bookmark.end;
  3246. nativeRangeEnd.moveToElementText(end);
  3247. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  3248. } else {
  3249. if (!noFillData && this.startContainer.nodeType != 3) {
  3250. //使用<span>|x<span>固定住光标
  3251. var tmpText = this.document.createTextNode(fillChar),
  3252. tmp = this.document.createElement('span');
  3253. tmp.appendChild(this.document.createTextNode(fillChar));
  3254. start.parentNode.insertBefore(tmp, start);
  3255. start.parentNode.insertBefore(tmpText, start);
  3256. //当点b,i,u时,不能清除i上边的b
  3257. removeFillData(this.document, tmpText);
  3258. fillData = tmpText;
  3259. mergeSibling(tmp, 'previousSibling');
  3260. mergeSibling(start, 'nextSibling');
  3261. nativeRange.moveStart('character', -1);
  3262. nativeRange.collapse(true);
  3263. }
  3264. }
  3265. this.moveToBookmark(bookmark);
  3266. tmp && domUtils.remove(tmp);
  3267. //IE在隐藏状态下不支持range操作,catch一下
  3268. try {
  3269. nativeRange.select();
  3270. } catch (e) {
  3271. }
  3272. return this;
  3273. } : function (notInsertFillData) {
  3274. function checkOffset(rng){
  3275. function check(node,offset,dir){
  3276. if(node.nodeType == 3 && node.nodeValue.length < offset){
  3277. rng[dir + 'Offset'] = node.nodeValue.length
  3278. }
  3279. }
  3280. check(rng.startContainer,rng.startOffset,'start');
  3281. check(rng.endContainer,rng.endOffset,'end');
  3282. }
  3283. var win = domUtils.getWindow(this.document),
  3284. sel = win.getSelection(),
  3285. txtNode;
  3286. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  3287. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  3288. browser.gecko ? this.document.body.focus() : win.focus();
  3289. if (sel) {
  3290. sel.removeAllRanges();
  3291. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  3292. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  3293. if (this.collapsed && !notInsertFillData) {
  3294. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  3295. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  3296. // var tmp = this.document.createTextNode('');
  3297. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  3298. // }
  3299. //
  3300. //处理光标落在文本节点的情况
  3301. //处理以下的情况
  3302. //<b>|xxxx</b>
  3303. //<b>xxxx</b>|xxxx
  3304. //xxxx<b>|</b>
  3305. var start = this.startContainer,child = start;
  3306. if(start.nodeType == 1){
  3307. child = start.childNodes[this.startOffset];
  3308. }
  3309. if( !(start.nodeType == 3 && this.startOffset) &&
  3310. (child ?
  3311. (!child.previousSibling || child.previousSibling.nodeType != 3)
  3312. :
  3313. (!start.lastChild || start.lastChild.nodeType != 3)
  3314. )
  3315. ){
  3316. txtNode = this.document.createTextNode(fillChar);
  3317. //跟着前边走
  3318. this.insertNode(txtNode);
  3319. removeFillData(this.document, txtNode);
  3320. mergeSibling(txtNode, 'previousSibling');
  3321. mergeSibling(txtNode, 'nextSibling');
  3322. fillData = txtNode;
  3323. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  3324. }
  3325. }
  3326. var nativeRange = this.document.createRange();
  3327. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  3328. var child = this.startContainer.childNodes[this.startOffset];
  3329. if(!child){
  3330. //往前靠拢
  3331. child = this.startContainer.lastChild;
  3332. if( child && domUtils.isBr(child)){
  3333. this.setStartBefore(child).collapse(true);
  3334. }
  3335. }else{
  3336. //向后靠拢
  3337. while(child && domUtils.isBlockElm(child)){
  3338. if(child.nodeType == 1 && child.childNodes[0]){
  3339. child = child.childNodes[0]
  3340. }else{
  3341. break;
  3342. }
  3343. }
  3344. child && this.setStartBefore(child).collapse(true)
  3345. }
  3346. }
  3347. //是createAddress最后一位算的不准,现在这里进行微调
  3348. checkOffset(this);
  3349. nativeRange.setStart(this.startContainer, this.startOffset);
  3350. nativeRange.setEnd(this.endContainer, this.endOffset);
  3351. sel.addRange(nativeRange);
  3352. }
  3353. return this;
  3354. },
  3355. /**
  3356. * 滚动条跳到当然range开始的位置
  3357. * @name scrollToView
  3358. * @grammar range.scrollToView([win,offset]) => Range //针对window对象,若不指定,将以编辑区域的窗口为准,offset偏移量
  3359. */
  3360. scrollToView:function (win, offset) {
  3361. win = win ? window : domUtils.getWindow(this.document);
  3362. var me = this,
  3363. span = me.document.createElement('span');
  3364. //trace:717
  3365. span.innerHTML = '&nbsp;';
  3366. me.cloneRange().insertNode(span);
  3367. domUtils.scrollToView(span, win, offset);
  3368. domUtils.remove(span);
  3369. return me;
  3370. },
  3371. inFillChar : function(){
  3372. var start = this.startContainer;
  3373. if(this.collapsed && start.nodeType == 3
  3374. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  3375. ){
  3376. return true;
  3377. }
  3378. return false;
  3379. },
  3380. createAddress : function(ignoreEnd,ignoreTxt){
  3381. var addr = {},me = this;
  3382. function getAddress(isStart){
  3383. var node = isStart ? me.startContainer : me.endContainer;
  3384. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  3385. addrs = [];
  3386. for(var i = 0,ci;ci = parents[i++];){
  3387. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  3388. }
  3389. var firstIndex = 0;
  3390. if(ignoreTxt){
  3391. if(node.nodeType == 3){
  3392. var tmpNode = node.previousSibling;
  3393. while(tmpNode && tmpNode.nodeType == 3){
  3394. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  3395. tmpNode = tmpNode.previousSibling;
  3396. }
  3397. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  3398. }else{
  3399. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  3400. if(node){
  3401. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  3402. }else{
  3403. node = isStart ? me.startContainer : me.endContainer;
  3404. var first = node.firstChild;
  3405. while(first){
  3406. if(domUtils.isFillChar(first)){
  3407. first = first.nextSibling;
  3408. continue;
  3409. }
  3410. firstIndex++;
  3411. if(first.nodeType == 3){
  3412. while( first && first.nodeType == 3){
  3413. first = first.nextSibling;
  3414. }
  3415. }else{
  3416. first = first.nextSibling;
  3417. }
  3418. }
  3419. }
  3420. }
  3421. }else{
  3422. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  3423. }
  3424. if(firstIndex < 0){
  3425. firstIndex = 0;
  3426. }
  3427. addrs.push(firstIndex);
  3428. return addrs;
  3429. }
  3430. addr.startAddress = getAddress(true);
  3431. if(!ignoreEnd){
  3432. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  3433. }
  3434. return addr;
  3435. },
  3436. moveToAddress : function(addr,ignoreEnd){
  3437. var me = this;
  3438. function getNode(address,isStart){
  3439. var tmpNode = me.document.body,
  3440. parentNode,offset;
  3441. for(var i= 0,ci,l=address.length;i<l;i++){
  3442. ci = address[i];
  3443. parentNode = tmpNode;
  3444. tmpNode = tmpNode.childNodes[ci];
  3445. if(!tmpNode){
  3446. offset = ci;
  3447. break;
  3448. }
  3449. }
  3450. if(isStart){
  3451. if(tmpNode){
  3452. me.setStartBefore(tmpNode)
  3453. }else{
  3454. me.setStart(parentNode,offset)
  3455. }
  3456. }else{
  3457. if(tmpNode){
  3458. me.setEndBefore(tmpNode)
  3459. }else{
  3460. me.setEnd(parentNode,offset)
  3461. }
  3462. }
  3463. }
  3464. getNode(addr.startAddress,true);
  3465. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  3466. return me;
  3467. },
  3468. equals : function(rng){
  3469. for(var p in this){
  3470. if(this.hasOwnProperty(p)){
  3471. if(this[p] !== rng[p])
  3472. return false
  3473. }
  3474. }
  3475. return true;
  3476. },
  3477. traversal:function(doFn,filterFn){
  3478. if (this.collapsed)
  3479. return this;
  3480. var bookmark = this.createBookmark(),
  3481. end = bookmark.end,
  3482. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  3483. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  3484. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  3485. doFn(current);
  3486. current = tmpNode;
  3487. }
  3488. return this.moveToBookmark(bookmark);
  3489. }
  3490. };
  3491. })();
  3492. ///import editor.js
  3493. ///import core/browser.js
  3494. ///import core/dom/dom.js
  3495. ///import core/dom/dtd.js
  3496. ///import core/dom/domUtils.js
  3497. ///import core/dom/Range.js
  3498. /**
  3499. * @class baidu.editor.dom.Selection Selection类
  3500. */
  3501. (function () {
  3502. function getBoundaryInformation( range, start ) {
  3503. var getIndex = domUtils.getNodeIndex;
  3504. range = range.duplicate();
  3505. range.collapse( start );
  3506. var parent = range.parentElement();
  3507. //如果节点里没有子节点,直接退出
  3508. if ( !parent.hasChildNodes() ) {
  3509. return {container:parent, offset:0};
  3510. }
  3511. var siblings = parent.children,
  3512. child,
  3513. testRange = range.duplicate(),
  3514. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  3515. distance;
  3516. while ( startIndex <= endIndex ) {
  3517. index = Math.floor( (startIndex + endIndex) / 2 );
  3518. child = siblings[index];
  3519. testRange.moveToElementText( child );
  3520. var position = testRange.compareEndPoints( 'StartToStart', range );
  3521. if ( position > 0 ) {
  3522. endIndex = index - 1;
  3523. } else if ( position < 0 ) {
  3524. startIndex = index + 1;
  3525. } else {
  3526. //trace:1043
  3527. return {container:parent, offset:getIndex( child )};
  3528. }
  3529. }
  3530. if ( index == -1 ) {
  3531. testRange.moveToElementText( parent );
  3532. testRange.setEndPoint( 'StartToStart', range );
  3533. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3534. siblings = parent.childNodes;
  3535. if ( !distance ) {
  3536. child = siblings[siblings.length - 1];
  3537. return {container:child, offset:child.nodeValue.length};
  3538. }
  3539. var i = siblings.length;
  3540. while ( distance > 0 ){
  3541. distance -= siblings[ --i ].nodeValue.length;
  3542. }
  3543. return {container:siblings[i], offset:-distance};
  3544. }
  3545. testRange.collapse( position > 0 );
  3546. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  3547. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3548. if ( !distance ) {
  3549. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  3550. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  3551. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  3552. }
  3553. while ( distance > 0 ) {
  3554. try {
  3555. var pre = child;
  3556. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  3557. distance -= child.nodeValue.length;
  3558. } catch ( e ) {
  3559. return {container:parent, offset:getIndex( pre )};
  3560. }
  3561. }
  3562. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  3563. }
  3564. /**
  3565. * 将ieRange转换为Range对象
  3566. * @param {Range} ieRange ieRange对象
  3567. * @param {Range} range Range对象
  3568. * @return {Range} range 返回转换后的Range对象
  3569. */
  3570. function transformIERangeToRange( ieRange, range ) {
  3571. if ( ieRange.item ) {
  3572. range.selectNode( ieRange.item( 0 ) );
  3573. } else {
  3574. var bi = getBoundaryInformation( ieRange, true );
  3575. range.setStart( bi.container, bi.offset );
  3576. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  3577. bi = getBoundaryInformation( ieRange, false );
  3578. range.setEnd( bi.container, bi.offset );
  3579. }
  3580. }
  3581. return range;
  3582. }
  3583. /**
  3584. * 获得ieRange
  3585. * @param {Selection} sel Selection对象
  3586. * @return {ieRange} 得到ieRange
  3587. */
  3588. function _getIERange( sel ) {
  3589. var ieRange;
  3590. //ie下有可能报错
  3591. try {
  3592. ieRange = sel.getNative().createRange();
  3593. } catch ( e ) {
  3594. return null;
  3595. }
  3596. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  3597. if ( ( el.ownerDocument || el ) === sel.document ) {
  3598. return ieRange;
  3599. }
  3600. return null;
  3601. }
  3602. var Selection = dom.Selection = function ( doc ) {
  3603. var me = this, iframe;
  3604. me.document = doc;
  3605. if ( browser.ie9under ) {
  3606. iframe = domUtils.getWindow( doc ).frameElement;
  3607. domUtils.on( iframe, 'beforedeactivate', function () {
  3608. me._bakIERange = me.getIERange();
  3609. } );
  3610. domUtils.on( iframe, 'activate', function () {
  3611. try {
  3612. if ( !_getIERange( me ) && me._bakIERange ) {
  3613. me._bakIERange.select();
  3614. }
  3615. } catch ( ex ) {
  3616. }
  3617. me._bakIERange = null;
  3618. } );
  3619. }
  3620. iframe = doc = null;
  3621. };
  3622. Selection.prototype = {
  3623. /**
  3624. * 获取原生seleciton对象
  3625. * @public
  3626. * @function
  3627. * @name baidu.editor.dom.Selection.getNative
  3628. * @return {Selection} 获得selection对象
  3629. */
  3630. getNative:function () {
  3631. var doc = this.document;
  3632. try {
  3633. return !doc ? null : browser.ie9under ? doc.selection : domUtils.getWindow( doc ).getSelection();
  3634. } catch ( e ) {
  3635. return null;
  3636. }
  3637. },
  3638. /**
  3639. * 获得ieRange
  3640. * @public
  3641. * @function
  3642. * @name baidu.editor.dom.Selection.getIERange
  3643. * @return {ieRange} 返回ie原生的Range
  3644. */
  3645. getIERange:function () {
  3646. var ieRange = _getIERange( this );
  3647. if ( !ieRange ) {
  3648. if ( this._bakIERange ) {
  3649. return this._bakIERange;
  3650. }
  3651. }
  3652. return ieRange;
  3653. },
  3654. /**
  3655. * 缓存当前选区的range和选区的开始节点
  3656. * @public
  3657. * @function
  3658. * @name baidu.editor.dom.Selection.cache
  3659. */
  3660. cache:function () {
  3661. this.clear();
  3662. this._cachedRange = this.getRange();
  3663. this._cachedStartElement = this.getStart();
  3664. this._cachedStartElementPath = this.getStartElementPath();
  3665. },
  3666. getStartElementPath:function () {
  3667. if ( this._cachedStartElementPath ) {
  3668. return this._cachedStartElementPath;
  3669. }
  3670. var start = this.getStart();
  3671. if ( start ) {
  3672. return domUtils.findParents( start, true, null, true )
  3673. }
  3674. return [];
  3675. },
  3676. /**
  3677. * 清空缓存
  3678. * @public
  3679. * @function
  3680. * @name baidu.editor.dom.Selection.clear
  3681. */
  3682. clear:function () {
  3683. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  3684. },
  3685. /**
  3686. * 编辑器是否得到了选区
  3687. */
  3688. isFocus:function () {
  3689. try {
  3690. return browser.ie9under && _getIERange( this ) || !browser.ie9under && this.getNative().rangeCount ? true : false;
  3691. } catch ( e ) {
  3692. return false;
  3693. }
  3694. },
  3695. /**
  3696. * 获取选区对应的Range
  3697. * @public
  3698. * @function
  3699. * @name baidu.editor.dom.Selection.getRange
  3700. * @returns {baidu.editor.dom.Range} 得到Range对象
  3701. */
  3702. getRange:function () {
  3703. var me = this;
  3704. function optimze( range ) {
  3705. var child = me.document.body.firstChild,
  3706. collapsed = range.collapsed;
  3707. while ( child && child.firstChild ) {
  3708. range.setStart( child, 0 );
  3709. child = child.firstChild;
  3710. }
  3711. if ( !range.startContainer ) {
  3712. range.setStart( me.document.body, 0 )
  3713. }
  3714. if ( collapsed ) {
  3715. range.collapse( true );
  3716. }
  3717. }
  3718. if ( me._cachedRange != null ) {
  3719. return this._cachedRange;
  3720. }
  3721. var range = new baidu.editor.dom.Range( me.document );
  3722. if ( browser.ie9under ) {
  3723. var nativeRange = me.getIERange();
  3724. if ( nativeRange ) {
  3725. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  3726. try{
  3727. transformIERangeToRange( nativeRange, range );
  3728. }catch(e){
  3729. optimze( range );
  3730. }
  3731. } else {
  3732. optimze( range );
  3733. }
  3734. } else {
  3735. var sel = me.getNative();
  3736. if ( sel && sel.rangeCount ) {
  3737. var firstRange = sel.getRangeAt( 0 );
  3738. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  3739. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  3740. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  3741. optimze( range );
  3742. }
  3743. } else {
  3744. //trace:1734 有可能已经不在dom树上了,标识的节点
  3745. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  3746. return this._bakRange;
  3747. }
  3748. optimze( range );
  3749. }
  3750. }
  3751. return this._bakRange = range;
  3752. },
  3753. /**
  3754. * 获取开始元素,用于状态反射
  3755. * @public
  3756. * @function
  3757. * @name baidu.editor.dom.Selection.getStart
  3758. * @return {Element} 获得开始元素
  3759. */
  3760. getStart:function () {
  3761. if ( this._cachedStartElement ) {
  3762. return this._cachedStartElement;
  3763. }
  3764. var range = browser.ie9under ? this.getIERange() : this.getRange(),
  3765. tmpRange,
  3766. start, tmp, parent;
  3767. if ( browser.ie9under ) {
  3768. if ( !range ) {
  3769. //todo 给第一个值可能会有问题
  3770. return this.document.body.firstChild;
  3771. }
  3772. //control元素
  3773. if ( range.item ){
  3774. return range.item( 0 );
  3775. }
  3776. tmpRange = range.duplicate();
  3777. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  3778. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  3779. tmpRange.collapse( 1 );
  3780. start = tmpRange.parentElement();
  3781. parent = tmp = range.parentElement();
  3782. while ( tmp = tmp.parentNode ) {
  3783. if ( tmp == start ) {
  3784. start = parent;
  3785. break;
  3786. }
  3787. }
  3788. } else {
  3789. range.shrinkBoundary();
  3790. start = range.startContainer;
  3791. if ( start.nodeType == 1 && start.hasChildNodes() ){
  3792. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  3793. }
  3794. if ( start.nodeType == 3 ){
  3795. return start.parentNode;
  3796. }
  3797. }
  3798. return start;
  3799. },
  3800. /**
  3801. * 得到选区中的文本
  3802. * @public
  3803. * @function
  3804. * @name baidu.editor.dom.Selection.getText
  3805. * @return {String} 选区中包含的文本
  3806. */
  3807. getText:function () {
  3808. var nativeSel, nativeRange;
  3809. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  3810. nativeRange = browser.ie9under ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  3811. return browser.ie9under ? nativeRange.text : nativeRange.toString();
  3812. }
  3813. return '';
  3814. },
  3815. clearRange : function(){
  3816. this.getNative()[browser.ie9under ? 'empty' : 'removeAllRanges']();
  3817. }
  3818. };
  3819. })();
  3820. /**
  3821. * @file
  3822. * @name UE.Editor
  3823. * @short Editor
  3824. * @import editor.js,core/utils.js,core/EventBase.js,core/browser.js,core/dom/dtd.js,core/dom/domUtils.js,core/dom/Range.js,core/dom/Selection.js,plugins/serialize.js
  3825. * @desc 编辑器主类,包含编辑器提供的大部分公用接口
  3826. */
  3827. (function () {
  3828. var uid = 0, _selectionChangeTimer;
  3829. /**
  3830. * @private
  3831. * @ignore
  3832. * @param form 编辑器所在的form元素
  3833. * @param editor 编辑器实例对象
  3834. */
  3835. function setValue(form, editor) {
  3836. var textarea;
  3837. if (editor.textarea) {
  3838. if (utils.isString(editor.textarea)) {
  3839. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  3840. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  3841. textarea = ti;
  3842. break;
  3843. }
  3844. }
  3845. } else {
  3846. textarea = editor.textarea;
  3847. }
  3848. }
  3849. if (!textarea) {
  3850. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  3851. 'name': editor.options.textarea,
  3852. 'id': 'ueditor_textarea_' + editor.options.textarea,
  3853. 'style': "display:none"
  3854. }));
  3855. //不要产生多个textarea
  3856. editor.textarea = textarea;
  3857. }
  3858. textarea.value = editor.hasContents() ?
  3859. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  3860. ''
  3861. }
  3862. function loadPlugins(me){
  3863. //初始化插件
  3864. for (var pi in UE.plugins) {
  3865. UE.plugins[pi].call(me);
  3866. }
  3867. me.langIsReady = true;
  3868. me.fireEvent("langReady");
  3869. }
  3870. function checkCurLang(I18N){
  3871. for(var lang in I18N){
  3872. return lang
  3873. }
  3874. }
  3875. /**
  3876. * UEditor编辑器类
  3877. * @name Editor
  3878. * @desc 创建一个跟编辑器实例
  3879. * - ***container*** 编辑器容器对象
  3880. * - ***iframe*** 编辑区域所在的iframe对象
  3881. * - ***window*** 编辑区域所在的window
  3882. * - ***document*** 编辑区域所在的document对象
  3883. * - ***body*** 编辑区域所在的body对象
  3884. * - ***selection*** 编辑区域的选区对象
  3885. */
  3886. var Editor = UE.Editor = function (options) {
  3887. var me = this;
  3888. me.uid = uid++;
  3889. EventBase.call(me);
  3890. me.commands = {};
  3891. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  3892. me.shortcutkeys = {};
  3893. me.inputRules = [];
  3894. me.outputRules = [];
  3895. //设置默认的常用属性
  3896. me.setOpt({
  3897. isShow: true,
  3898. initialContent: '',
  3899. initialStyle:'',
  3900. autoClearinitialContent: false,
  3901. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  3902. textarea: 'editorValue',
  3903. focus: false,
  3904. focusInEnd: true,
  3905. autoClearEmptyNode: true,
  3906. fullscreen: false,
  3907. readonly: false,
  3908. zIndex: 999,
  3909. imagePopup: true,
  3910. enterTag: 'p',
  3911. customDomain: false,
  3912. lang: 'zh-cn',
  3913. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  3914. theme: 'default',
  3915. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  3916. allHtmlEnabled: false,
  3917. scaleEnabled: false,
  3918. tableNativeEditInFF: false,
  3919. autoSyncData : true
  3920. });
  3921. if(!utils.isEmptyObject(UE.I18N)){
  3922. //修改默认的语言类型
  3923. me.options.lang = checkCurLang(UE.I18N);
  3924. loadPlugins(me)
  3925. }else{
  3926. utils.loadFile(document, {
  3927. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  3928. tag: "script",
  3929. type: "text/javascript",
  3930. defer: "defer"
  3931. }, function () {
  3932. loadPlugins(me)
  3933. });
  3934. }
  3935. UE.instants['ueditorInstant' + me.uid] = me;
  3936. };
  3937. Editor.prototype = {
  3938. /**
  3939. * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。
  3940. * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。
  3941. * @name ready
  3942. * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function
  3943. * @example
  3944. * var editor = new UE.ui.Editor();
  3945. * editor.render("myEditor");
  3946. * editor.ready(function(){
  3947. * editor.setContent("欢迎使用UEditor!");
  3948. * })
  3949. */
  3950. ready: function (fn) {
  3951. var me = this;
  3952. if (fn) {
  3953. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  3954. }
  3955. },
  3956. /**
  3957. * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准
  3958. * @grammar editor.setOpt(key,value); //传入一个键、值对
  3959. * @grammar editor.setOpt({ key:value}); //传入一个json对象
  3960. */
  3961. setOpt: function (key, val) {
  3962. var obj = {};
  3963. if (utils.isString(key)) {
  3964. obj[key] = val
  3965. } else {
  3966. obj = key;
  3967. }
  3968. utils.extend(this.options, obj, true);
  3969. },
  3970. /**
  3971. * 销毁编辑器实例对象
  3972. * @name destroy
  3973. * @grammar editor.destroy();
  3974. */
  3975. destroy: function () {
  3976. var me = this;
  3977. me.fireEvent('destroy');
  3978. var container = me.container.parentNode;
  3979. var textarea = me.textarea;
  3980. if (!textarea) {
  3981. textarea = document.createElement('textarea');
  3982. container.parentNode.insertBefore(textarea, container);
  3983. } else {
  3984. textarea.style.display = ''
  3985. }
  3986. textarea.style.width = me.iframe.offsetWidth + 'px';
  3987. textarea.style.height = me.iframe.offsetHeight + 'px';
  3988. textarea.value = me.getContent();
  3989. textarea.id = me.key;
  3990. container.innerHTML = '';
  3991. domUtils.remove(container);
  3992. var key = me.key;
  3993. //trace:2004
  3994. for (var p in me) {
  3995. if (me.hasOwnProperty(p)) {
  3996. delete this[p];
  3997. }
  3998. }
  3999. UE.delEditor(key);
  4000. },
  4001. /**
  4002. * 渲染编辑器的DOM到指定容器,必须且只能调用一次
  4003. * @name render
  4004. * @grammar editor.render(containerId); //可以指定一个容器ID
  4005. * @grammar editor.render(containerDom); //也可以直接指定容器对象
  4006. */
  4007. render: function (container) {
  4008. var me = this,
  4009. options = me.options,
  4010. getStyleValue=function(attr){
  4011. return parseInt(domUtils.getComputedStyle(container,attr));
  4012. };
  4013. if (utils.isString(container)) {
  4014. container = document.getElementById(container);
  4015. }
  4016. if (container) {
  4017. if(options.initialFrameWidth){
  4018. options.minFrameWidth = options.initialFrameWidth
  4019. }else{
  4020. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  4021. }
  4022. if(options.initialFrameHeight){
  4023. options.minFrameHeight = options.initialFrameHeight
  4024. }else{
  4025. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  4026. }
  4027. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  4028. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  4029. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  4030. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  4031. container.style.zIndex = options.zIndex;
  4032. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  4033. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  4034. '<style type=\'text/css\'>' +
  4035. //设置四周的留边
  4036. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  4037. //设置默认字体和字号
  4038. //font-family不能呢随便改,在safari下fillchar会有解析问题
  4039. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  4040. //设置段落间距
  4041. 'p{margin:5px 0;}</style>' +
  4042. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  4043. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  4044. '</head><body class=\'view\' ></body>' +
  4045. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  4046. 'setTimeout(function(){window.parent.UE.instants[\'ueditorInstant' + me.uid + '\']._setup(document);},0);' +
  4047. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  4048. container.appendChild(domUtils.createElement(document, 'iframe', {
  4049. id: 'ueditor_' + me.uid,
  4050. width: "100%",
  4051. height: "100%",
  4052. frameborder: "0",
  4053. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  4054. 'document.write("' + html + '");document.close();}())'
  4055. }));
  4056. container.style.overflow = 'hidden';
  4057. //解决如果是给定的百分比,会导致高度算不对的问题
  4058. setTimeout(function(){
  4059. if( /%$/.test(options.initialFrameWidth)){
  4060. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  4061. container.style.width = options.initialFrameWidth + 'px';
  4062. }
  4063. if(/%$/.test(options.initialFrameHeight)){
  4064. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  4065. container.style.height = options.initialFrameHeight + 'px';
  4066. }
  4067. })
  4068. }
  4069. },
  4070. /**
  4071. * 编辑器初始化
  4072. * @private
  4073. * @ignore
  4074. * @param {Element} doc 编辑器Iframe中的文档对象
  4075. */
  4076. _setup: function (doc) {
  4077. var me = this,
  4078. options = me.options;
  4079. if (ie) {
  4080. doc.body.disabled = true;
  4081. doc.body.contentEditable = true;
  4082. doc.body.disabled = false;
  4083. } else {
  4084. doc.body.contentEditable = true;
  4085. }
  4086. doc.body.spellcheck = false;
  4087. me.document = doc;
  4088. me.window = doc.defaultView || doc.parentWindow;
  4089. me.iframe = me.window.frameElement;
  4090. me.body = doc.body;
  4091. me.selection = new dom.Selection(doc);
  4092. //gecko初始化就能得到range,无法判断isFocus了
  4093. var geckoSel;
  4094. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  4095. geckoSel.removeAllRanges();
  4096. }
  4097. this._initEvents();
  4098. //为form提交提供一个隐藏的textarea
  4099. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  4100. if (form.tagName == 'FORM') {
  4101. me.form = form;
  4102. if(me.options.autoSyncData){
  4103. domUtils.on(me.window,'blur',function(){
  4104. setValue(form,me);
  4105. });
  4106. }else{
  4107. domUtils.on(form, 'submit', function () {
  4108. setValue(this, me);
  4109. });
  4110. }
  4111. break;
  4112. }
  4113. }
  4114. if (options.initialContent) {
  4115. if (options.autoClearinitialContent) {
  4116. var oldExecCommand = me.execCommand;
  4117. me.execCommand = function () {
  4118. me.fireEvent('firstBeforeExecCommand');
  4119. return oldExecCommand.apply(me, arguments);
  4120. };
  4121. this._setDefaultContent(options.initialContent);
  4122. } else
  4123. this.setContent(options.initialContent, false, true);
  4124. }
  4125. //编辑器不能为空内容
  4126. if (domUtils.isEmptyNode(me.body)) {
  4127. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  4128. }
  4129. //如果要求focus, 就把光标定位到内容开始
  4130. if (options.focus) {
  4131. setTimeout(function () {
  4132. me.focus(me.options.focusInEnd);
  4133. //如果自动清除开着,就不需要做selectionchange;
  4134. !me.options.autoClearinitialContent && me._selectionChange();
  4135. }, 0);
  4136. }
  4137. if (!me.container) {
  4138. me.container = this.iframe.parentNode;
  4139. }
  4140. if (options.fullscreen && me.ui) {
  4141. me.ui.setFullScreen(true);
  4142. }
  4143. try {
  4144. me.document.execCommand('2D-position', false, false);
  4145. } catch (e) {
  4146. }
  4147. try {
  4148. me.document.execCommand('enableInlineTableEditing', false, false);
  4149. } catch (e) {
  4150. }
  4151. try {
  4152. me.document.execCommand('enableObjectResizing', false, false);
  4153. } catch (e) {
  4154. // domUtils.on(me.body,browser.ie ? 'resizestart' : 'resize', function( evt ) {
  4155. // domUtils.preventDefault(evt)
  4156. // });
  4157. }
  4158. me._bindshortcutKeys();
  4159. me.isReady = 1;
  4160. me.fireEvent('ready');
  4161. options.onready && options.onready.call(me);
  4162. if (!browser.ie9under) {
  4163. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  4164. //chrome下会出现alt+tab切换时,导致选区位置不对
  4165. if (e.type == 'blur') {
  4166. me._bakRange = me.selection.getRange();
  4167. try {
  4168. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  4169. me.selection.getNative().removeAllRanges();
  4170. } catch (e) {
  4171. me._bakNativeRange = null;
  4172. }
  4173. } else {
  4174. try {
  4175. me._bakRange && me._bakRange.select();
  4176. } catch (e) {
  4177. }
  4178. }
  4179. });
  4180. }
  4181. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  4182. if (browser.gecko && browser.version <= 10902) {
  4183. //修复ff3.6初始化进来,不能点击获得焦点
  4184. me.body.contentEditable = false;
  4185. setTimeout(function () {
  4186. me.body.contentEditable = true;
  4187. }, 100);
  4188. setInterval(function () {
  4189. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  4190. }, 100)
  4191. }
  4192. !options.isShow && me.setHide();
  4193. options.readonly && me.setDisabled();
  4194. },
  4195. /**
  4196. * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况
  4197. * @name sync
  4198. * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据
  4199. * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  4200. * @desc
  4201. * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea''
  4202. * @example
  4203. * editor.sync();
  4204. * form.sumbit(); //form变量已经指向了form元素
  4205. *
  4206. */
  4207. sync: function (formId) {
  4208. var me = this,
  4209. form = formId ? document.getElementById(formId) :
  4210. domUtils.findParent(me.iframe.parentNode, function (node) {
  4211. return node.tagName == 'FORM'
  4212. }, true);
  4213. form && setValue(form, me);
  4214. },
  4215. /**
  4216. * 设置编辑器高度
  4217. * @name setHeight
  4218. * @grammar editor.setHeight(number); //纯数值,不带单位
  4219. */
  4220. setHeight: function (height,notSetHeight) {
  4221. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  4222. this.iframe.parentNode.style.height = height + 'px';
  4223. }
  4224. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  4225. this.body.style.height = height + 'px';
  4226. },
  4227. addshortcutkey: function (cmd, keys) {
  4228. var obj = {};
  4229. if (keys) {
  4230. obj[cmd] = keys
  4231. } else {
  4232. obj = cmd;
  4233. }
  4234. utils.extend(this.shortcutkeys, obj)
  4235. },
  4236. _bindshortcutKeys: function () {
  4237. var me = this, shortcutkeys = this.shortcutkeys;
  4238. me.addListener('keydown', function (type, e) {
  4239. var keyCode = e.keyCode || e.which;
  4240. for (var i in shortcutkeys) {
  4241. var tmp = shortcutkeys[i].split(',');
  4242. for (var t = 0, ti; ti = tmp[t++];) {
  4243. ti = ti.split(':');
  4244. var key = ti[0], param = ti[1];
  4245. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  4246. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  4247. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  4248. && keyCode == RegExp.$3
  4249. ) ||
  4250. keyCode == RegExp.$1
  4251. ) {
  4252. if (me.queryCommandState(i,param) != -1)
  4253. me.execCommand(i, param);
  4254. domUtils.preventDefault(e);
  4255. }
  4256. }
  4257. }
  4258. }
  4259. });
  4260. },
  4261. /**
  4262. * 获取编辑器内容
  4263. * @name getContent
  4264. * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。
  4265. * @grammar editor.getContent(fn) => String
  4266. * @example
  4267. * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串
  4268. * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则
  4269. * editor.getContent(function(){
  4270. * return false //编辑器没有内容 ,getContent直接返回空
  4271. * })
  4272. */
  4273. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  4274. var me = this;
  4275. if (cmd && utils.isFunction(cmd)) {
  4276. fn = cmd;
  4277. cmd = '';
  4278. }
  4279. if (fn ? !fn() : !this.hasContents()) {
  4280. return '';
  4281. }
  4282. me.fireEvent('beforegetcontent');
  4283. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  4284. me.filterOutputRule(root);
  4285. me.fireEvent('aftergetcontent', cmd);
  4286. return root.toHtml(formatter);
  4287. },
  4288. /**
  4289. * 取得完整的html代码,可以直接显示成完整的html文档
  4290. * @name getAllHtml
  4291. * @grammar editor.getAllHtml() => String
  4292. */
  4293. getAllHtml: function () {
  4294. var me = this,
  4295. headHtml = [],
  4296. html = '';
  4297. me.fireEvent('getAllHtml', headHtml);
  4298. if (browser.ie && browser.version > 8) {
  4299. var headHtmlForIE9 = '';
  4300. utils.each(me.document.styleSheets, function (si) {
  4301. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  4302. });
  4303. utils.each(me.document.getElementsByTagName('script'), function (si) {
  4304. headHtmlForIE9 += si.outerHTML;
  4305. });
  4306. }
  4307. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  4308. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  4309. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  4310. },
  4311. /**
  4312. * 得到编辑器的纯文本内容,但会保留段落格式
  4313. * @name getPlainTxt
  4314. * @grammar editor.getPlainTxt() => String
  4315. */
  4316. getPlainTxt: function () {
  4317. var reg = new RegExp(domUtils.fillChar, 'g'),
  4318. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  4319. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  4320. .replace(/<br\/?>/gi, '\n')
  4321. .replace(/<[^>/]+>/g, '')
  4322. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  4323. return dtd.$block[c] ? '\n' : b ? b : '';
  4324. });
  4325. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4326. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  4327. },
  4328. /**
  4329. * 获取编辑器中的纯文本内容,没有段落格式
  4330. * @name getContentTxt
  4331. * @grammar editor.getContentTxt() => String
  4332. */
  4333. getContentTxt: function () {
  4334. var reg = new RegExp(domUtils.fillChar, 'g');
  4335. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4336. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  4337. },
  4338. /**
  4339. * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行
  4340. * @name setContent
  4341. * @grammar editor.setContent(html)
  4342. * @example
  4343. * var editor = new UE.ui.Editor()
  4344. * editor.ready(function(){
  4345. * //需要ready后执行,否则可能报错
  4346. * editor.setContent("欢迎使用UEditor!");
  4347. * })
  4348. */
  4349. setContent: function (html, isAppendTo, notFireSelectionchange) {
  4350. var me = this;
  4351. me.fireEvent('beforesetcontent', html);
  4352. var root = UE.htmlparser(html);
  4353. me.filterInputRule(root);
  4354. html = root.toHtml();
  4355. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  4356. function isCdataDiv(node){
  4357. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  4358. }
  4359. //给文本或者inline节点套p标签
  4360. if (me.options.enterTag == 'p') {
  4361. var child = this.body.firstChild, tmpNode;
  4362. if (!child || child.nodeType == 1 &&
  4363. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  4364. domUtils.isCustomeNode(child)
  4365. )
  4366. && child === this.body.lastChild) {
  4367. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  4368. } else {
  4369. var p = me.document.createElement('p');
  4370. while (child) {
  4371. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  4372. tmpNode = child.nextSibling;
  4373. p.appendChild(child);
  4374. child = tmpNode;
  4375. }
  4376. if (p.firstChild) {
  4377. if (!child) {
  4378. me.body.appendChild(p);
  4379. break;
  4380. } else {
  4381. child.parentNode.insertBefore(p, child);
  4382. p = me.document.createElement('p');
  4383. }
  4384. }
  4385. child = child.nextSibling;
  4386. }
  4387. }
  4388. }
  4389. me.fireEvent('aftersetcontent');
  4390. me.fireEvent('contentchange');
  4391. !notFireSelectionchange && me._selectionChange();
  4392. //清除保存的选区
  4393. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  4394. //trace:1742 setContent后gecko能得到焦点问题
  4395. var geckoSel;
  4396. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  4397. geckoSel.removeAllRanges();
  4398. }
  4399. if(me.options.autoSyncData){
  4400. me.form && setValue(me.form,me);
  4401. }
  4402. },
  4403. /**
  4404. * 让编辑器获得焦点,toEnd确定focus位置
  4405. * @name focus
  4406. * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部
  4407. */
  4408. focus: function (toEnd) {
  4409. try {
  4410. var me = this,
  4411. rng = me.selection.getRange();
  4412. if (toEnd) {
  4413. rng.setStartAtLast(me.body.lastChild).setCursor(false, true);
  4414. } else {
  4415. rng.select(true);
  4416. }
  4417. this.fireEvent('focus');
  4418. } catch (e) {
  4419. }
  4420. },
  4421. /**
  4422. * 初始化UE事件及部分事件代理
  4423. * @private
  4424. * @ignore
  4425. */
  4426. _initEvents: function () {
  4427. var me = this,
  4428. doc = me.document,
  4429. win = me.window;
  4430. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  4431. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  4432. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  4433. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  4434. //特殊键不触发selectionchange
  4435. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  4436. return;
  4437. }
  4438. if (evt.button == 2)return;
  4439. me._selectionChange(250, evt);
  4440. });
  4441. // //处理拖拽
  4442. // //ie ff不能从外边拖入
  4443. // //chrome只针对从外边拖入的内容过滤
  4444. // var innerDrag = 0, source = browser.ie ? me.body : me.document, dragoverHandler;
  4445. // domUtils.on(source, 'dragstart', function () {
  4446. // innerDrag = 1;
  4447. // });
  4448. // domUtils.on(source, browser.webkit ? 'dragover' : 'drop', function () {
  4449. // return browser.webkit ?
  4450. // function () {
  4451. // clearTimeout(dragoverHandler);
  4452. // dragoverHandler = setTimeout(function () {
  4453. // if (!innerDrag) {
  4454. // var sel = me.selection,
  4455. // range = sel.getRange();
  4456. // if (range) {
  4457. // var common = range.getCommonAncestor();
  4458. // if (common && me.serialize) {
  4459. // var f = me.serialize,
  4460. // node =
  4461. // f.filter(
  4462. // f.transformInput(
  4463. // f.parseHTML(
  4464. // f.word(common.innerHTML)
  4465. // )
  4466. // )
  4467. // );
  4468. // common.innerHTML = f.toHTML(node);
  4469. // }
  4470. // }
  4471. // }
  4472. // innerDrag = 0;
  4473. // }, 200);
  4474. // } :
  4475. // function (e) {
  4476. // if (!innerDrag) {
  4477. // e.preventDefault ? e.preventDefault() : (e.returnValue = false);
  4478. // }
  4479. // innerDrag = 0;
  4480. // }
  4481. // }());
  4482. },
  4483. /**
  4484. * 触发事件代理
  4485. * @private
  4486. * @ignore
  4487. */
  4488. _proxyDomEvent: function (evt) {
  4489. return this.fireEvent(evt.type.replace(/^on/, ''), evt);
  4490. },
  4491. /**
  4492. * 变化选区
  4493. * @private
  4494. * @ignore
  4495. */
  4496. _selectionChange: function (delay, evt) {
  4497. var me = this;
  4498. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  4499. // if ( !me.selection.isFocus() ){
  4500. // return;
  4501. // }
  4502. var hackForMouseUp = false;
  4503. var mouseX, mouseY;
  4504. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  4505. var range = this.selection.getRange();
  4506. if (!range.collapsed) {
  4507. hackForMouseUp = true;
  4508. mouseX = evt.clientX;
  4509. mouseY = evt.clientY;
  4510. }
  4511. }
  4512. clearTimeout(_selectionChangeTimer);
  4513. _selectionChangeTimer = setTimeout(function () {
  4514. if (!me.selection.getNative()) {
  4515. return;
  4516. }
  4517. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  4518. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  4519. var ieRange;
  4520. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  4521. ieRange = me.document.body.createTextRange();
  4522. try {
  4523. ieRange.moveToPoint(mouseX, mouseY);
  4524. } catch (ex) {
  4525. ieRange = null;
  4526. }
  4527. }
  4528. var bakGetIERange;
  4529. if (ieRange) {
  4530. bakGetIERange = me.selection.getIERange;
  4531. me.selection.getIERange = function () {
  4532. return ieRange;
  4533. };
  4534. }
  4535. me.selection.cache();
  4536. if (bakGetIERange) {
  4537. me.selection.getIERange = bakGetIERange;
  4538. }
  4539. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  4540. me.fireEvent('beforeselectionchange');
  4541. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  4542. me.fireEvent('selectionchange', !!evt);
  4543. me.fireEvent('afterselectionchange');
  4544. me.selection.clear();
  4545. }
  4546. }, delay || 50);
  4547. },
  4548. _callCmdFn: function (fnName, args) {
  4549. var cmdName = args[0].toLowerCase(),
  4550. cmd, cmdFn;
  4551. cmd = this.commands[cmdName] || UE.commands[cmdName];
  4552. cmdFn = cmd && cmd[fnName];
  4553. //没有querycommandstate或者没有command的都默认返回0
  4554. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  4555. return 0;
  4556. } else if (cmdFn) {
  4557. return cmdFn.apply(this, args);
  4558. }
  4559. },
  4560. /**
  4561. * 执行编辑命令cmdName,完成富文本编辑效果
  4562. * @name execCommand
  4563. * @grammar editor.execCommand(cmdName) => {*}
  4564. */
  4565. execCommand: function (cmdName) {
  4566. cmdName = cmdName.toLowerCase();
  4567. var me = this,
  4568. result,
  4569. cmd = me.commands[cmdName] || UE.commands[cmdName];
  4570. if (!cmd || !cmd.execCommand) {
  4571. return null;
  4572. }
  4573. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  4574. me.__hasEnterExecCommand = true;
  4575. if (me.queryCommandState.apply(me,arguments) != -1) {
  4576. me.fireEvent('beforeexeccommand', cmdName);
  4577. result = this._callCmdFn('execCommand', arguments);
  4578. !me._ignoreContentChange && me.fireEvent('contentchange');
  4579. me.fireEvent('afterexeccommand', cmdName);
  4580. }
  4581. me.__hasEnterExecCommand = false;
  4582. } else {
  4583. result = this._callCmdFn('execCommand', arguments);
  4584. !me._ignoreContentChange && me.fireEvent('contentchange')
  4585. }
  4586. !me._ignoreContentChange && me._selectionChange();
  4587. return result;
  4588. },
  4589. /**
  4590. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  4591. * @name queryCommandState
  4592. * @grammar editor.queryCommandState(cmdName) => (-1|0|1)
  4593. * @desc
  4594. * * ''-1'' 当前命令不可用
  4595. * * ''0'' 当前命令可用
  4596. * * ''1'' 当前命令已经执行过了
  4597. */
  4598. queryCommandState: function (cmdName) {
  4599. return this._callCmdFn('queryCommandState', arguments);
  4600. },
  4601. /**
  4602. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  4603. * @name queryCommandValue
  4604. * @grammar editor.queryCommandValue(cmdName) => {*}
  4605. */
  4606. queryCommandValue: function (cmdName) {
  4607. return this._callCmdFn('queryCommandValue', arguments);
  4608. },
  4609. /**
  4610. * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true
  4611. * @name hasContents
  4612. * @desc
  4613. * 默认有文本内容,或者有以下节点都不认为是空
  4614. * <code>{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}</code>
  4615. * @grammar editor.hasContents() => (true|false)
  4616. * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true
  4617. * @example
  4618. * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空
  4619. */
  4620. hasContents: function (tags) {
  4621. if (tags) {
  4622. for (var i = 0, ci; ci = tags[i++];) {
  4623. if (this.document.getElementsByTagName(ci).length > 0) {
  4624. return true;
  4625. }
  4626. }
  4627. }
  4628. if (!domUtils.isEmptyBlock(this.body)) {
  4629. return true
  4630. }
  4631. //随时添加,定义的特殊标签如果存在,不能认为是空
  4632. tags = ['div'];
  4633. for (i = 0; ci = tags[i++];) {
  4634. var nodes = domUtils.getElementsByTagName(this.document, ci);
  4635. for (var n = 0, cn; cn = nodes[n++];) {
  4636. if (domUtils.isCustomeNode(cn)) {
  4637. return true;
  4638. }
  4639. }
  4640. }
  4641. return false;
  4642. },
  4643. /**
  4644. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  4645. * @name reset
  4646. * @desc
  4647. * * 清空编辑器内容
  4648. * * 清空回退列表
  4649. * @grammar editor.reset()
  4650. */
  4651. reset: function () {
  4652. this.fireEvent('reset');
  4653. },
  4654. setEnabled: function () {
  4655. var me = this, range;
  4656. if (me.body.contentEditable == 'false') {
  4657. me.body.contentEditable = true;
  4658. range = me.selection.getRange();
  4659. //有可能内容丢失了
  4660. try {
  4661. range.moveToBookmark(me.lastBk);
  4662. delete me.lastBk
  4663. } catch (e) {
  4664. range.setStartAtFirst(me.body).collapse(true)
  4665. }
  4666. range.select(true);
  4667. if (me.bkqueryCommandState) {
  4668. me.queryCommandState = me.bkqueryCommandState;
  4669. delete me.bkqueryCommandState;
  4670. }
  4671. me.fireEvent('selectionchange');
  4672. }
  4673. },
  4674. /**
  4675. * 设置当前编辑区域可以编辑
  4676. * @name enable
  4677. * @grammar editor.enable()
  4678. */
  4679. enable: function () {
  4680. return this.setEnabled();
  4681. },
  4682. setDisabled: function (except) {
  4683. var me = this;
  4684. except = except ? utils.isArray(except) ? except : [except] : [];
  4685. if (me.body.contentEditable == 'true') {
  4686. if (!me.lastBk) {
  4687. me.lastBk = me.selection.getRange().createBookmark(true);
  4688. }
  4689. me.body.contentEditable = false;
  4690. me.bkqueryCommandState = me.queryCommandState;
  4691. me.queryCommandState = function (type) {
  4692. if (utils.indexOf(except, type) != -1) {
  4693. return me.bkqueryCommandState.apply(me, arguments);
  4694. }
  4695. return -1;
  4696. };
  4697. me.fireEvent('selectionchange');
  4698. }
  4699. },
  4700. /** 设置当前编辑区域不可编辑,except中的命令除外
  4701. * @name disable
  4702. * @grammar editor.disable()
  4703. * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行
  4704. * @example
  4705. * //禁用工具栏中除加粗和插入图片之外的所有功能
  4706. * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array
  4707. */
  4708. disable: function (except) {
  4709. return this.setDisabled(except);
  4710. },
  4711. /**
  4712. * 设置默认内容
  4713. * @ignore
  4714. * @private
  4715. * @param {String} cont 要存入的内容
  4716. */
  4717. _setDefaultContent: function () {
  4718. function clear() {
  4719. var me = this;
  4720. if (me.document.getElementById('initContent')) {
  4721. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  4722. me.removeListener('firstBeforeExecCommand focus', clear);
  4723. setTimeout(function () {
  4724. me.focus();
  4725. me._selectionChange();
  4726. }, 0)
  4727. }
  4728. }
  4729. return function (cont) {
  4730. var me = this;
  4731. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  4732. me.addListener('firstBeforeExecCommand focus', clear);
  4733. }
  4734. }(),
  4735. /**
  4736. * show方法的兼容版本
  4737. * @private
  4738. * @ignore
  4739. */
  4740. setShow: function () {
  4741. var me = this, range = me.selection.getRange();
  4742. if (me.container.style.display == 'none') {
  4743. //有可能内容丢失了
  4744. try {
  4745. range.moveToBookmark(me.lastBk);
  4746. delete me.lastBk
  4747. } catch (e) {
  4748. range.setStartAtFirst(me.body).collapse(true)
  4749. }
  4750. //ie下focus实效,所以做了个延迟
  4751. setTimeout(function () {
  4752. range.select(true);
  4753. }, 100);
  4754. me.container.style.display = '';
  4755. }
  4756. },
  4757. /**
  4758. * 显示编辑器
  4759. * @name show
  4760. * @grammar editor.show()
  4761. */
  4762. show: function () {
  4763. return this.setShow();
  4764. },
  4765. /**
  4766. * hide方法的兼容版本
  4767. * @private
  4768. * @ignore
  4769. */
  4770. setHide: function () {
  4771. var me = this;
  4772. if (!me.lastBk) {
  4773. me.lastBk = me.selection.getRange().createBookmark(true);
  4774. }
  4775. me.container.style.display = 'none'
  4776. },
  4777. /**
  4778. * 隐藏编辑器
  4779. * @name hide
  4780. * @grammar editor.hide()
  4781. */
  4782. hide: function () {
  4783. return this.setHide();
  4784. },
  4785. /**
  4786. * 根据制定的路径,获取对应的语言资源
  4787. * @name getLang
  4788. * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构
  4789. * @example
  4790. * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除
  4791. */
  4792. getLang: function (path) {
  4793. var lang = UE.I18N[this.options.lang];
  4794. if (!lang) {
  4795. throw Error("not import language file");
  4796. }
  4797. path = (path || "").split(".");
  4798. for (var i = 0, ci; ci = path[i++];) {
  4799. lang = lang[ci];
  4800. if (!lang)break;
  4801. }
  4802. return lang;
  4803. },
  4804. /**
  4805. * 计算编辑器当前内容的长度
  4806. * @name getContentLength
  4807. * @grammar editor.getContentLength(ingoneHtml,tagNames) =>
  4808. * @example
  4809. * editor.getLang(true)
  4810. */
  4811. getContentLength: function (ingoneHtml, tagNames) {
  4812. var count = this.getContent(false,false,true).length;
  4813. if (ingoneHtml) {
  4814. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  4815. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  4816. for (var i = 0, ci; ci = tagNames[i++];) {
  4817. count += this.document.getElementsByTagName(ci).length;
  4818. }
  4819. }
  4820. return count;
  4821. },
  4822. addInputRule: function (rule) {
  4823. this.inputRules.push(rule);
  4824. },
  4825. filterInputRule: function (root) {
  4826. for (var i = 0, ci; ci = this.inputRules[i++];) {
  4827. ci.call(this, root)
  4828. }
  4829. },
  4830. addOutputRule: function (rule) {
  4831. this.outputRules.push(rule)
  4832. },
  4833. filterOutputRule: function (root) {
  4834. for (var i = 0, ci; ci = this.outputRules[i++];) {
  4835. ci.call(this, root)
  4836. }
  4837. }
  4838. /**
  4839. * 得到dialog实例对象
  4840. * @name getDialog
  4841. * @grammar editor.getDialog(dialogName) => Object
  4842. * @example
  4843. * var dialog = editor.getDialog("insertimage");
  4844. * dialog.open(); //打开dialog
  4845. * dialog.close(); //关闭dialog
  4846. */
  4847. };
  4848. utils.inherits(Editor, EventBase);
  4849. })();
  4850. /**
  4851. * @file
  4852. * @name UE.ajax
  4853. * @short Ajax
  4854. * @desc UEditor内置的ajax请求模块
  4855. * @import core/utils.js
  4856. * @user: taoqili
  4857. * @date: 11-8-18
  4858. * @time: 下午3:18
  4859. */
  4860. UE.ajax = function() {
  4861. /**
  4862. * 创建一个ajaxRequest对象
  4863. */
  4864. var fnStr = 'XMLHttpRequest()';
  4865. try {
  4866. new ActiveXObject("Msxml2.XMLHTTP");
  4867. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  4868. } catch (e) {
  4869. try {
  4870. new ActiveXObject("Microsoft.XMLHTTP");
  4871. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  4872. } catch (e) {
  4873. }
  4874. }
  4875. var creatAjaxRequest = new Function('return new ' + fnStr);
  4876. /**
  4877. * 将json参数转化成适合ajax提交的参数列表
  4878. * @param json
  4879. */
  4880. function json2str(json) {
  4881. var strArr = [];
  4882. for (var i in json) {
  4883. //忽略默认的几个参数
  4884. if(i=="method" || i=="timeout" || i=="async") continue;
  4885. //传递过来的对象和函数不在提交之列
  4886. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  4887. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  4888. }
  4889. }
  4890. return strArr.join("&");
  4891. }
  4892. return {
  4893. /**
  4894. * @name request
  4895. * @desc 发出ajax请求,ajaxOpt中默认包含method,timeout,async,data,onsuccess以及onerror等六个,支持自定义添加参数
  4896. * @grammar UE.ajax.request(url,ajaxOpt);
  4897. * @example
  4898. * UE.ajax.request('http://www.xxxx.com/test.php',{
  4899. * //可省略,默认POST
  4900. * method:'POST',
  4901. * //可以自定义参数
  4902. * content:'这里是提交的内容',
  4903. * //也可以直接传json,但是只能命名为data,否则当做一般字符串处理
  4904. * data:{
  4905. * name:'UEditor',
  4906. * age:'1'
  4907. * }
  4908. * onsuccess:function(xhr){
  4909. * console.log(xhr.responseText);
  4910. * },
  4911. * onerror:function(xhr){
  4912. * console.log(xhr.responseText);
  4913. * }
  4914. * })
  4915. * @param ajaxOptions
  4916. */
  4917. request:function(url, ajaxOptions) {
  4918. var ajaxRequest = creatAjaxRequest(),
  4919. //是否超时
  4920. timeIsOut = false,
  4921. //默认参数
  4922. defaultAjaxOptions = {
  4923. method:"POST",
  4924. timeout:5000,
  4925. async:true,
  4926. data:{},//需要传递对象的话只能覆盖
  4927. onsuccess:function() {
  4928. },
  4929. onerror:function() {
  4930. }
  4931. };
  4932. if (typeof url === "object") {
  4933. ajaxOptions = url;
  4934. url = ajaxOptions.url;
  4935. }
  4936. if (!ajaxRequest || !url) return;
  4937. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  4938. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  4939. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  4940. if (!utils.isEmptyObject(ajaxOpts.data)){
  4941. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  4942. }
  4943. //超时检测
  4944. var timerID = setTimeout(function() {
  4945. if (ajaxRequest.readyState != 4) {
  4946. timeIsOut = true;
  4947. ajaxRequest.abort();
  4948. clearTimeout(timerID);
  4949. }
  4950. }, ajaxOpts.timeout);
  4951. var method = ajaxOpts.method.toUpperCase();
  4952. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  4953. ajaxRequest.open(method, str, ajaxOpts.async);
  4954. ajaxRequest.onreadystatechange = function() {
  4955. if (ajaxRequest.readyState == 4) {
  4956. if (!timeIsOut && ajaxRequest.status == 200) {
  4957. ajaxOpts.onsuccess(ajaxRequest);
  4958. } else {
  4959. ajaxOpts.onerror(ajaxRequest);
  4960. }
  4961. }
  4962. };
  4963. if (method == "POST") {
  4964. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4965. ajaxRequest.send(submitStr);
  4966. } else {
  4967. ajaxRequest.send(null);
  4968. }
  4969. }
  4970. };
  4971. }();
  4972. /**
  4973. * @file
  4974. * @name UE.filterWord
  4975. * @short filterWord
  4976. * @desc 用来过滤word粘贴过来的字符串
  4977. * @import editor.js,core/utils.js
  4978. * @anthor zhanyi
  4979. */
  4980. var filterWord = UE.filterWord = function () {
  4981. //是否是word过来的内容
  4982. function isWordDocument( str ) {
  4983. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig.test( str );
  4984. }
  4985. //去掉小数
  4986. function transUnit( v ) {
  4987. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  4988. return utils.transUnitToPx(m);
  4989. } );
  4990. return v;
  4991. }
  4992. function filterPasteWord( str ) {
  4993. return str.replace( /[\t\r\n]+/g, "" )
  4994. .replace( /<!--[\s\S]*?-->/ig, "" )
  4995. //转换图片
  4996. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  4997. //opera能自己解析出image所这里直接返回空
  4998. if(browser.opera){
  4999. return '';
  5000. }
  5001. try{
  5002. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  5003. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  5004. src = str.match(/src=\s*"([^"]*)"/i)[1];
  5005. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  5006. } catch(e){
  5007. return '';
  5008. }
  5009. })
  5010. //针对wps添加的多余标签处理
  5011. .replace(/<\/?div[^>]*>/g,'')
  5012. //去掉多余的属性
  5013. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  5014. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  5015. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  5016. //去掉多余的属性
  5017. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  5018. //保留list的标示
  5019. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  5020. })
  5021. //清除多余的font/span不能匹配&nbsp;有可能是空格
  5022. .replace( /<(font|span)[^>]*>\s*<\/\1>/gi, '' )
  5023. //处理style的问题
  5024. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  5025. var n = [],
  5026. s = style.replace( /^\s+|\s+$/, '' )
  5027. .replace(/&#39;/g,'\'')
  5028. .replace( /&quot;/gi, "'" )
  5029. .split( /;\s*/g );
  5030. for ( var i = 0,v; v = s[i];i++ ) {
  5031. var name, value,
  5032. parts = v.split( ":" );
  5033. if ( parts.length == 2 ) {
  5034. name = parts[0].toLowerCase();
  5035. value = parts[1].toLowerCase();
  5036. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  5037. ||
  5038. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  5039. ){
  5040. continue;
  5041. }
  5042. switch ( name ) {
  5043. case "mso-padding-alt":
  5044. case "mso-padding-top-alt":
  5045. case "mso-padding-right-alt":
  5046. case "mso-padding-bottom-alt":
  5047. case "mso-padding-left-alt":
  5048. case "mso-margin-alt":
  5049. case "mso-margin-top-alt":
  5050. case "mso-margin-right-alt":
  5051. case "mso-margin-bottom-alt":
  5052. case "mso-margin-left-alt":
  5053. //ie下会出现挤到一起的情况
  5054. //case "mso-table-layout-alt":
  5055. case "mso-height":
  5056. case "mso-width":
  5057. case "mso-vertical-align-alt":
  5058. //trace:1819 ff下会解析出padding在table上
  5059. if(!/<table/.test(tag))
  5060. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  5061. continue;
  5062. case "horiz-align":
  5063. n[i] = "text-align:" + value;
  5064. continue;
  5065. case "vert-align":
  5066. n[i] = "vertical-align:" + value;
  5067. continue;
  5068. case "font-color":
  5069. case "mso-foreground":
  5070. n[i] = "color:" + value;
  5071. continue;
  5072. case "mso-background":
  5073. case "mso-highlight":
  5074. n[i] = "background:" + value;
  5075. continue;
  5076. case "mso-default-height":
  5077. n[i] = "min-height:" + transUnit( value );
  5078. continue;
  5079. case "mso-default-width":
  5080. n[i] = "min-width:" + transUnit( value );
  5081. continue;
  5082. case "mso-padding-between-alt":
  5083. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  5084. continue;
  5085. case "text-line-through":
  5086. if ( (value == "single") || (value == "double") ) {
  5087. n[i] = "text-decoration:line-through";
  5088. }
  5089. continue;
  5090. case "mso-zero-height":
  5091. if ( value == "yes" ) {
  5092. n[i] = "display:none";
  5093. }
  5094. continue;
  5095. case 'background':
  5096. break;
  5097. case 'margin':
  5098. if ( !/[1-9]/.test( value ) ) {
  5099. continue;
  5100. }
  5101. }
  5102. 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 )
  5103. ||
  5104. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  5105. ) {
  5106. continue;
  5107. }
  5108. n[i] = name + ":" + parts[1];
  5109. }
  5110. }
  5111. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  5112. })
  5113. .replace(/[\d.]+(cm|pt)/g,function(str){
  5114. return utils.transUnitToPx(str)
  5115. })
  5116. }
  5117. return function ( html ) {
  5118. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  5119. };
  5120. }();
  5121. ///import editor.js
  5122. ///import core/utils.js
  5123. ///import core/dom/dom.js
  5124. ///import core/dom/dtd.js
  5125. ///import core/htmlparser.js
  5126. //模拟的节点类
  5127. //by zhanyi
  5128. (function () {
  5129. var uNode = UE.uNode = function (obj) {
  5130. this.type = obj.type;
  5131. this.data = obj.data;
  5132. this.tagName = obj.tagName;
  5133. this.parentNode = obj.parentNode;
  5134. this.attrs = obj.attrs || {};
  5135. this.children = obj.children;
  5136. };
  5137. var indentChar = ' ',
  5138. breakChar = '\n';
  5139. function insertLine(arr, current, begin) {
  5140. arr.push(breakChar);
  5141. return current + (begin ? 1 : -1);
  5142. }
  5143. function insertIndent(arr, current) {
  5144. //插入缩进
  5145. for (var i = 0; i < current; i++) {
  5146. arr.push(indentChar);
  5147. }
  5148. }
  5149. //创建uNode的静态方法
  5150. //支持标签和html
  5151. uNode.createElement = function (html) {
  5152. if (/[<>]/.test(html)) {
  5153. return UE.htmlparser(html).children[0]
  5154. } else {
  5155. return new uNode({
  5156. type:'element',
  5157. children:[],
  5158. tagName:html
  5159. })
  5160. }
  5161. };
  5162. uNode.createText = function (data) {
  5163. return new UE.uNode({
  5164. type:'text',
  5165. 'data':utils.unhtml(data || '')
  5166. })
  5167. };
  5168. function nodeToHtml(node, arr, formatter, current) {
  5169. switch (node.type) {
  5170. case 'root':
  5171. for (var i = 0, ci; ci = node.children[i++];) {
  5172. //插入新行
  5173. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  5174. insertLine(arr, current, true);
  5175. insertIndent(arr, current)
  5176. }
  5177. nodeToHtml(ci, arr, formatter, current)
  5178. }
  5179. break;
  5180. case 'text':
  5181. isText(node, arr);
  5182. break;
  5183. case 'element':
  5184. isElement(node, arr, formatter, current);
  5185. break;
  5186. case 'comment':
  5187. isComment(node, arr, formatter);
  5188. }
  5189. return arr;
  5190. }
  5191. function isText(node, arr) {
  5192. arr.push(node.parentNode.tagName == 'pre' ? node.data : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  5193. }
  5194. function isElement(node, arr, formatter, current) {
  5195. var attrhtml = '';
  5196. if (node.attrs) {
  5197. attrhtml = [];
  5198. var attrs = node.attrs;
  5199. for (var a in attrs) {
  5200. attrhtml.push(a + (attrs[a] !== undefined ? '="' + utils.unhtml(attrs[a]) + '"' : ''))
  5201. }
  5202. attrhtml = attrhtml.join(' ');
  5203. }
  5204. arr.push('<' + node.tagName +
  5205. (attrhtml ? ' ' + attrhtml : '') +
  5206. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  5207. );
  5208. //插入新行
  5209. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  5210. if(node.children && node.children.length){
  5211. current = insertLine(arr, current, true);
  5212. insertIndent(arr, current)
  5213. }
  5214. }
  5215. if (node.children && node.children.length) {
  5216. for (var i = 0, ci; ci = node.children[i++];) {
  5217. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  5218. insertLine(arr, current);
  5219. insertIndent(arr, current)
  5220. }
  5221. nodeToHtml(ci, arr, formatter, current)
  5222. }
  5223. }
  5224. if (!dtd.$empty[node.tagName]) {
  5225. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  5226. if(node.children && node.children.length){
  5227. current = insertLine(arr, current);
  5228. insertIndent(arr, current)
  5229. }
  5230. }
  5231. arr.push('<\/' + node.tagName + '>');
  5232. }
  5233. }
  5234. function isComment(node, arr) {
  5235. arr.push('<!--' + node.data + '-->');
  5236. }
  5237. function getNodeById(root, id) {
  5238. var node;
  5239. if (root.type == 'element' && root.getAttr('id') == id) {
  5240. return root;
  5241. }
  5242. if (root.children && root.children.length) {
  5243. for (var i = 0, ci; ci = root.children[i++];) {
  5244. if (node = getNodeById(ci, id)) {
  5245. return node;
  5246. }
  5247. }
  5248. }
  5249. }
  5250. function getNodesByTagName(node, tagName, arr) {
  5251. if (node.type == 'element' && node.tagName == tagName) {
  5252. arr.push(node);
  5253. }
  5254. if (node.children && node.children.length) {
  5255. for (var i = 0, ci; ci = node.children[i++];) {
  5256. getNodesByTagName(ci, tagName, arr)
  5257. }
  5258. }
  5259. }
  5260. function nodeTraversal(root,fn){
  5261. if(root.children && root.children.length){
  5262. for(var i= 0,ci;ci=root.children[i];){
  5263. nodeTraversal(ci,fn);
  5264. //ci被替换的情况,这里就不再走 fn了
  5265. if(ci.parentNode ){
  5266. if(ci.children && ci.children.length){
  5267. fn(ci)
  5268. }
  5269. if(ci.parentNode) i++
  5270. }
  5271. }
  5272. }else{
  5273. fn(root)
  5274. }
  5275. }
  5276. uNode.prototype = {
  5277. toHtml:function (formatter) {
  5278. var arr = [];
  5279. nodeToHtml(this, arr, formatter, 0);
  5280. return arr.join('')
  5281. },
  5282. innerHTML:function (htmlstr) {
  5283. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5284. return this;
  5285. }
  5286. if (utils.isString(htmlstr)) {
  5287. if(this.children){
  5288. for (var i = 0, ci; ci = this.children[i++];) {
  5289. ci.parentNode = null;
  5290. }
  5291. }
  5292. this.children = [];
  5293. var tmpRoot = UE.htmlparser(htmlstr);
  5294. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  5295. this.children.push(ci);
  5296. ci.parentNode = this;
  5297. }
  5298. return this;
  5299. } else {
  5300. var tmpRoot = new UE.uNode({
  5301. type:'root',
  5302. children:this.children
  5303. });
  5304. return tmpRoot.toHtml();
  5305. }
  5306. },
  5307. innerText:function (textStr) {
  5308. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5309. return this;
  5310. }
  5311. if (textStr) {
  5312. if(this.children){
  5313. for (var i = 0, ci; ci = this.children[i++];) {
  5314. ci.parentNode = null;
  5315. }
  5316. }
  5317. this.children = [];
  5318. this.appendChild(uNode.createText(textStr));
  5319. return this;
  5320. } else {
  5321. return this.toHtml().replace(/<[^>]+>/g, '');
  5322. }
  5323. },
  5324. getData:function () {
  5325. if (this.type == 'element')
  5326. return '';
  5327. return this.data
  5328. },
  5329. firstChild:function () {
  5330. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5331. // return this;
  5332. // }
  5333. return this.children ? this.children[0] : null;
  5334. },
  5335. lastChild:function () {
  5336. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  5337. // return this;
  5338. // }
  5339. return this.children ? this.children[this.children.length - 1] : null;
  5340. },
  5341. previousSibling : function(){
  5342. var parent = this.parentNode;
  5343. for (var i = 0, ci; ci = parent.children[i]; i++) {
  5344. if (ci === this) {
  5345. return i == 0 ? null : parent.children[i-1];
  5346. }
  5347. }
  5348. },
  5349. nextSibling : function(){
  5350. var parent = this.parentNode;
  5351. for (var i = 0, ci; ci = parent.children[i++];) {
  5352. if (ci === this) {
  5353. return parent.children[i];
  5354. }
  5355. }
  5356. },
  5357. replaceChild:function (target, source) {
  5358. if (this.children) {
  5359. if(target.parentNode){
  5360. target.parentNode.removeChild(target);
  5361. }
  5362. for (var i = 0, ci; ci = this.children[i]; i++) {
  5363. if (ci === source) {
  5364. this.children.splice(i, 1, target);
  5365. source.parentNode = null;
  5366. target.parentNode = this;
  5367. return target;
  5368. }
  5369. }
  5370. }
  5371. },
  5372. appendChild:function (node) {
  5373. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  5374. if (!this.children) {
  5375. this.children = []
  5376. }
  5377. if(node.parentNode){
  5378. node.parentNode.removeChild(node);
  5379. }
  5380. for (var i = 0, ci; ci = this.children[i]; i++) {
  5381. if (ci === node) {
  5382. this.children.splice(i, 1);
  5383. break;
  5384. }
  5385. }
  5386. this.children.push(node);
  5387. node.parentNode = this;
  5388. return node;
  5389. }
  5390. },
  5391. insertBefore:function (target, source) {
  5392. if (this.children) {
  5393. if(target.parentNode){
  5394. target.parentNode.removeChild(target);
  5395. }
  5396. for (var i = 0, ci; ci = this.children[i]; i++) {
  5397. if (ci === source) {
  5398. this.children.splice(i, 0, target);
  5399. target.parentNode = this;
  5400. return target;
  5401. }
  5402. }
  5403. }
  5404. },
  5405. insertAfter:function (target, source) {
  5406. if (this.children) {
  5407. if(target.parentNode){
  5408. target.parentNode.removeChild(target);
  5409. }
  5410. for (var i = 0, ci; ci = this.children[i]; i++) {
  5411. if (ci === source) {
  5412. this.children.splice(i + 1, 0, target);
  5413. target.parentNode = this;
  5414. return target;
  5415. }
  5416. }
  5417. }
  5418. },
  5419. removeChild:function (node,keepChildren) {
  5420. if (this.children) {
  5421. for (var i = 0, ci; ci = this.children[i]; i++) {
  5422. if (ci === node) {
  5423. this.children.splice(i, 1);
  5424. ci.parentNode = null;
  5425. if(keepChildren && ci.children && ci.children.length){
  5426. for(var j= 0,cj;cj=ci.children[j];j++){
  5427. this.children.splice(i+j,0,cj);
  5428. cj.parentNode = this;
  5429. }
  5430. }
  5431. return ci;
  5432. }
  5433. }
  5434. }
  5435. },
  5436. getAttr:function (attrName) {
  5437. return this.attrs && this.attrs[attrName.toLowerCase()]
  5438. },
  5439. setAttr:function (attrName, attrVal) {
  5440. if (!attrName) {
  5441. delete this.attrs;
  5442. return;
  5443. }
  5444. if(!this.attrs){
  5445. this.attrs = {};
  5446. }
  5447. if (utils.isObject(attrName)) {
  5448. for (var a in attrName) {
  5449. if (!attrName[a]) {
  5450. delete this.attrs[a]
  5451. } else {
  5452. this.attrs[a.toLowerCase()] = attrName[a];
  5453. }
  5454. }
  5455. } else {
  5456. if (!attrVal) {
  5457. delete this.attrs[attrName]
  5458. } else {
  5459. this.attrs[attrName.toLowerCase()] = attrVal;
  5460. }
  5461. }
  5462. },
  5463. getIndex:function(){
  5464. var parent = this.parentNode;
  5465. for(var i= 0,ci;ci=parent.children[i];i++){
  5466. if(ci === this){
  5467. return i;
  5468. }
  5469. }
  5470. return -1;
  5471. },
  5472. getNodeById:function (id) {
  5473. var node;
  5474. if (this.children && this.children.length) {
  5475. for (var i = 0, ci; ci = this.children[i++];) {
  5476. if (node = getNodeById(ci, id)) {
  5477. return node;
  5478. }
  5479. }
  5480. }
  5481. },
  5482. getNodesByTagName:function (tagNames) {
  5483. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  5484. var arr = [], me = this;
  5485. utils.each(tagNames, function (tagName) {
  5486. if (me.children && me.children.length) {
  5487. for (var i = 0, ci; ci = me.children[i++];) {
  5488. getNodesByTagName(ci, tagName, arr)
  5489. }
  5490. }
  5491. });
  5492. return arr;
  5493. },
  5494. getStyle:function (name) {
  5495. var cssStyle = this.getAttr('style');
  5496. if (!cssStyle) {
  5497. return ''
  5498. }
  5499. var reg = new RegExp(name + ':([^;]+)','i');
  5500. var match = cssStyle.match(reg);
  5501. if (match && match[0]) {
  5502. return match[1]
  5503. }
  5504. return '';
  5505. },
  5506. setStyle:function (name, val) {
  5507. function exec(name, val) {
  5508. var reg = new RegExp(name + ':([^;]+;?)', 'gi');
  5509. cssStyle = cssStyle.replace(reg, '');
  5510. if (val) {
  5511. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  5512. }
  5513. }
  5514. var cssStyle = this.getAttr('style');
  5515. if (!cssStyle) {
  5516. cssStyle = '';
  5517. }
  5518. if (utils.isObject(name)) {
  5519. for (var a in name) {
  5520. exec(a, name[a])
  5521. }
  5522. } else {
  5523. exec(name, val)
  5524. }
  5525. this.setAttr('style', utils.trim(cssStyle))
  5526. },
  5527. traversal:function(fn){
  5528. if(this.children && this.children.length){
  5529. nodeTraversal(this,fn);
  5530. }
  5531. return this;
  5532. }
  5533. }
  5534. })();
  5535. //html字符串转换成uNode节点
  5536. //by zhanyi
  5537. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  5538. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  5539. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  5540. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  5541. var allowEmptyTags = {
  5542. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  5543. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  5544. };
  5545. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  5546. if(!ignoreBlank){
  5547. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  5548. //br暂时单独处理
  5549. if(b && allowEmptyTags[b.toLowerCase()]){
  5550. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  5551. }
  5552. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  5553. });
  5554. }
  5555. var uNode = UE.uNode,
  5556. needParentNode = {
  5557. 'td':'tr',
  5558. 'tr':['tbody','thead','tfoot'],
  5559. 'tbody':'table',
  5560. 'th':'tr',
  5561. 'thead':'table',
  5562. 'tfoot':'table',
  5563. 'caption':'table',
  5564. 'li':['ul', 'ol'],
  5565. 'dt':'dl',
  5566. 'dd':'dl',
  5567. 'option':'select'
  5568. },
  5569. needChild = {
  5570. 'ol':'li',
  5571. 'ul':'li'
  5572. };
  5573. function text(parent, data) {
  5574. if(needChild[parent.tagName]){
  5575. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  5576. parent.appendChild(tmpNode);
  5577. tmpNode.appendChild(uNode.createText(data));
  5578. parent = tmpNode;
  5579. }else{
  5580. parent.appendChild(uNode.createText(data));
  5581. }
  5582. }
  5583. function element(parent, tagName, htmlattr) {
  5584. var needParentTag;
  5585. if (needParentTag = needParentNode[tagName]) {
  5586. var tmpParent = parent,hasParent;
  5587. while(tmpParent.type != 'root'){
  5588. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  5589. parent = tmpParent;
  5590. hasParent = true;
  5591. break;
  5592. }
  5593. tmpParent = tmpParent.parentNode;
  5594. }
  5595. if(!hasParent){
  5596. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  5597. }
  5598. }
  5599. //按dtd处理嵌套
  5600. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  5601. // parent = parent.parentNode;
  5602. var elm = new uNode({
  5603. parentNode:parent,
  5604. type:'element',
  5605. tagName:tagName.toLowerCase(),
  5606. //是自闭合的处理一下
  5607. children:dtd.$empty[tagName] ? null : []
  5608. });
  5609. //如果属性存在,处理属性
  5610. if (htmlattr) {
  5611. var attrs = {}, match;
  5612. while (match = re_attr.exec(htmlattr)) {
  5613. attrs[match[1].toLowerCase()] = utils.unhtml(match[2] || match[3] || match[4])
  5614. }
  5615. elm.attrs = attrs;
  5616. }
  5617. parent.children.push(elm);
  5618. //如果是自闭合节点返回父亲节点
  5619. return dtd.$empty[tagName] ? parent : elm
  5620. }
  5621. function comment(parent, data) {
  5622. parent.children.push(new uNode({
  5623. type:'comment',
  5624. data:data,
  5625. parentNode:parent
  5626. }));
  5627. }
  5628. var match, currentIndex = 0, nextIndex = 0;
  5629. //设置根节点
  5630. var root = new uNode({
  5631. type:'root',
  5632. children:[]
  5633. });
  5634. var currentParent = root;
  5635. while (match = re_tag.exec(htmlstr)) {
  5636. currentIndex = match.index;
  5637. try{
  5638. if (currentIndex > nextIndex) {
  5639. //text node
  5640. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  5641. }
  5642. if (match[3]) {
  5643. //start tag
  5644. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  5645. } else if (match[1]) {
  5646. if(currentParent.type != 'root'){
  5647. var tmpParent = currentParent;
  5648. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  5649. currentParent = currentParent.parentNode;
  5650. if(currentParent.type == 'root'){
  5651. currentParent = tmpParent;
  5652. throw 'break'
  5653. }
  5654. }
  5655. //end tag
  5656. currentParent = currentParent.parentNode;
  5657. }
  5658. } else if (match[2]) {
  5659. //comment
  5660. comment(currentParent, match[2])
  5661. }
  5662. }catch(e){}
  5663. nextIndex = re_tag.lastIndex;
  5664. }
  5665. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  5666. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  5667. if (nextIndex < htmlstr.length) {
  5668. text(currentParent, htmlstr.slice(nextIndex));
  5669. }
  5670. return root;
  5671. };
  5672. /**
  5673. * @file
  5674. * @name UE.filterNode
  5675. * @short filterNode
  5676. * @desc 根据给定的规则过滤节点
  5677. * @import editor.js,core/utils.js
  5678. * @anthor zhanyi
  5679. */
  5680. var filterNode = UE.filterNode = function () {
  5681. function filterNode(node,rules){
  5682. switch (node.type) {
  5683. case 'text':
  5684. break;
  5685. case 'element':
  5686. var val;
  5687. if(val = rules[node.tagName]){
  5688. if(val === '-'){
  5689. node.parentNode.removeChild(node)
  5690. }else if(utils.isFunction(val)){
  5691. var parentNode = node.parentNode,
  5692. index = node.getIndex();
  5693. val(node);
  5694. if(node.parentNode){
  5695. if(node.children){
  5696. for(var i = 0,ci;ci=node.children[i];){
  5697. filterNode(ci,rules);
  5698. if(ci.parentNode){
  5699. i++;
  5700. }
  5701. }
  5702. }
  5703. }else{
  5704. for(var i = index,ci;ci=parentNode.children[i];){
  5705. filterNode(ci,rules);
  5706. if(ci.parentNode){
  5707. i++;
  5708. }
  5709. }
  5710. }
  5711. }else{
  5712. var attrs = val['$'];
  5713. if(attrs && node.attrs){
  5714. var tmpAttrs = {},tmpVal;
  5715. for(var a in attrs){
  5716. tmpVal = node.getAttr(a);
  5717. //todo 只先对style单独处理
  5718. if(a == 'style' && utils.isArray(attrs[a])){
  5719. var tmpCssStyle = [];
  5720. utils.each(attrs[a],function(v){
  5721. var tmp;
  5722. if(tmp = node.getStyle(v)){
  5723. tmpCssStyle.push(v + ':' + tmp);
  5724. }
  5725. });
  5726. tmpVal = tmpCssStyle.join(';')
  5727. }
  5728. if(tmpVal){
  5729. tmpAttrs[a] = tmpVal;
  5730. }
  5731. }
  5732. node.attrs = tmpAttrs;
  5733. }
  5734. if(node.children){
  5735. for(var i = 0,ci;ci=node.children[i];){
  5736. filterNode(ci,rules);
  5737. if(ci.parentNode){
  5738. i++;
  5739. }
  5740. }
  5741. }
  5742. }
  5743. }else{
  5744. //如果不在名单里扣出子节点并删除该节点,cdata除外
  5745. if(dtd.$cdata[node.tagName]){
  5746. node.parentNode.removeChild(node)
  5747. }else{
  5748. var parentNode = node.parentNode,
  5749. index = node.getIndex();
  5750. node.parentNode.removeChild(node,true);
  5751. for(var i = index,ci;ci=parentNode.children[i];){
  5752. filterNode(ci,rules);
  5753. if(ci.parentNode){
  5754. i++;
  5755. }
  5756. }
  5757. }
  5758. }
  5759. break;
  5760. case 'comment':
  5761. node.parentNode.removeChild(node)
  5762. }
  5763. }
  5764. return function(root,rules){
  5765. if(utils.isEmptyObject(rules)){
  5766. return root;
  5767. }
  5768. var val;
  5769. if(val = rules['-']){
  5770. utils.each(val.split(' '),function(k){
  5771. rules[k] = '-'
  5772. })
  5773. }
  5774. for(var i= 0,ci;ci=root.children[i];){
  5775. filterNode(ci,rules);
  5776. if(ci.parentNode){
  5777. i++;
  5778. }
  5779. }
  5780. return root;
  5781. }
  5782. }();
  5783. ///import core
  5784. ///plugin 编辑器默认的过滤转换机制
  5785. UE.plugins['defaultfilter'] = function () {
  5786. var me = this;
  5787. me.setOpt('allowDivTransToP',true);
  5788. //默认的过滤处理
  5789. //进入编辑器的内容处理
  5790. me.addInputRule(function (root) {
  5791. var allowDivTransToP = this.options.allowDivTransToP;
  5792. var val;
  5793. //进行默认的处理
  5794. root.traversal(function (node) {
  5795. if (node.type == 'element') {
  5796. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5797. if (!node.firstChild()) node.parentNode.removeChild(node);
  5798. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5799. node.parentNode.removeChild(node, true)
  5800. }
  5801. return;
  5802. }
  5803. switch (node.tagName) {
  5804. case 'style':
  5805. case 'script':
  5806. node.setAttr({
  5807. cdata_tag: node.tagName,
  5808. cdata_data: encodeURIComponent(node.innerText() || '')
  5809. });
  5810. node.tagName = 'div';
  5811. node.removeChild(node.firstChild());
  5812. break;
  5813. case 'a':
  5814. if (val = node.getAttr('href')) {
  5815. node.setAttr('_href', val)
  5816. }
  5817. break;
  5818. case 'img':
  5819. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  5820. if (val = node.getAttr('src')) {
  5821. if (/^data:/.test(val)) {
  5822. node.parentNode.removeChild(node);
  5823. break;
  5824. }
  5825. }
  5826. node.setAttr('_src', node.getAttr('src'));
  5827. break;
  5828. case 'span':
  5829. if (browser.webkit && (val = node.getStyle('white-space'))) {
  5830. if (/nowrap|normal/.test(val)) {
  5831. node.setStyle('white-space', '');
  5832. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  5833. node.parentNode.removeChild(node, true)
  5834. }
  5835. }
  5836. }
  5837. break;
  5838. case 'p':
  5839. if (val = node.getAttr('align')) {
  5840. node.setAttr('align');
  5841. node.setStyle('text-align', val)
  5842. }
  5843. //trace:3431
  5844. // var cssStyle = node.getAttr('style');
  5845. // if (cssStyle) {
  5846. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  5847. // node.setAttr('style', cssStyle)
  5848. //
  5849. // }
  5850. if (!node.firstChild()) {
  5851. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  5852. }
  5853. break;
  5854. case 'div':
  5855. if(node.getAttr('cdata_tag')){
  5856. break;
  5857. }
  5858. //针对代码这里不处理插入代码的div
  5859. val = node.getAttr('class');
  5860. if(val && /^line number\d+/.test(val)){
  5861. break;
  5862. }
  5863. if(!allowDivTransToP){
  5864. break;
  5865. }
  5866. var tmpNode, p = UE.uNode.createElement('p');
  5867. while (tmpNode = node.firstChild()) {
  5868. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  5869. p.appendChild(tmpNode);
  5870. } else {
  5871. if (p.firstChild()) {
  5872. node.parentNode.insertBefore(p, node);
  5873. p = UE.uNode.createElement('p');
  5874. } else {
  5875. node.parentNode.insertBefore(tmpNode, node);
  5876. }
  5877. }
  5878. }
  5879. if (p.firstChild()) {
  5880. node.parentNode.insertBefore(p, node);
  5881. }
  5882. node.parentNode.removeChild(node);
  5883. break;
  5884. case 'dl':
  5885. node.tagName = 'ul';
  5886. break;
  5887. case 'dt':
  5888. case 'dd':
  5889. node.tagName = 'li';
  5890. break;
  5891. case 'li':
  5892. var className = node.getAttr('class');
  5893. if (!className || !/list\-/.test(className)) {
  5894. node.setAttr()
  5895. }
  5896. var tmpNodes = node.getNodesByTagName('ol ul');
  5897. UE.utils.each(tmpNodes, function (n) {
  5898. node.parentNode.insertAfter(n, node);
  5899. });
  5900. break;
  5901. case 'td':
  5902. case 'th':
  5903. case 'caption':
  5904. if(!node.children || !node.children.length){
  5905. node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  5906. }
  5907. }
  5908. }
  5909. if(node.type == 'comment'){
  5910. node.parentNode.removeChild(node);
  5911. }
  5912. })
  5913. });
  5914. //从编辑器出去的内容处理
  5915. me.addOutputRule(function (root) {
  5916. var val;
  5917. root.traversal(function (node) {
  5918. if (node.type == 'element') {
  5919. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5920. if (!node.firstChild()) node.parentNode.removeChild(node);
  5921. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5922. node.parentNode.removeChild(node, true)
  5923. }
  5924. return;
  5925. }
  5926. switch (node.tagName) {
  5927. case 'div':
  5928. if (val = node.getAttr('cdata_tag')) {
  5929. node.tagName = val;
  5930. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  5931. node.setAttr({cdata_tag: '', cdata_data: ''});
  5932. }
  5933. break;
  5934. case 'a':
  5935. if (val = node.getAttr('_href')) {
  5936. node.setAttr({
  5937. 'href': val,
  5938. '_href': ''
  5939. })
  5940. }
  5941. break;
  5942. case 'img':
  5943. if (val = node.getAttr('_src')) {
  5944. node.setAttr({
  5945. 'src': node.getAttr('_src'),
  5946. '_src': ''
  5947. })
  5948. }
  5949. }
  5950. }
  5951. })
  5952. });
  5953. };
  5954. ///import core
  5955. /**
  5956. * @description 插入内容
  5957. * @name baidu.editor.execCommand
  5958. * @param {String} cmdName inserthtml插入内容的命令
  5959. * @param {String} html 要插入的内容
  5960. * @author zhanyi
  5961. */
  5962. UE.commands['inserthtml'] = {
  5963. execCommand: function (command,html,notNeedFilter){
  5964. var me = this,
  5965. range,
  5966. div;
  5967. if(!html){
  5968. return;
  5969. }
  5970. if(me.fireEvent('beforeinserthtml',html) === true){
  5971. return;
  5972. }
  5973. range = me.selection.getRange();
  5974. div = range.document.createElement( 'div' );
  5975. div.style.display = 'inline';
  5976. if (!notNeedFilter) {
  5977. var root = UE.htmlparser(html);
  5978. //如果给了过滤规则就先进行过滤
  5979. if(me.options.filterRules){
  5980. UE.filterNode(root,me.options.filterRules);
  5981. }
  5982. //执行默认的处理
  5983. me.filterInputRule(root);
  5984. html = root.toHtml()
  5985. }
  5986. div.innerHTML = utils.trim( html );
  5987. if ( !range.collapsed ) {
  5988. var tmpNode = range.startContainer;
  5989. if(domUtils.isFillChar(tmpNode)){
  5990. range.setStartBefore(tmpNode)
  5991. }
  5992. tmpNode = range.endContainer;
  5993. if(domUtils.isFillChar(tmpNode)){
  5994. range.setEndAfter(tmpNode)
  5995. }
  5996. range.txtToElmBoundary();
  5997. //结束边界可能放到了br的前边,要把br包含进来
  5998. // x[xxx]<br/>
  5999. if(range.endContainer && range.endContainer.nodeType == 1){
  6000. tmpNode = range.endContainer.childNodes[range.endOffset];
  6001. if(tmpNode && domUtils.isBr(tmpNode)){
  6002. range.setEndAfter(tmpNode);
  6003. }
  6004. }
  6005. if(range.startOffset == 0){
  6006. tmpNode = range.startContainer;
  6007. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  6008. tmpNode = range.endContainer;
  6009. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  6010. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  6011. range.setStart(me.body.firstChild,0).collapse(true)
  6012. }
  6013. }
  6014. }
  6015. !range.collapsed && range.deleteContents();
  6016. if(range.startContainer.nodeType == 1){
  6017. var child = range.startContainer.childNodes[range.startOffset],pre;
  6018. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  6019. range.setEnd(pre,pre.childNodes.length).collapse();
  6020. while(child.firstChild){
  6021. pre.appendChild(child.firstChild);
  6022. }
  6023. domUtils.remove(child);
  6024. }
  6025. }
  6026. }
  6027. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  6028. //如果当前位置选中了fillchar要干掉,要不会产生空行
  6029. if(range.inFillChar()){
  6030. child = range.startContainer;
  6031. if(domUtils.isFillChar(child)){
  6032. range.setStartBefore(child).collapse(true);
  6033. domUtils.remove(child);
  6034. }else if(domUtils.isFillChar(child,true)){
  6035. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  6036. range.startOffset--;
  6037. range.collapsed && range.collapse(true)
  6038. }
  6039. }
  6040. //列表单独处理
  6041. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  6042. if(li){
  6043. var next,last;
  6044. while(child = div.firstChild){
  6045. //针对hr单独处理一下先
  6046. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  6047. next = child.nextSibling;
  6048. range.insertNode( child).collapse();
  6049. last = child;
  6050. child = next;
  6051. }
  6052. if(child){
  6053. if(/^(ol|ul)$/i.test(child.tagName)){
  6054. while(child.firstChild){
  6055. last = child.firstChild;
  6056. domUtils.insertAfter(li,child.firstChild);
  6057. li = li.nextSibling;
  6058. }
  6059. domUtils.remove(child)
  6060. }else{
  6061. var tmpLi;
  6062. next = child.nextSibling;
  6063. tmpLi = me.document.createElement('li');
  6064. domUtils.insertAfter(li,tmpLi);
  6065. tmpLi.appendChild(child);
  6066. last = child;
  6067. child = next;
  6068. li = tmpLi;
  6069. }
  6070. }
  6071. }
  6072. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  6073. if(domUtils.isEmptyBlock(li)){
  6074. domUtils.remove(li)
  6075. }
  6076. if(last){
  6077. range.setStartAfter(last).collapse(true).select(true)
  6078. }
  6079. }else{
  6080. while ( child = div.firstChild ) {
  6081. if(hadBreak){
  6082. var p = me.document.createElement('p');
  6083. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  6084. nextNode = child.nextSibling;
  6085. p.appendChild(child);
  6086. child = nextNode;
  6087. }
  6088. if(p.firstChild){
  6089. child = p
  6090. }
  6091. }
  6092. range.insertNode( child );
  6093. nextNode = child.nextSibling;
  6094. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  6095. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  6096. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  6097. if(!dtd[parent.tagName][child.nodeName]){
  6098. pre = parent;
  6099. }else{
  6100. tmp = child.parentNode;
  6101. while (tmp !== parent){
  6102. pre = tmp;
  6103. tmp = tmp.parentNode;
  6104. }
  6105. }
  6106. domUtils.breakParent( child, pre || tmp );
  6107. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  6108. var pre = child.previousSibling;
  6109. domUtils.trimWhiteTextNode(pre);
  6110. if(!pre.childNodes.length){
  6111. domUtils.remove(pre);
  6112. }
  6113. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  6114. if(!browser.ie &&
  6115. (next = child.nextSibling) &&
  6116. domUtils.isBlockElm(next) &&
  6117. next.lastChild &&
  6118. !domUtils.isBr(next.lastChild)){
  6119. next.appendChild(me.document.createElement('br'));
  6120. }
  6121. hadBreak = 1;
  6122. }
  6123. }
  6124. var next = child.nextSibling;
  6125. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  6126. range.setStart(next,0).collapse(true);
  6127. break;
  6128. }
  6129. range.setEndAfter( child ).collapse();
  6130. }
  6131. child = range.startContainer;
  6132. if(nextNode && domUtils.isBr(nextNode)){
  6133. domUtils.remove(nextNode)
  6134. }
  6135. //用chrome可能有空白展位符
  6136. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  6137. if(nextNode = child.nextSibling){
  6138. domUtils.remove(child);
  6139. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  6140. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  6141. }
  6142. }else{
  6143. try{
  6144. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  6145. }catch(e){
  6146. range.setStartBefore(child);
  6147. domUtils.remove(child)
  6148. }
  6149. }
  6150. }
  6151. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  6152. try{
  6153. range.select(true);
  6154. }catch(e){}
  6155. }
  6156. setTimeout(function(){
  6157. range = me.selection.getRange();
  6158. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  6159. me.fireEvent('afterinserthtml');
  6160. },200);
  6161. }
  6162. };
  6163. ///import core
  6164. ///commands 自动排版
  6165. ///commandsName autotypeset
  6166. ///commandsTitle 自动排版
  6167. /**
  6168. * 自动排版
  6169. * @function
  6170. * @name baidu.editor.execCommands
  6171. */
  6172. UE.plugins['autotypeset'] = function(){
  6173. this.setOpt({'autotypeset':{
  6174. mergeEmptyline : true, //合并空行
  6175. removeClass : true, //去掉冗余的class
  6176. removeEmptyline : false, //去掉空行
  6177. textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  6178. imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  6179. pasteFilter : false, //根据规则过滤没事粘贴进来的内容
  6180. clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
  6181. clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
  6182. removeEmptyNode : false, // 去掉空节点
  6183. //可以去掉的标签
  6184. removeTagNames : utils.extend({div:1},dtd.$removeEmpty),
  6185. indent : false, // 行首缩进
  6186. indentValue : '2em' //行首缩进的大小
  6187. }});
  6188. var me = this,
  6189. opt = me.options.autotypeset,
  6190. remainClass = {
  6191. 'selectTdClass':1,
  6192. 'pagebreak':1,
  6193. 'anchorclass':1
  6194. },
  6195. remainTag = {
  6196. 'li':1
  6197. },
  6198. tags = {
  6199. div:1,
  6200. p:1,
  6201. //trace:2183 这些也认为是行
  6202. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  6203. span:1
  6204. },
  6205. highlightCont;
  6206. //升级了版本,但配置项目里没有autotypeset
  6207. if(!opt){
  6208. return;
  6209. }
  6210. function isLine(node,notEmpty){
  6211. if(!node || node.nodeType == 3)
  6212. return 0;
  6213. if(domUtils.isBr(node))
  6214. return 1;
  6215. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  6216. if(highlightCont && highlightCont.contains(node)
  6217. ||
  6218. node.getAttribute('pagebreak')
  6219. ){
  6220. return 0;
  6221. }
  6222. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  6223. +']','g'));
  6224. }
  6225. }
  6226. function removeNotAttributeSpan(node){
  6227. if(!node.style.cssText){
  6228. domUtils.removeAttributes(node,['style']);
  6229. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  6230. domUtils.remove(node,true);
  6231. }
  6232. }
  6233. }
  6234. function autotype(type,html){
  6235. var me = this,cont;
  6236. if(html){
  6237. if(!opt.pasteFilter){
  6238. return;
  6239. }
  6240. cont = me.document.createElement('div');
  6241. cont.innerHTML = html.html;
  6242. }else{
  6243. cont = me.document.body;
  6244. }
  6245. var nodes = domUtils.getElementsByTagName(cont,'*');
  6246. // 行首缩进,段落方向,段间距,段内间距
  6247. for(var i=0,ci;ci=nodes[i++];){
  6248. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  6249. continue;
  6250. }
  6251. //font-size
  6252. if(opt.clearFontSize && ci.style.fontSize){
  6253. domUtils.removeStyle(ci,'font-size');
  6254. removeNotAttributeSpan(ci);
  6255. }
  6256. //font-family
  6257. if(opt.clearFontFamily && ci.style.fontFamily){
  6258. domUtils.removeStyle(ci,'font-family');
  6259. removeNotAttributeSpan(ci);
  6260. }
  6261. if(isLine(ci)){
  6262. //合并空行
  6263. if(opt.mergeEmptyline ){
  6264. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  6265. while(isLine(next)){
  6266. tmpNode = next;
  6267. next = tmpNode.nextSibling;
  6268. if(isBr && (!next || next && !domUtils.isBr(next))){
  6269. break;
  6270. }
  6271. domUtils.remove(tmpNode);
  6272. }
  6273. }
  6274. //去掉空行,保留占位的空行
  6275. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  6276. if(domUtils.isBr(ci)){
  6277. next = ci.nextSibling;
  6278. if(next && !domUtils.isBr(next)){
  6279. continue;
  6280. }
  6281. }
  6282. domUtils.remove(ci);
  6283. continue;
  6284. }
  6285. }
  6286. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  6287. if(opt.indent){
  6288. ci.style.textIndent = opt.indentValue;
  6289. }
  6290. if(opt.textAlign){
  6291. ci.style.textAlign = opt.textAlign;
  6292. }
  6293. // if(opt.lineHeight)
  6294. // ci.style.lineHeight = opt.lineHeight + 'cm';
  6295. }
  6296. //去掉class,保留的class不去掉
  6297. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  6298. if(highlightCont && highlightCont.contains(ci)){
  6299. continue;
  6300. }
  6301. domUtils.removeAttributes(ci,['class']);
  6302. }
  6303. //表情不处理
  6304. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  6305. if(html){
  6306. var img = ci;
  6307. switch (opt.imageBlockLine){
  6308. case 'left':
  6309. case 'right':
  6310. case 'none':
  6311. var pN = img.parentNode,tmpNode,pre,next;
  6312. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  6313. pN = pN.parentNode;
  6314. }
  6315. tmpNode = pN;
  6316. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  6317. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  6318. pre = tmpNode.previousSibling;
  6319. next = tmpNode.nextSibling;
  6320. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  6321. pre.appendChild(tmpNode.firstChild);
  6322. while(next.firstChild){
  6323. pre.appendChild(next.firstChild);
  6324. }
  6325. domUtils.remove(tmpNode);
  6326. domUtils.remove(next);
  6327. }else{
  6328. domUtils.setStyle(tmpNode,'text-align','');
  6329. }
  6330. }
  6331. }
  6332. domUtils.setStyle(img,'float',opt.imageBlockLine);
  6333. break;
  6334. case 'center':
  6335. if(me.queryCommandValue('imagefloat') != 'center'){
  6336. pN = img.parentNode;
  6337. domUtils.setStyle(img,'float','none');
  6338. tmpNode = img;
  6339. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  6340. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  6341. tmpNode = pN;
  6342. pN = pN.parentNode;
  6343. }
  6344. var pNode = me.document.createElement('p');
  6345. domUtils.setAttributes(pNode,{
  6346. style:'text-align:center'
  6347. });
  6348. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  6349. pNode.appendChild(tmpNode);
  6350. domUtils.setStyle(tmpNode,'float','');
  6351. }
  6352. }
  6353. }else{
  6354. var range = me.selection.getRange();
  6355. range.selectNode(ci).select();
  6356. me.execCommand('imagefloat',opt.imageBlockLine);
  6357. }
  6358. }
  6359. //去掉冗余的标签
  6360. if(opt.removeEmptyNode){
  6361. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  6362. domUtils.remove(ci);
  6363. }
  6364. }
  6365. }
  6366. if(html){
  6367. html.html = cont.innerHTML;
  6368. }
  6369. }
  6370. if(opt.pasteFilter){
  6371. me.addListener('beforepaste',autotype);
  6372. }
  6373. me.commands['autotypeset'] = {
  6374. execCommand:function () {
  6375. me.removeListener('beforepaste',autotype);
  6376. if(opt.pasteFilter){
  6377. me.addListener('beforepaste',autotype);
  6378. }
  6379. autotype.call(me)
  6380. }
  6381. };
  6382. };
  6383. ///import core
  6384. ///commands 自动提交
  6385. ///commandsName autosubmit
  6386. ///commandsTitle 自动提交
  6387. UE.plugins['autosubmit'] = function(){
  6388. var me = this;
  6389. me.commands['autosubmit'] = {
  6390. execCommand:function () {
  6391. var me=this,
  6392. form = domUtils.findParentByTagName(me.iframe,"form", false);
  6393. if (form) {
  6394. if(me.fireEvent("beforesubmit")===false){
  6395. return;
  6396. }
  6397. me.sync();
  6398. form.submit();
  6399. }
  6400. }
  6401. };
  6402. //快捷键
  6403. me.addshortcutkey({
  6404. "autosubmit" : "ctrl+13" //手动提交
  6405. });
  6406. };
  6407. ///import core
  6408. ///commands 插入背景
  6409. ///commandsName background
  6410. ///commandsTitle 插入背景
  6411. ///commandsDialog dialogs\background
  6412. UE.plugins['background'] = function(){
  6413. var me = this;
  6414. me.addListener("getAllHtml",function(type,headHtml){
  6415. var body = this.body,
  6416. su = domUtils.getComputedStyle(body,"background-image"),
  6417. url="";
  6418. if(su.indexOf(me.options.imagePath)>0){
  6419. url = su.substring(su.indexOf(me.options.imagePath),su.length-1).replace(/"|\(|\)/ig,"");
  6420. }else{
  6421. url = su!="none" ? su.replace(/url\("?|"?\)/ig,""):"";
  6422. }
  6423. var html = '<style type="text/css">body{';
  6424. var bgObj = {
  6425. "background-color" : domUtils.getComputedStyle(body,"background-color")||"#ffffff",
  6426. 'background-image' : url ? 'url('+url+')' : '',
  6427. 'background-repeat':domUtils.getComputedStyle(body,"background-repeat")||"",
  6428. 'background-position': browser.ie?(domUtils.getComputedStyle(body,"background-position-x")+" "+domUtils.getComputedStyle(body,"background-position-y")):domUtils.getComputedStyle(body,"background-position"),
  6429. 'height':domUtils.getComputedStyle(body,"height")
  6430. };
  6431. for ( var name in bgObj ) {
  6432. if ( bgObj.hasOwnProperty( name ) ) {
  6433. html += name+":"+bgObj[name]+";";
  6434. }
  6435. }
  6436. html += '}</style> ';
  6437. headHtml.push(html);
  6438. });
  6439. }
  6440. ///import core
  6441. ///import plugins\inserthtml.js
  6442. ///commands 插入图片,操作图片的对齐方式
  6443. ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter
  6444. ///commandsTitle 图片,默认,居左,居右,居中
  6445. ///commandsDialog dialogs\image
  6446. /**
  6447. * Created by .
  6448. * User: zhanyi
  6449. * for image
  6450. */
  6451. UE.commands['imagefloat'] = {
  6452. execCommand:function (cmd, align) {
  6453. var me = this,
  6454. range = me.selection.getRange();
  6455. if (!range.collapsed) {
  6456. var img = range.getClosedNode();
  6457. if (img && img.tagName == 'IMG') {
  6458. switch (align) {
  6459. case 'left':
  6460. case 'right':
  6461. case 'none':
  6462. var pN = img.parentNode, tmpNode, pre, next;
  6463. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  6464. pN = pN.parentNode;
  6465. }
  6466. tmpNode = pN;
  6467. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  6468. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  6469. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  6470. }) == 1) {
  6471. pre = tmpNode.previousSibling;
  6472. next = tmpNode.nextSibling;
  6473. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  6474. pre.appendChild(tmpNode.firstChild);
  6475. while (next.firstChild) {
  6476. pre.appendChild(next.firstChild);
  6477. }
  6478. domUtils.remove(tmpNode);
  6479. domUtils.remove(next);
  6480. } else {
  6481. domUtils.setStyle(tmpNode, 'text-align', '');
  6482. }
  6483. }
  6484. range.selectNode(img).select();
  6485. }
  6486. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  6487. if(align == 'none'){
  6488. domUtils.removeAttributes(img,'align');
  6489. }
  6490. break;
  6491. case 'center':
  6492. if (me.queryCommandValue('imagefloat') != 'center') {
  6493. pN = img.parentNode;
  6494. domUtils.setStyle(img, 'float', '');
  6495. domUtils.removeAttributes(img,'align');
  6496. tmpNode = img;
  6497. while (pN && domUtils.getChildCount(pN, function (node) {
  6498. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  6499. }) == 1
  6500. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  6501. tmpNode = pN;
  6502. pN = pN.parentNode;
  6503. }
  6504. range.setStartBefore(tmpNode).setCursor(false);
  6505. pN = me.document.createElement('div');
  6506. pN.appendChild(tmpNode);
  6507. domUtils.setStyle(tmpNode, 'float', '');
  6508. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  6509. tmpNode = me.document.getElementById('_img_parent_tmp');
  6510. tmpNode.removeAttribute('id');
  6511. tmpNode = tmpNode.firstChild;
  6512. range.selectNode(tmpNode).select();
  6513. //去掉后边多余的元素
  6514. next = tmpNode.parentNode.nextSibling;
  6515. if (next && domUtils.isEmptyNode(next)) {
  6516. domUtils.remove(next);
  6517. }
  6518. }
  6519. break;
  6520. }
  6521. }
  6522. }
  6523. },
  6524. queryCommandValue:function () {
  6525. var range = this.selection.getRange(),
  6526. startNode, floatStyle;
  6527. if (range.collapsed) {
  6528. return 'none';
  6529. }
  6530. startNode = range.getClosedNode();
  6531. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  6532. floatStyle = startNode.getAttribute('align')||domUtils.getComputedStyle(startNode, 'float');
  6533. if (floatStyle == 'none') {
  6534. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  6535. }
  6536. return {
  6537. left:1,
  6538. right:1,
  6539. center:1
  6540. }[floatStyle] ? floatStyle : 'none';
  6541. }
  6542. return 'none';
  6543. },
  6544. queryCommandState:function () {
  6545. var range = this.selection.getRange(),
  6546. startNode;
  6547. if (range.collapsed) return -1;
  6548. startNode = range.getClosedNode();
  6549. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  6550. return 0;
  6551. }
  6552. return -1;
  6553. }
  6554. };
  6555. UE.commands['insertimage'] = {
  6556. execCommand:function (cmd, opt) {
  6557. opt = utils.isArray(opt) ? opt : [opt];
  6558. if (!opt.length) {
  6559. return;
  6560. }
  6561. var me = this,
  6562. range = me.selection.getRange(),
  6563. img = range.getClosedNode();
  6564. if (img && /img/i.test(img.tagName) && img.className != "edui-faked-video" && !img.getAttribute("word_img")) {
  6565. var first = opt.shift();
  6566. var floatStyle = first['floatStyle'];
  6567. delete first['floatStyle'];
  6568. //// img.style.border = (first.border||0) +"px solid #000";
  6569. //// img.style.margin = (first.margin||0) +"px";
  6570. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  6571. domUtils.setAttributes(img, first);
  6572. me.execCommand('imagefloat', floatStyle);
  6573. if (opt.length > 0) {
  6574. range.setStartAfter(img).setCursor(false, true);
  6575. me.execCommand('insertimage', opt);
  6576. }
  6577. } else {
  6578. var html = [], str = '', ci;
  6579. ci = opt[0];
  6580. if (opt.length == 1) {
  6581. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  6582. (ci.width ? 'width="' + ci.width + '" ' : '') +
  6583. (ci.height ? ' height="' + ci.height + '" ' : '') +
  6584. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  6585. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  6586. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  6587. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  6588. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  6589. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  6590. if (ci['floatStyle'] == 'center') {
  6591. str = '<p style="text-align: center">' + str + '</p>';
  6592. }
  6593. html.push(str);
  6594. } else {
  6595. for (var i = 0; ci = opt[i++];) {
  6596. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  6597. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  6598. (ci.height ? ' height="' + ci.height + '" ' : '') +
  6599. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  6600. (ci.border || '') + '" ' +
  6601. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  6602. html.push(str);
  6603. }
  6604. }
  6605. me.execCommand('insertHtml', html.join(''));
  6606. }
  6607. }
  6608. };
  6609. ///import core
  6610. ///commands 段落格式,居左,居右,居中,两端对齐
  6611. ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify
  6612. ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐
  6613. /**
  6614. * @description 居左右中
  6615. * @name baidu.editor.execCommand
  6616. * @param {String} cmdName justify执行对齐方式的命令
  6617. * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐
  6618. * @author zhanyi
  6619. */
  6620. UE.plugins['justify']=function(){
  6621. var me=this,
  6622. block = domUtils.isBlockElm,
  6623. defaultValue = {
  6624. left:1,
  6625. right:1,
  6626. center:1,
  6627. justify:1
  6628. },
  6629. doJustify = function (range, style) {
  6630. var bookmark = range.createBookmark(),
  6631. filterFn = function (node) {
  6632. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  6633. };
  6634. range.enlarge(true);
  6635. var bookmark2 = range.createBookmark(),
  6636. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  6637. tmpRange = range.cloneRange(),
  6638. tmpNode;
  6639. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  6640. if (current.nodeType == 3 || !block(current)) {
  6641. tmpRange.setStartBefore(current);
  6642. while (current && current !== bookmark2.end && !block(current)) {
  6643. tmpNode = current;
  6644. current = domUtils.getNextDomNode(current, false, null, function (node) {
  6645. return !block(node);
  6646. });
  6647. }
  6648. tmpRange.setEndAfter(tmpNode);
  6649. var common = tmpRange.getCommonAncestor();
  6650. if (!domUtils.isBody(common) && block(common)) {
  6651. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  6652. current = common;
  6653. } else {
  6654. var p = range.document.createElement('p');
  6655. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  6656. var frag = tmpRange.extractContents();
  6657. p.appendChild(frag);
  6658. tmpRange.insertNode(p);
  6659. current = p;
  6660. }
  6661. current = domUtils.getNextDomNode(current, false, filterFn);
  6662. } else {
  6663. current = domUtils.getNextDomNode(current, true, filterFn);
  6664. }
  6665. }
  6666. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  6667. };
  6668. UE.commands['justify'] = {
  6669. execCommand:function (cmdName, align) {
  6670. var range = this.selection.getRange(),
  6671. txt;
  6672. //闭合时单独处理
  6673. if (range.collapsed) {
  6674. txt = this.document.createTextNode('p');
  6675. range.insertNode(txt);
  6676. }
  6677. doJustify(range, align);
  6678. if (txt) {
  6679. range.setStartBefore(txt).collapse(true);
  6680. domUtils.remove(txt);
  6681. }
  6682. range.select();
  6683. return true;
  6684. },
  6685. queryCommandValue:function () {
  6686. var startNode = this.selection.getStart(),
  6687. value = domUtils.getComputedStyle(startNode, 'text-align');
  6688. return defaultValue[value] ? value : 'left';
  6689. },
  6690. queryCommandState:function () {
  6691. var start = this.selection.getStart(),
  6692. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  6693. return cell? -1:0;
  6694. }
  6695. };
  6696. };
  6697. ///import core
  6698. ///import plugins\removeformat.js
  6699. ///commands 字体颜色,背景色,字号,字体,下划线,删除线
  6700. ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
  6701. ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线
  6702. /**
  6703. * @description 字体
  6704. * @name baidu.editor.execCommand
  6705. * @param {String} cmdName 执行的功能名称
  6706. * @param {String} value 传入的值
  6707. */
  6708. UE.plugins['font'] = function () {
  6709. var me = this,
  6710. fonts = {
  6711. 'forecolor': 'color',
  6712. 'backcolor': 'background-color',
  6713. 'fontsize': 'font-size',
  6714. 'fontfamily': 'font-family',
  6715. 'underline': 'text-decoration',
  6716. 'strikethrough': 'text-decoration',
  6717. 'fontborder': 'border'
  6718. },
  6719. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  6720. needSetChild = {
  6721. 'forecolor': 'color',
  6722. 'backcolor': 'background-color',
  6723. 'fontsize': 'font-size',
  6724. 'fontfamily': 'font-family'
  6725. };
  6726. me.setOpt({
  6727. 'fontfamily': [
  6728. { name: 'songti', val: '宋体,SimSun'},
  6729. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  6730. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  6731. { name: 'heiti', val: '黑体, SimHei'},
  6732. { name: 'lishu', val: '隶书, SimLi'},
  6733. { name: 'andaleMono', val: 'andale mono'},
  6734. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  6735. { name: 'arialBlack', val: 'arial black,avant garde'},
  6736. { name: 'comicSansMs', val: 'comic sans ms'},
  6737. { name: 'impact', val: 'impact,chicago'},
  6738. { name: 'timesNewRoman', val: 'times new roman'}
  6739. ],
  6740. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  6741. });
  6742. function mergeWithParent(node){
  6743. var parent;
  6744. while(parent = node.parentNode){
  6745. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  6746. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  6747. }) == 1) {
  6748. parent.style.cssText += node.style.cssText;
  6749. domUtils.remove(node,true);
  6750. node = parent;
  6751. }else{
  6752. break;
  6753. }
  6754. }
  6755. }
  6756. function mergeChild(rng,cmdName,value){
  6757. if(needSetChild[cmdName]){
  6758. rng.adjustmentBoundary();
  6759. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  6760. var start = rng.startContainer.childNodes[rng.startOffset];
  6761. if(start && domUtils.isTagNode(start,'span')){
  6762. var bk = rng.createBookmark();
  6763. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  6764. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  6765. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  6766. return;
  6767. }
  6768. domUtils.removeStyle(span,needSetChild[cmdName]);
  6769. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  6770. domUtils.remove(span,true)
  6771. }
  6772. });
  6773. rng.moveToBookmark(bk)
  6774. }
  6775. }
  6776. }
  6777. }
  6778. function mergesibling(rng,cmdName,value) {
  6779. var collapsed = rng.collapsed,
  6780. bk = rng.createBookmark(), common;
  6781. if (collapsed) {
  6782. common = bk.start.parentNode;
  6783. while (dtd.$inline[common.tagName]) {
  6784. common = common.parentNode;
  6785. }
  6786. } else {
  6787. common = domUtils.getCommonAncestor(bk.start, bk.end);
  6788. }
  6789. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  6790. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  6791. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  6792. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  6793. domUtils.remove(span, true);
  6794. }else{
  6795. domUtils.removeStyle(span,'border');
  6796. }
  6797. return
  6798. }
  6799. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  6800. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  6801. }
  6802. if(!(cmdName=='fontborder' && value=='none')){
  6803. var next = span.nextSibling;
  6804. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  6805. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  6806. span.appendChild(next);
  6807. next = span.nextSibling;
  6808. continue;
  6809. }
  6810. if (next.style.cssText == span.style.cssText) {
  6811. domUtils.moveChild(next, span);
  6812. domUtils.remove(next);
  6813. }
  6814. if (span.nextSibling === next)
  6815. break;
  6816. next = span.nextSibling;
  6817. }
  6818. }
  6819. mergeWithParent(span);
  6820. if(browser.ie && browser.version > 8 ){
  6821. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  6822. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  6823. if(parent && !/background-color/.test(span.style.cssText)){
  6824. span.style.backgroundColor = parent.style.backgroundColor;
  6825. }
  6826. }
  6827. });
  6828. rng.moveToBookmark(bk);
  6829. mergeChild(rng,cmdName,value)
  6830. }
  6831. me.addInputRule(function (root) {
  6832. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  6833. if (node.tagName == 'font') {
  6834. var cssStyle = [];
  6835. for (var p in node.attrs) {
  6836. switch (p) {
  6837. case 'size':
  6838. cssStyle.push('font-size:' + node.attrs[p] + 'px');
  6839. break;
  6840. case 'color':
  6841. cssStyle.push('color:' + node.attrs[p]);
  6842. break;
  6843. case 'face':
  6844. cssStyle.push('font-family:' + node.attrs[p]);
  6845. break;
  6846. case 'style':
  6847. cssStyle.push(node.attrs[p]);
  6848. }
  6849. }
  6850. node.attrs = {
  6851. 'style': cssStyle.join(';')
  6852. };
  6853. } else {
  6854. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  6855. node.attrs = {
  6856. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  6857. }
  6858. }
  6859. node.tagName = 'span';
  6860. });
  6861. // utils.each(root.getNodesByTagName('span'), function (node) {
  6862. // var val;
  6863. // if(val = node.getAttr('class')){
  6864. // if(/fontstrikethrough/.test(val)){
  6865. // node.setStyle('text-decoration','line-through');
  6866. // if(node.attrs['class']){
  6867. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  6868. // }else{
  6869. // node.setAttr('class')
  6870. // }
  6871. // }
  6872. // if(/fontborder/.test(val)){
  6873. // node.setStyle('border','1px solid #000');
  6874. // if(node.attrs['class']){
  6875. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  6876. // }else{
  6877. // node.setAttr('class')
  6878. // }
  6879. // }
  6880. // }
  6881. // });
  6882. });
  6883. // me.addOutputRule(function(root){
  6884. // utils.each(root.getNodesByTagName('span'), function (node) {
  6885. // var val;
  6886. // if(val = node.getStyle('text-decoration')){
  6887. // if(/line-through/.test(val)){
  6888. // if(node.attrs['class']){
  6889. // node.attrs['class'] += ' fontstrikethrough';
  6890. // }else{
  6891. // node.setAttr('class','fontstrikethrough')
  6892. // }
  6893. // }
  6894. //
  6895. // node.setStyle('text-decoration')
  6896. // }
  6897. // if(val = node.getStyle('border')){
  6898. // if(/1px/.test(val) && /solid/.test(val)){
  6899. // if(node.attrs['class']){
  6900. // node.attrs['class'] += ' fontborder';
  6901. //
  6902. // }else{
  6903. // node.setAttr('class','fontborder')
  6904. // }
  6905. // }
  6906. // node.setStyle('border')
  6907. //
  6908. // }
  6909. // });
  6910. // });
  6911. for (var p in fonts) {
  6912. (function (cmd, style) {
  6913. UE.commands[cmd] = {
  6914. execCommand: function (cmdName, value) {
  6915. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  6916. cmdName == 'fontborder' ? '1px solid #000' :
  6917. 'line-through');
  6918. var me = this,
  6919. range = this.selection.getRange(),
  6920. text;
  6921. if (value == 'default') {
  6922. if (range.collapsed) {
  6923. text = me.document.createTextNode('font');
  6924. range.insertNode(text).select();
  6925. }
  6926. me.execCommand('removeFormat', 'span,a', style);
  6927. if (text) {
  6928. range.setStartBefore(text).collapse(true);
  6929. domUtils.remove(text);
  6930. }
  6931. mergesibling(range,cmdName,value);
  6932. range.select()
  6933. } else {
  6934. if (!range.collapsed) {
  6935. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  6936. me.execCommand('removeFormat', 'span,a', style);
  6937. }
  6938. range = me.selection.getRange();
  6939. range.applyInlineStyle('span', {'style': style + ':' + value});
  6940. mergesibling(range, cmdName,value);
  6941. range.select();
  6942. } else {
  6943. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  6944. text = me.document.createTextNode('font');
  6945. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  6946. //for ie hack when enter
  6947. range.insertNode(text);
  6948. if (needCmd[cmd]) {
  6949. range.selectNode(text).select();
  6950. me.execCommand('removeFormat', 'span,a', style, null);
  6951. span = domUtils.findParentByTagName(text, 'span', true);
  6952. range.setStartBefore(text);
  6953. }
  6954. span && (span.style.cssText += ';' + style + ':' + value);
  6955. range.collapse(true).select();
  6956. } else {
  6957. range.insertNode(text);
  6958. range.selectNode(text).select();
  6959. span = range.document.createElement('span');
  6960. if (needCmd[cmd]) {
  6961. //a标签内的不处理跳过
  6962. if (domUtils.findParentByTagName(text, 'a', true)) {
  6963. range.setStartBefore(text).setCursor();
  6964. domUtils.remove(text);
  6965. return;
  6966. }
  6967. me.execCommand('removeFormat', 'span,a', style);
  6968. }
  6969. span.style.cssText = style + ':' + value;
  6970. text.parentNode.insertBefore(span, text);
  6971. //修复,span套span 但样式不继承的问题
  6972. if (!browser.ie || browser.ie && browser.version == 9) {
  6973. var spanParent = span.parentNode;
  6974. while (!domUtils.isBlockElm(spanParent)) {
  6975. if (spanParent.tagName == 'SPAN') {
  6976. //opera合并style不会加入";"
  6977. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  6978. }
  6979. spanParent = spanParent.parentNode;
  6980. }
  6981. }
  6982. if (opera) {
  6983. setTimeout(function () {
  6984. range.setStart(span, 0).collapse(true);
  6985. mergesibling(range, cmdName,value);
  6986. range.select();
  6987. });
  6988. } else {
  6989. range.setStart(span, 0).collapse(true);
  6990. mergesibling(range,cmdName,value);
  6991. range.select();
  6992. }
  6993. //trace:981
  6994. //domUtils.mergeToParent(span)
  6995. }
  6996. domUtils.remove(text);
  6997. }
  6998. }
  6999. return true;
  7000. },
  7001. queryCommandValue: function (cmdName) {
  7002. var startNode = this.selection.getStart();
  7003. //trace:946
  7004. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  7005. var tmpNode = startNode, value;
  7006. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  7007. if (tmpNode.nodeType == 1) {
  7008. value = domUtils.getComputedStyle(tmpNode, style);
  7009. if (value != 'none') {
  7010. return value;
  7011. }
  7012. }
  7013. tmpNode = tmpNode.parentNode;
  7014. }
  7015. return 'none';
  7016. }
  7017. if (cmdName == 'fontborder') {
  7018. var tmp = startNode, val;
  7019. while (tmp && dtd.$inline[tmp.tagName]) {
  7020. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  7021. if (/1px/.test(val) && /solid/.test(val)) {
  7022. return val;
  7023. }
  7024. }
  7025. tmp = tmp.parentNode;
  7026. }
  7027. return ''
  7028. }
  7029. if( cmdName == 'FontSize' ) {
  7030. var styleVal = domUtils.getComputedStyle(startNode, style),
  7031. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  7032. if( tmp ) {
  7033. return Math.floor( tmp[1] ) + tmp[2];
  7034. }
  7035. return styleVal;
  7036. }
  7037. return domUtils.getComputedStyle(startNode, style);
  7038. },
  7039. queryCommandState: function (cmdName) {
  7040. if (!needCmd[cmdName])
  7041. return 0;
  7042. var val = this.queryCommandValue(cmdName);
  7043. if (cmdName == 'fontborder') {
  7044. return /1px/.test(val) && /solid/.test(val)
  7045. } else {
  7046. return val == (cmdName == 'underline' ?
  7047. 'underline' : 'line-through');
  7048. }
  7049. }
  7050. };
  7051. })(p, fonts[p]);
  7052. }
  7053. };
  7054. ///import core
  7055. ///commands 超链接,取消链接
  7056. ///commandsName Link,Unlink
  7057. ///commandsTitle 超链接,取消链接
  7058. ///commandsDialog dialogs\link
  7059. /**
  7060. * 超链接
  7061. * @function
  7062. * @name baidu.editor.execCommand
  7063. * @param {String} cmdName link插入超链接
  7064. * @param {Object} options url地址,title标题,target是否打开新页
  7065. * @author zhanyi
  7066. */
  7067. /**
  7068. * 取消链接
  7069. * @function
  7070. * @name baidu.editor.execCommand
  7071. * @param {String} cmdName unlink取消链接
  7072. * @author zhanyi
  7073. */
  7074. UE.plugins['link'] = function(){
  7075. function optimize( range ) {
  7076. var start = range.startContainer,end = range.endContainer;
  7077. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  7078. range.setStartBefore( start );
  7079. }
  7080. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  7081. range.setEndAfter( end );
  7082. }
  7083. }
  7084. UE.commands['unlink'] = {
  7085. execCommand : function() {
  7086. var range = this.selection.getRange(),
  7087. bookmark;
  7088. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  7089. return;
  7090. }
  7091. bookmark = range.createBookmark();
  7092. optimize( range );
  7093. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  7094. },
  7095. queryCommandState : function(){
  7096. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  7097. }
  7098. };
  7099. function doLink(range,opt,me){
  7100. var rngClone = range.cloneRange(),
  7101. link = me.queryCommandValue('link');
  7102. optimize( range = range.adjustmentBoundary() );
  7103. var start = range.startContainer;
  7104. if(start.nodeType == 1 && link){
  7105. start = start.childNodes[range.startOffset];
  7106. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  7107. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  7108. }
  7109. }
  7110. if( !rngClone.collapsed || link){
  7111. range.removeInlineStyle( 'a' );
  7112. rngClone = range.cloneRange();
  7113. }
  7114. if ( rngClone.collapsed ) {
  7115. var a = range.document.createElement( 'a'),
  7116. text = '';
  7117. if(opt.textValue){
  7118. text = utils.html(opt.textValue);
  7119. delete opt.textValue;
  7120. }else{
  7121. text = utils.html(opt.href);
  7122. }
  7123. domUtils.setAttributes( a, opt );
  7124. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  7125. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  7126. range.setStartAfter(start).collapse(true);
  7127. }
  7128. a[browser.ie ? 'innerText' : 'textContent'] = text;
  7129. range.insertNode(a).selectNode( a );
  7130. } else {
  7131. range.applyInlineStyle( 'a', opt );
  7132. }
  7133. }
  7134. UE.commands['link'] = {
  7135. execCommand : function( cmdName, opt ) {
  7136. var range;
  7137. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  7138. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  7139. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  7140. doLink(range=this.selection.getRange(),opt,this);
  7141. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  7142. range.collapse().select(true);
  7143. },
  7144. queryCommandValue : function() {
  7145. var range = this.selection.getRange(),
  7146. node;
  7147. if ( range.collapsed ) {
  7148. // node = this.selection.getStart();
  7149. //在ie下getstart()取值偏上了
  7150. node = range.startContainer;
  7151. node = node.nodeType == 1 ? node : node.parentNode;
  7152. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  7153. return node;
  7154. }
  7155. } else {
  7156. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  7157. range.shrinkBoundary();
  7158. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  7159. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  7160. common = range.getCommonAncestor();
  7161. node = domUtils.findParentByTagName( common, 'a', true );
  7162. if ( !node && common.nodeType == 1){
  7163. var as = common.getElementsByTagName( 'a' ),
  7164. ps,pe;
  7165. for ( var i = 0,ci; ci = as[i++]; ) {
  7166. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  7167. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  7168. &&
  7169. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  7170. ) {
  7171. node = ci;
  7172. break;
  7173. }
  7174. }
  7175. }
  7176. return node;
  7177. }
  7178. },
  7179. queryCommandState : function() {
  7180. //判断如果是视频的话连接不可用
  7181. //fix 853
  7182. var img = this.selection.getRange().getClosedNode(),
  7183. flag = img && (img.className == "edui-faked-video");
  7184. return flag ? -1 : 0;
  7185. }
  7186. };
  7187. };
  7188. ///import core
  7189. ///import plugins\inserthtml.js
  7190. ///commands 插入框架
  7191. ///commandsName InsertFrame
  7192. ///commandsTitle 插入Iframe
  7193. ///commandsDialog dialogs\insertframe
  7194. UE.plugins['insertframe'] = function() {
  7195. var me =this;
  7196. function deleteIframe(){
  7197. me._iframe && delete me._iframe;
  7198. }
  7199. me.addListener("selectionchange",function(){
  7200. deleteIframe();
  7201. });
  7202. };
  7203. ///import core
  7204. ///commands 涂鸦
  7205. ///commandsName Scrawl
  7206. ///commandsTitle 涂鸦
  7207. ///commandsDialog dialogs\scrawl
  7208. UE.commands['scrawl'] = {
  7209. queryCommandState : function(){
  7210. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  7211. }
  7212. };
  7213. ///import core
  7214. ///commands 清除格式
  7215. ///commandsName RemoveFormat
  7216. ///commandsTitle 清除格式
  7217. /**
  7218. * @description 清除格式
  7219. * @name baidu.editor.execCommand
  7220. * @param {String} cmdName removeformat清除格式命令
  7221. * @param {String} tags 以逗号隔开的标签。如:span,a
  7222. * @param {String} style 样式
  7223. * @param {String} attrs 属性
  7224. * @param {String} notIncluedA 是否把a标签切开
  7225. * @author zhanyi
  7226. */
  7227. UE.plugins['removeformat'] = function(){
  7228. var me = this;
  7229. me.setOpt({
  7230. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  7231. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  7232. });
  7233. me.commands['removeformat'] = {
  7234. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  7235. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  7236. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  7237. range = new dom.Range( this.document ),
  7238. bookmark,node,parent,
  7239. filter = function( node ) {
  7240. return node.nodeType == 1;
  7241. };
  7242. function isRedundantSpan (node) {
  7243. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  7244. return 0;
  7245. }
  7246. if (browser.ie) {
  7247. //ie 下判断实效,所以只能简单用style来判断
  7248. //return node.style.cssText == '' ? 1 : 0;
  7249. var attrs = node.attributes;
  7250. if ( attrs.length ) {
  7251. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  7252. if ( attrs[i].specified ) {
  7253. return 0;
  7254. }
  7255. }
  7256. return 1;
  7257. }
  7258. }
  7259. return !node.attributes.length;
  7260. }
  7261. function doRemove( range ) {
  7262. var bookmark1 = range.createBookmark();
  7263. if ( range.collapsed ) {
  7264. range.enlarge( true );
  7265. }
  7266. //不能把a标签切了
  7267. if(!notIncludeA){
  7268. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  7269. if(aNode){
  7270. range.setStartBefore(aNode);
  7271. }
  7272. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  7273. if(aNode){
  7274. range.setEndAfter(aNode);
  7275. }
  7276. }
  7277. bookmark = range.createBookmark();
  7278. node = bookmark.start;
  7279. //切开始
  7280. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7281. domUtils.breakParent( node, parent );
  7282. domUtils.clearEmptySibling( node );
  7283. }
  7284. if ( bookmark.end ) {
  7285. //切结束
  7286. node = bookmark.end;
  7287. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7288. domUtils.breakParent( node, parent );
  7289. domUtils.clearEmptySibling( node );
  7290. }
  7291. //开始去除样式
  7292. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  7293. next;
  7294. while ( current ) {
  7295. if ( current == bookmark.end ) {
  7296. break;
  7297. }
  7298. next = domUtils.getNextDomNode( current, true, filter );
  7299. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  7300. if ( tagReg.test( current.tagName ) ) {
  7301. if ( style ) {
  7302. domUtils.removeStyle( current, style );
  7303. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  7304. domUtils.remove( current, true );
  7305. }
  7306. } else {
  7307. domUtils.remove( current, true );
  7308. }
  7309. } else {
  7310. //trace:939 不能把list上的样式去掉
  7311. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  7312. domUtils.removeAttributes( current, removeFormatAttributes );
  7313. if ( isRedundantSpan( current ) ){
  7314. domUtils.remove( current, true );
  7315. }
  7316. }
  7317. }
  7318. }
  7319. current = next;
  7320. }
  7321. }
  7322. //trace:1035
  7323. //trace:1096 不能把td上的样式去掉,比如边框
  7324. var pN = bookmark.start.parentNode;
  7325. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  7326. domUtils.removeAttributes( pN,removeFormatAttributes );
  7327. }
  7328. pN = bookmark.end.parentNode;
  7329. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  7330. domUtils.removeAttributes( pN,removeFormatAttributes );
  7331. }
  7332. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  7333. //清除冗余的代码 <b><bookmark></b>
  7334. var node = range.startContainer,
  7335. tmp,
  7336. collapsed = range.collapsed;
  7337. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7338. tmp = node.parentNode;
  7339. range.setStartBefore(node);
  7340. //trace:937
  7341. //更新结束边界
  7342. if(range.startContainer === range.endContainer){
  7343. range.endOffset--;
  7344. }
  7345. domUtils.remove(node);
  7346. node = tmp;
  7347. }
  7348. if(!collapsed){
  7349. node = range.endContainer;
  7350. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7351. tmp = node.parentNode;
  7352. range.setEndBefore(node);
  7353. domUtils.remove(node);
  7354. node = tmp;
  7355. }
  7356. }
  7357. }
  7358. range = this.selection.getRange();
  7359. doRemove( range );
  7360. range.select();
  7361. }
  7362. };
  7363. };
  7364. ///import core
  7365. ///commands 引用
  7366. ///commandsName BlockQuote
  7367. ///commandsTitle 引用
  7368. /**
  7369. *
  7370. * 引用模块实现
  7371. * @function
  7372. * @name baidu.editor.execCommand
  7373. * @param {String} cmdName blockquote引用
  7374. */
  7375. UE.plugins['blockquote'] = function(){
  7376. var me = this;
  7377. function getObj(editor){
  7378. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  7379. }
  7380. me.commands['blockquote'] = {
  7381. execCommand : function( cmdName, attrs ) {
  7382. var range = this.selection.getRange(),
  7383. obj = getObj(this),
  7384. blockquote = dtd.blockquote,
  7385. bookmark = range.createBookmark();
  7386. if ( obj ) {
  7387. var start = range.startContainer,
  7388. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  7389. end = range.endContainer,
  7390. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  7391. //处理一下li
  7392. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  7393. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  7394. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  7395. domUtils.remove(obj,true);
  7396. }else{
  7397. domUtils.breakParent(startBlock,obj);
  7398. }
  7399. if(startBlock !== endBlock){
  7400. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  7401. if(obj){
  7402. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  7403. obj.parentNode && domUtils.remove(obj,true);
  7404. }else{
  7405. domUtils.breakParent(endBlock,obj);
  7406. }
  7407. }
  7408. }
  7409. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  7410. for(var i=0,bi;bi=blockquotes[i++];){
  7411. if(!bi.childNodes.length){
  7412. domUtils.remove(bi);
  7413. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  7414. domUtils.remove(bi,true);
  7415. }
  7416. }
  7417. } else {
  7418. var tmpRange = range.cloneRange(),
  7419. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  7420. preNode = node,
  7421. doEnd = 1;
  7422. //调整开始
  7423. while ( 1 ) {
  7424. if ( domUtils.isBody(node) ) {
  7425. if ( preNode !== node ) {
  7426. if ( range.collapsed ) {
  7427. tmpRange.selectNode( preNode );
  7428. doEnd = 0;
  7429. } else {
  7430. tmpRange.setStartBefore( preNode );
  7431. }
  7432. }else{
  7433. tmpRange.setStart(node,0);
  7434. }
  7435. break;
  7436. }
  7437. if ( !blockquote[node.tagName] ) {
  7438. if ( range.collapsed ) {
  7439. tmpRange.selectNode( preNode );
  7440. } else{
  7441. tmpRange.setStartBefore( preNode);
  7442. }
  7443. break;
  7444. }
  7445. preNode = node;
  7446. node = node.parentNode;
  7447. }
  7448. //调整结束
  7449. if ( doEnd ) {
  7450. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  7451. while ( 1 ) {
  7452. if ( domUtils.isBody( node ) ) {
  7453. if ( preNode !== node ) {
  7454. tmpRange.setEndAfter( preNode );
  7455. } else {
  7456. tmpRange.setEnd( node, node.childNodes.length );
  7457. }
  7458. break;
  7459. }
  7460. if ( !blockquote[node.tagName] ) {
  7461. tmpRange.setEndAfter( preNode );
  7462. break;
  7463. }
  7464. preNode = node;
  7465. node = node.parentNode;
  7466. }
  7467. }
  7468. node = range.document.createElement( 'blockquote' );
  7469. domUtils.setAttributes( node, attrs );
  7470. node.appendChild( tmpRange.extractContents() );
  7471. tmpRange.insertNode( node );
  7472. //去除重复的
  7473. var childs = domUtils.getElementsByTagName(node,'blockquote');
  7474. for(var i=0,ci;ci=childs[i++];){
  7475. if(ci.parentNode){
  7476. domUtils.remove(ci,true);
  7477. }
  7478. }
  7479. }
  7480. range.moveToBookmark( bookmark ).select();
  7481. },
  7482. queryCommandState : function() {
  7483. return getObj(this) ? 1 : 0;
  7484. }
  7485. };
  7486. };
  7487. ///import core
  7488. ///commands 大小写转换
  7489. ///commandsName touppercase,tolowercase
  7490. ///commandsTitle 大写,小写
  7491. /**
  7492. * 大小写转换
  7493. * @function
  7494. * @name baidu.editor.execCommands
  7495. * @param {String} cmdName cmdName="convertcase"
  7496. */
  7497. UE.commands['touppercase'] =
  7498. UE.commands['tolowercase'] = {
  7499. execCommand:function (cmd) {
  7500. var me = this;
  7501. var rng = me.selection.getRange();
  7502. if(rng.collapsed){
  7503. return rng;
  7504. }
  7505. var bk = rng.createBookmark(),
  7506. bkEnd = bk.end,
  7507. filterFn = function( node ) {
  7508. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  7509. },
  7510. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  7511. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  7512. if ( curNode.nodeType == 3 ) {
  7513. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  7514. }
  7515. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  7516. if(curNode === bkEnd){
  7517. break;
  7518. }
  7519. }
  7520. rng.moveToBookmark(bk).select();
  7521. }
  7522. };
  7523. ///import core
  7524. ///import plugins\paragraph.js
  7525. ///commands 首行缩进
  7526. ///commandsName Outdent,Indent
  7527. ///commandsTitle 取消缩进,首行缩进
  7528. /**
  7529. * 首行缩进
  7530. * @function
  7531. * @name baidu.editor.execCommand
  7532. * @param {String} cmdName outdent取消缩进,indent缩进
  7533. */
  7534. UE.commands['indent'] = {
  7535. execCommand : function() {
  7536. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  7537. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  7538. },
  7539. queryCommandState : function() {
  7540. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  7541. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  7542. }
  7543. };
  7544. ///import core
  7545. ///commands 打印
  7546. ///commandsName Print
  7547. ///commandsTitle 打印
  7548. /**
  7549. * @description 打印
  7550. * @name baidu.editor.execCommand
  7551. * @param {String} cmdName print打印编辑器内容
  7552. * @author zhanyi
  7553. */
  7554. UE.commands['print'] = {
  7555. execCommand : function(){
  7556. this.window.print();
  7557. },
  7558. notNeedUndo : 1
  7559. };
  7560. ///import core
  7561. ///commands 预览
  7562. ///commandsName Preview
  7563. ///commandsTitle 预览
  7564. /**
  7565. * 预览
  7566. * @function
  7567. * @name baidu.editor.execCommand
  7568. * @param {String} cmdName preview预览编辑器内容
  7569. */
  7570. UE.commands['preview'] = {
  7571. execCommand : function(){
  7572. var w = window.open('', '_blank', ''),
  7573. d = w.document;
  7574. d.open();
  7575. d.write('<html><head><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  7576. "setTimeout(function(){uParse('div',{" +
  7577. " 'highlightJsUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCore.js'," +
  7578. " 'highlightCssUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCoreDefault.css'" +
  7579. "})},300)" +
  7580. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  7581. d.close();
  7582. },
  7583. notNeedUndo : 1
  7584. };
  7585. ///import core
  7586. ///commands 全选
  7587. ///commandsName SelectAll
  7588. ///commandsTitle 全选
  7589. /**
  7590. * 选中所有
  7591. * @function
  7592. * @name baidu.editor.execCommand
  7593. * @param {String} cmdName selectall选中编辑器里的所有内容
  7594. * @author zhanyi
  7595. */
  7596. UE.plugins['selectall'] = function(){
  7597. var me = this;
  7598. me.commands['selectall'] = {
  7599. execCommand : function(){
  7600. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  7601. var me = this,body = me.body,
  7602. range = me.selection.getRange();
  7603. range.selectNodeContents(body);
  7604. if(domUtils.isEmptyBlock(body)){
  7605. //opera不能自动合并到元素的里边,要手动处理一下
  7606. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  7607. range.setStartAtFirst(body.firstChild);
  7608. }
  7609. range.collapse(true);
  7610. }
  7611. range.select(true);
  7612. },
  7613. notNeedUndo : 1
  7614. };
  7615. //快捷键
  7616. me.addshortcutkey({
  7617. "selectAll" : "ctrl+65"
  7618. });
  7619. };
  7620. ///import core
  7621. ///commands 格式
  7622. ///commandsName Paragraph
  7623. ///commandsTitle 段落格式
  7624. /**
  7625. * 段落样式
  7626. * @function
  7627. * @name baidu.editor.execCommand
  7628. * @param {String} cmdName paragraph插入段落执行命令
  7629. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  7630. * @param {String} attrs 标签的属性
  7631. * @author zhanyi
  7632. */
  7633. UE.plugins['paragraph'] = function() {
  7634. var me = this,
  7635. block = domUtils.isBlockElm,
  7636. notExchange = ['TD','LI','PRE'],
  7637. doParagraph = function(range,style,attrs,sourceCmdName){
  7638. var bookmark = range.createBookmark(),
  7639. filterFn = function( node ) {
  7640. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  7641. },
  7642. para;
  7643. range.enlarge( true );
  7644. var bookmark2 = range.createBookmark(),
  7645. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  7646. tmpRange = range.cloneRange(),
  7647. tmpNode;
  7648. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  7649. if ( current.nodeType == 3 || !block( current ) ) {
  7650. tmpRange.setStartBefore( current );
  7651. while ( current && current !== bookmark2.end && !block( current ) ) {
  7652. tmpNode = current;
  7653. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  7654. return !block( node );
  7655. } );
  7656. }
  7657. tmpRange.setEndAfter( tmpNode );
  7658. para = range.document.createElement( style );
  7659. if(attrs){
  7660. domUtils.setAttributes(para,attrs);
  7661. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  7662. para.style.cssText = attrs.style;
  7663. }
  7664. }
  7665. para.appendChild( tmpRange.extractContents() );
  7666. //需要内容占位
  7667. if(domUtils.isEmptyNode(para)){
  7668. domUtils.fillChar(range.document,para);
  7669. }
  7670. tmpRange.insertNode( para );
  7671. var parent = para.parentNode;
  7672. //如果para上一级是一个block元素且不是body,td就删除它
  7673. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  7674. //存储dir,style
  7675. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  7676. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  7677. //trace:1070
  7678. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  7679. //trace:1030
  7680. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  7681. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  7682. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  7683. }
  7684. //trace:1706 选择的就是h1-6要删除
  7685. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  7686. domUtils.setAttributes(parent,attrs);
  7687. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  7688. parent.style.cssText = attrs.style;
  7689. }
  7690. domUtils.remove(para,true);
  7691. para = parent;
  7692. }else{
  7693. domUtils.remove( para.parentNode, true );
  7694. }
  7695. }
  7696. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  7697. current = parent;
  7698. }else{
  7699. current = para;
  7700. }
  7701. current = domUtils.getNextDomNode( current, false, filterFn );
  7702. } else {
  7703. current = domUtils.getNextDomNode( current, true, filterFn );
  7704. }
  7705. }
  7706. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  7707. };
  7708. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  7709. me.commands['paragraph'] = {
  7710. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  7711. var range = this.selection.getRange();
  7712. //闭合时单独处理
  7713. if(range.collapsed){
  7714. var txt = this.document.createTextNode('p');
  7715. range.insertNode(txt);
  7716. //去掉冗余的fillchar
  7717. if(browser.ie){
  7718. var node = txt.previousSibling;
  7719. if(node && domUtils.isWhitespace(node)){
  7720. domUtils.remove(node);
  7721. }
  7722. node = txt.nextSibling;
  7723. if(node && domUtils.isWhitespace(node)){
  7724. domUtils.remove(node);
  7725. }
  7726. }
  7727. }
  7728. range = doParagraph(range,style,attrs,sourceCmdName);
  7729. if(txt){
  7730. range.setStartBefore(txt).collapse(true);
  7731. pN = txt.parentNode;
  7732. domUtils.remove(txt);
  7733. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  7734. domUtils.fillNode(this.document,pN);
  7735. }
  7736. }
  7737. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  7738. var child = range.startContainer.childNodes[range.startOffset];
  7739. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  7740. range.setStart(child,0).collapse(true);
  7741. }
  7742. }
  7743. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  7744. range.select();
  7745. return true;
  7746. },
  7747. queryCommandValue : function() {
  7748. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  7749. return node ? node.tagName.toLowerCase() : '';
  7750. }
  7751. };
  7752. };
  7753. ///import core
  7754. ///commands 输入的方向
  7755. ///commandsName DirectionalityLtr,DirectionalityRtl
  7756. ///commandsTitle 从左向右输入,从右向左输入
  7757. /**
  7758. * 输入的方向
  7759. * @function
  7760. * @name baidu.editor.execCommand
  7761. * @param {String} cmdName directionality执行函数的参数
  7762. * @param {String} forward ltr从左向右输入,rtl从右向左输入
  7763. */
  7764. (function() {
  7765. var block = domUtils.isBlockElm ,
  7766. getObj = function(editor){
  7767. // var startNode = editor.selection.getStart(),
  7768. // parents;
  7769. // if ( startNode ) {
  7770. // //查找所有的是block的父亲节点
  7771. // parents = domUtils.findParents( startNode, true, block, true );
  7772. // for ( var i = 0,ci; ci = parents[i++]; ) {
  7773. // if ( ci.getAttribute( 'dir' ) ) {
  7774. // return ci;
  7775. // }
  7776. // }
  7777. // }
  7778. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  7779. },
  7780. doDirectionality = function(range,editor,forward){
  7781. var bookmark,
  7782. filterFn = function( node ) {
  7783. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  7784. },
  7785. obj = getObj( editor );
  7786. if ( obj && range.collapsed ) {
  7787. obj.setAttribute( 'dir', forward );
  7788. return range;
  7789. }
  7790. bookmark = range.createBookmark();
  7791. range.enlarge( true );
  7792. var bookmark2 = range.createBookmark(),
  7793. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  7794. tmpRange = range.cloneRange(),
  7795. tmpNode;
  7796. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  7797. if ( current.nodeType == 3 || !block( current ) ) {
  7798. tmpRange.setStartBefore( current );
  7799. while ( current && current !== bookmark2.end && !block( current ) ) {
  7800. tmpNode = current;
  7801. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  7802. return !block( node );
  7803. } );
  7804. }
  7805. tmpRange.setEndAfter( tmpNode );
  7806. var common = tmpRange.getCommonAncestor();
  7807. if ( !domUtils.isBody( common ) && block( common ) ) {
  7808. //遍历到了block节点
  7809. common.setAttribute( 'dir', forward );
  7810. current = common;
  7811. } else {
  7812. //没有遍历到,添加一个block节点
  7813. var p = range.document.createElement( 'p' );
  7814. p.setAttribute( 'dir', forward );
  7815. var frag = tmpRange.extractContents();
  7816. p.appendChild( frag );
  7817. tmpRange.insertNode( p );
  7818. current = p;
  7819. }
  7820. current = domUtils.getNextDomNode( current, false, filterFn );
  7821. } else {
  7822. current = domUtils.getNextDomNode( current, true, filterFn );
  7823. }
  7824. }
  7825. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  7826. };
  7827. UE.commands['directionality'] = {
  7828. execCommand : function( cmdName,forward ) {
  7829. var range = this.selection.getRange();
  7830. //闭合时单独处理
  7831. if(range.collapsed){
  7832. var txt = this.document.createTextNode('d');
  7833. range.insertNode(txt);
  7834. }
  7835. doDirectionality(range,this,forward);
  7836. if(txt){
  7837. range.setStartBefore(txt).collapse(true);
  7838. domUtils.remove(txt);
  7839. }
  7840. range.select();
  7841. return true;
  7842. },
  7843. queryCommandValue : function() {
  7844. var node = getObj(this);
  7845. return node ? node.getAttribute('dir') : 'ltr';
  7846. }
  7847. };
  7848. })();
  7849. ///import core
  7850. ///import plugins\inserthtml.js
  7851. ///commands 分割线
  7852. ///commandsName Horizontal
  7853. ///commandsTitle 分隔线
  7854. /**
  7855. * 分割线
  7856. * @function
  7857. * @name baidu.editor.execCommand
  7858. * @param {String} cmdName horizontal插入分割线
  7859. */
  7860. UE.plugins['horizontal'] = function(){
  7861. var me = this;
  7862. me.commands['horizontal'] = {
  7863. execCommand : function( cmdName ) {
  7864. var me = this;
  7865. if(me.queryCommandState(cmdName)!==-1){
  7866. me.execCommand('insertHtml','<hr>');
  7867. var range = me.selection.getRange(),
  7868. start = range.startContainer;
  7869. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  7870. var tmp;
  7871. if(tmp = start.childNodes[range.startOffset - 1]){
  7872. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  7873. if(me.options.enterTag == 'p'){
  7874. tmp = me.document.createElement('p');
  7875. range.insertNode(tmp);
  7876. range.setStart(tmp,0).setCursor();
  7877. }else{
  7878. tmp = me.document.createElement('br');
  7879. range.insertNode(tmp);
  7880. range.setStartBefore(tmp).setCursor();
  7881. }
  7882. }
  7883. }
  7884. }
  7885. return true;
  7886. }
  7887. },
  7888. //边界在table里不能加分隔线
  7889. queryCommandState : function() {
  7890. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  7891. }
  7892. };
  7893. // me.addListener('delkeyup',function(){
  7894. // var rng = this.selection.getRange();
  7895. // if(browser.ie && browser.version > 8){
  7896. // rng.txtToElmBoundary(true);
  7897. // if(domUtils.isStartInblock(rng)){
  7898. // var tmpNode = rng.startContainer;
  7899. // var pre = tmpNode.previousSibling;
  7900. // if(pre && domUtils.isTagNode(pre,'hr')){
  7901. // domUtils.remove(pre);
  7902. // rng.select();
  7903. // return;
  7904. // }
  7905. // }
  7906. // }
  7907. // if(domUtils.isBody(rng.startContainer)){
  7908. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  7909. // if(hr && hr.nodeName == 'HR'){
  7910. // var next = hr.nextSibling;
  7911. // if(next){
  7912. // rng.setStart(next,0)
  7913. // }else if(hr.previousSibling){
  7914. // rng.setStartAtLast(hr.previousSibling)
  7915. // }else{
  7916. // var p = this.document.createElement('p');
  7917. // hr.parentNode.insertBefore(p,hr);
  7918. // domUtils.fillNode(this.document,p);
  7919. // rng.setStart(p,0);
  7920. // }
  7921. // domUtils.remove(hr);
  7922. // rng.setCursor(false,true);
  7923. // }
  7924. // }
  7925. // })
  7926. me.addListener('delkeydown',function(name,evt){
  7927. var rng = this.selection.getRange();
  7928. rng.txtToElmBoundary(true);
  7929. if(domUtils.isStartInblock(rng)){
  7930. var tmpNode = rng.startContainer;
  7931. var pre = tmpNode.previousSibling;
  7932. if(pre && domUtils.isTagNode(pre,'hr')){
  7933. domUtils.remove(pre);
  7934. rng.select();
  7935. domUtils.preventDefault(evt);
  7936. return true;
  7937. }
  7938. }
  7939. })
  7940. };
  7941. ///import core
  7942. ///import plugins\inserthtml.js
  7943. ///commands 日期,时间
  7944. ///commandsName Date,Time
  7945. ///commandsTitle 日期,时间
  7946. /**
  7947. * 插入日期
  7948. * @function
  7949. * @name baidu.editor.execCommand
  7950. * @param {String} cmdName date插入日期
  7951. * @author zhuwenxuan
  7952. */
  7953. /**
  7954. * 插入时间
  7955. * @function
  7956. * @name baidu.editor.execCommand
  7957. * @param {String} cmdName time插入时间
  7958. * @author zhuwenxuan
  7959. */
  7960. UE.commands['time'] = UE.commands["date"] = {
  7961. execCommand : function(cmd){
  7962. var date = new Date;
  7963. this.execCommand('insertHtml',cmd == "time" ?
  7964. (date.getHours()+":"+ (date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes())+":"+(date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds())) :
  7965. (date.getFullYear()+"-"+((date.getMonth()+1)<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1)+"-"+(date.getDate()<10?"0"+date.getDate():date.getDate())));
  7966. }
  7967. };
  7968. ///import core
  7969. ///import plugins\paragraph.js
  7970. ///commands 段间距
  7971. ///commandsName RowSpacingBottom,RowSpacingTop
  7972. ///commandsTitle 段间距
  7973. /**
  7974. * @description 设置段前距,段后距
  7975. * @name baidu.editor.execCommand
  7976. * @param {String} cmdName rowspacing设置段间距
  7977. * @param {String} value 值,以px为单位
  7978. * @param {String} dir top或bottom段前后段后
  7979. * @author zhanyi
  7980. */
  7981. UE.plugins['rowspacing'] = function(){
  7982. var me = this;
  7983. me.setOpt({
  7984. 'rowspacingtop':['5', '10', '15', '20', '25'],
  7985. 'rowspacingbottom':['5', '10', '15', '20', '25']
  7986. });
  7987. me.commands['rowspacing'] = {
  7988. execCommand : function( cmdName,value,dir ) {
  7989. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  7990. return true;
  7991. },
  7992. queryCommandValue : function(cmdName,dir) {
  7993. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  7994. value;
  7995. //trace:1026
  7996. if(pN){
  7997. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  7998. return !value ? 0 : value;
  7999. }
  8000. return 0;
  8001. }
  8002. };
  8003. };
  8004. ///import core
  8005. ///import plugins\paragraph.js
  8006. ///commands 行间距
  8007. ///commandsName LineHeight
  8008. ///commandsTitle 行间距
  8009. /**
  8010. * @description 设置行内间距
  8011. * @name baidu.editor.execCommand
  8012. * @param {String} cmdName lineheight设置行内间距
  8013. * @param {String} value 值
  8014. * @author zhuwenxuan
  8015. */
  8016. UE.plugins['lineheight'] = function(){
  8017. var me = this;
  8018. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  8019. me.commands['lineheight'] = {
  8020. execCommand : function( cmdName,value ) {
  8021. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  8022. return true;
  8023. },
  8024. queryCommandValue : function() {
  8025. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  8026. if(pN){
  8027. var value = domUtils.getComputedStyle(pN,'line-height');
  8028. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  8029. }
  8030. }
  8031. };
  8032. };
  8033. ///import core
  8034. ///import plugins/inserthtml.js
  8035. ///commands 插入代码
  8036. ///commandsName code
  8037. ///commandsTitle 插入代码
  8038. UE.plugins['insertcode'] = function() {
  8039. var me = this;
  8040. me.ready(function(){
  8041. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  8042. me.document)
  8043. });
  8044. me.setOpt('insertcode',{
  8045. 'as3':'ActionScript3',
  8046. 'bash':'Bash/Shell',
  8047. 'cpp':'C/C++',
  8048. 'css':'Css',
  8049. 'cf':'CodeFunction',
  8050. 'c#':'C#',
  8051. 'delphi':'Delphi',
  8052. 'diff':'Diff',
  8053. 'erlang':'Erlang',
  8054. 'groovy':'Groovy',
  8055. 'html':'Html',
  8056. 'java':'Java',
  8057. 'jfx':'JavaFx',
  8058. 'js':'Javascript',
  8059. 'pl':'Perl',
  8060. 'php':'Php',
  8061. 'plain':'Plain Text',
  8062. 'ps':'PowerShell',
  8063. 'python':'Python',
  8064. 'ruby':'Ruby',
  8065. 'scala':'Scala',
  8066. 'sql':'Sql',
  8067. 'vb':'Vb',
  8068. 'xml':'Xml'
  8069. });
  8070. me.commands['insertcode'] = {
  8071. execCommand : function(cmd,lang){
  8072. var me = this,
  8073. rng = me.selection.getRange(),
  8074. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8075. if(pre){
  8076. pre.className = 'brush:'+lang+';toolbar:false;';
  8077. }else{
  8078. var code = '';
  8079. if(rng.collapsed){
  8080. code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>';
  8081. }else{
  8082. var frag = rng.extractContents();
  8083. var div = me.document.createElement('div');
  8084. div.appendChild(frag);
  8085. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  8086. if(browser.ie && browser.version > 8){
  8087. if(node.type =='element'){
  8088. if(node.tagName == 'br'){
  8089. code += '\n'
  8090. }else if(!dtd.$empty[node.tagName]){
  8091. utils.each(node.children,function(cn){
  8092. if(cn.type =='element'){
  8093. if(cn.tagName == 'br'){
  8094. code += '\n'
  8095. }else if(!dtd.$empty[node.tagName]){
  8096. code += cn.innerText();
  8097. }
  8098. }else{
  8099. code += cn.data
  8100. }
  8101. })
  8102. if(!/\n$/.test(code)){
  8103. code += '\n';
  8104. }
  8105. }
  8106. }else{
  8107. code += node.data + '\n'
  8108. }
  8109. if(!node.nextSibling() && /\n$/.test(code)){
  8110. code = code.replace(/\n$/,'');
  8111. }
  8112. }else{
  8113. if(browser.ie){
  8114. if(node.type =='element'){
  8115. if(node.tagName == 'br'){
  8116. code += '<br>'
  8117. }else if(!dtd.$empty[node.tagName]){
  8118. utils.each(node.children,function(cn){
  8119. if(cn.type =='element'){
  8120. if(cn.tagName == 'br'){
  8121. code += '<br>'
  8122. }else if(!dtd.$empty[node.tagName]){
  8123. code += cn.innerText();
  8124. }
  8125. }else{
  8126. code += cn.data
  8127. }
  8128. });
  8129. if(!/br>$/.test(code)){
  8130. code += '<br>';
  8131. }
  8132. }
  8133. }else{
  8134. code += node.data + '<br>'
  8135. }
  8136. if(!node.nextSibling() && /<br>$/.test(code)){
  8137. code = code.replace(/<br>$/,'');
  8138. }
  8139. }else{
  8140. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  8141. if(!/br\/?\s*>$/.test(code)){
  8142. if(!node.nextSibling())
  8143. return;
  8144. code += '<br>'
  8145. }
  8146. }
  8147. }
  8148. });
  8149. }
  8150. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  8151. pre = me.document.getElementById('coder');
  8152. domUtils.removeAttributes(pre,'id');
  8153. var tmpNode = pre.previousSibling;
  8154. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  8155. domUtils.remove(tmpNode)
  8156. }
  8157. var rng = me.selection.getRange();
  8158. if(domUtils.isEmptyBlock(pre)){
  8159. rng.setStart(pre,0).setCursor(false,true)
  8160. }else{
  8161. rng.selectNodeContents(pre).select()
  8162. }
  8163. }
  8164. },
  8165. queryCommandValue : function(){
  8166. var path = this.selection.getStartElementPath();
  8167. var lang = '';
  8168. utils.each(path,function(node){
  8169. if(node.nodeName =='PRE'){
  8170. var match = node.className.match(/brush:([^;]+)/);
  8171. lang = match && match[1] ? match[1] : '';
  8172. return false;
  8173. }
  8174. });
  8175. return lang;
  8176. }
  8177. };
  8178. me.addInputRule(function(root){
  8179. utils.each(root.getNodesByTagName('pre'),function(pre){
  8180. var brs = pre.getNodesByTagName('br');
  8181. if(brs.length){
  8182. browser.ie && browser.version > 8 && utils.each(brs,function(br){
  8183. var txt = UE.uNode.createText('\n');
  8184. br.parentNode.insertBefore(txt,br);
  8185. br.parentNode.removeChild(br);
  8186. });
  8187. return;
  8188. }
  8189. if(browser.ie && browser.version > 8)
  8190. return;
  8191. var code = pre.innerText().split(/\n/);
  8192. pre.innerHTML('');
  8193. utils.each(code,function(c){
  8194. if(c.length){
  8195. pre.appendChild(UE.uNode.createText(c));
  8196. }
  8197. pre.appendChild(UE.uNode.createElement('br'))
  8198. })
  8199. })
  8200. });
  8201. me.addOutputRule(function(root){
  8202. utils.each(root.getNodesByTagName('pre'),function(pre){
  8203. var code = '';
  8204. utils.each(pre.children,function(n){
  8205. if(n.type == 'text'){
  8206. //在ie下文本内容有可能末尾带有\n要去掉
  8207. //trace:3396
  8208. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  8209. }else{
  8210. if(n.tagName == 'br'){
  8211. code += '\n'
  8212. }else{
  8213. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  8214. }
  8215. }
  8216. });
  8217. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  8218. })
  8219. });
  8220. //不需要判断highlight的command列表
  8221. me.notNeedCodeQuery ={
  8222. help:1,
  8223. undo:1,
  8224. redo:1,
  8225. source:1,
  8226. print:1,
  8227. searchreplace:1,
  8228. fullscreen:1,
  8229. preview:1,
  8230. insertparagraph:1,
  8231. elementpath:1,
  8232. highlightcode:1,
  8233. insertcode:1,
  8234. inserthtml:1,
  8235. selectall:1
  8236. };
  8237. //将queyCommamndState重置
  8238. var orgQuery = me.queryCommandState;
  8239. me.queryCommandState = function(cmd){
  8240. var me = this;
  8241. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  8242. return -1;
  8243. }
  8244. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  8245. };
  8246. me.addListener('beforeenterkeydown',function(){
  8247. var rng = me.selection.getRange();
  8248. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8249. if(pre){
  8250. me.fireEvent('saveScene');
  8251. if(!rng.collapsed){
  8252. rng.deleteContents();
  8253. }
  8254. if(!browser.ie ){
  8255. var tmpNode = me.document.createElement('br'),pre;
  8256. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  8257. var next = tmpNode.nextSibling;
  8258. if(!next){
  8259. rng.insertNode(tmpNode.cloneNode(false));
  8260. }else{
  8261. rng.setStartAfter(tmpNode);
  8262. }
  8263. pre = tmpNode.previousSibling;
  8264. var tmp;
  8265. while(pre ){
  8266. tmp = pre;
  8267. pre = pre.previousSibling;
  8268. if(!pre || pre.nodeName == 'BR'){
  8269. pre = tmp;
  8270. break;
  8271. }
  8272. }
  8273. if(pre){
  8274. var str = '';
  8275. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  8276. str += pre.nodeValue;
  8277. pre = pre.nextSibling;
  8278. }
  8279. if(pre.nodeName != 'BR'){
  8280. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  8281. if(match && match[1]){
  8282. str += match[1]
  8283. }
  8284. }
  8285. if(str){
  8286. str = me.document.createTextNode(str);
  8287. rng.insertNode(str).setStartAfter(str);
  8288. }
  8289. }
  8290. rng.collapse(true).select(true);
  8291. }else{
  8292. if(browser.version > 8){
  8293. var txt = me.document.createTextNode('\n');
  8294. var start = rng.startContainer;
  8295. if(rng.startOffset == 0){
  8296. var preNode = start.previousSibling;
  8297. if(preNode){
  8298. rng.insertNode(txt);
  8299. var fillchar = me.document.createTextNode(' ');
  8300. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  8301. }
  8302. }else{
  8303. rng.insertNode(txt).setStartAfter(txt);
  8304. var fillchar = me.document.createTextNode(' ');
  8305. start = rng.startContainer.childNodes[rng.startOffset];
  8306. if(start && !/^\n/.test(start.nodeValue)){
  8307. rng.setStartBefore(txt)
  8308. }
  8309. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  8310. }
  8311. }else{
  8312. var tmpNode = me.document.createElement('br');
  8313. rng.insertNode(tmpNode);
  8314. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  8315. rng.setStartAfter(tmpNode);
  8316. pre = tmpNode.previousSibling;
  8317. var tmp;
  8318. while(pre ){
  8319. tmp = pre;
  8320. pre = pre.previousSibling;
  8321. if(!pre || pre.nodeName == 'BR'){
  8322. pre = tmp;
  8323. break;
  8324. }
  8325. }
  8326. if(pre){
  8327. var str = '';
  8328. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  8329. str += pre.nodeValue;
  8330. pre = pre.nextSibling;
  8331. }
  8332. if(pre.nodeName != 'BR'){
  8333. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  8334. if(match && match[1]){
  8335. str += match[1]
  8336. }
  8337. }
  8338. str = me.document.createTextNode(str);
  8339. rng.insertNode(str).setStartAfter(str);
  8340. }
  8341. rng.collapse(true).select();
  8342. }
  8343. }
  8344. me.fireEvent('saveScene');
  8345. return true;
  8346. }
  8347. });
  8348. me.addListener('tabkeydown',function(cmd,evt){
  8349. var rng = me.selection.getRange();
  8350. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8351. if(pre){
  8352. me.fireEvent('saveScene');
  8353. if(evt.shiftKey){
  8354. // if(!rng.collapsed){
  8355. // var bk = rng.createBookmark();
  8356. // var start = bk.start.previousSibling;
  8357. // if(start === pre.firstChild){
  8358. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8359. // }else{
  8360. // while(start){
  8361. // if(domUtils.isBr(start)){
  8362. // start = start.nextSibling;
  8363. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8364. // break;
  8365. // }
  8366. // while(start.previousSibling && start.previousSibling.nodeType == 3){
  8367. // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue;
  8368. // domUtils.remove(start.previousSibling)
  8369. // }
  8370. // start = start.previousSibling;
  8371. // }
  8372. // }
  8373. //
  8374. // var end = bk.end;
  8375. // start = bk.start.nextSibling;
  8376. //
  8377. // while(start && start !== end){
  8378. // if(domUtils.isBr(start) && start.nextSibling){
  8379. // if(start.nextSibling === end){
  8380. // break;
  8381. // }
  8382. // start = start.nextSibling;
  8383. // while(start.nextSibling && start.nextSibling.nodeType == 3){
  8384. // start.nodeValue += start.nextSibling.nodeValue;
  8385. // domUtils.remove(start.nextSibling)
  8386. // }
  8387. //
  8388. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8389. // }
  8390. //
  8391. // start = start.nextSibling;
  8392. // }
  8393. // rng.moveToBookmark(bk).select();
  8394. // }else{
  8395. // var bk = rng.createBookmark();
  8396. // var start = bk.start.previousSibling;
  8397. // if(start === pre.firstChild){
  8398. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8399. // }else{
  8400. // while(start){
  8401. // if(domUtils.isBr(start)){
  8402. // start = start.nextSibling;
  8403. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8404. // break;
  8405. // }
  8406. // while(start.previousSibling && start.previousSibling.nodeType == 3){
  8407. // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue;
  8408. // domUtils.remove(start.previousSibling)
  8409. // }
  8410. // start = start.previousSibling;
  8411. // }
  8412. // }
  8413. // }
  8414. }else{
  8415. if(!rng.collapsed){
  8416. var bk = rng.createBookmark();
  8417. var start = bk.start.previousSibling;
  8418. while(start){
  8419. if(pre.firstChild === start && !domUtils.isBr(start)){
  8420. pre.insertBefore(me.document.createTextNode(' '),start);
  8421. break;
  8422. }
  8423. if(domUtils.isBr(start)){
  8424. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  8425. break;
  8426. }
  8427. start = start.previousSibling;
  8428. }
  8429. var end = bk.end;
  8430. start = bk.start.nextSibling;
  8431. if(pre.firstChild === bk.start){
  8432. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  8433. }
  8434. while(start && start !== end){
  8435. if(domUtils.isBr(start) && start.nextSibling){
  8436. if(start.nextSibling === end){
  8437. break;
  8438. }
  8439. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  8440. }
  8441. start = start.nextSibling;
  8442. }
  8443. rng.moveToBookmark(bk).select();
  8444. }else{
  8445. var tmpNode = me.document.createTextNode(' ');
  8446. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  8447. }
  8448. }
  8449. me.fireEvent('saveScene');
  8450. return true;
  8451. }
  8452. });
  8453. me.addListener('beforeinserthtml',function(evtName,html){
  8454. var me = this,
  8455. rng = me.selection.getRange(),
  8456. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8457. if(pre){
  8458. if(!rng.collapsed){
  8459. rng.deleteContents()
  8460. }
  8461. var htmlstr = '';
  8462. if(browser.ie && browser.version > 8){
  8463. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  8464. if(node.type =='element'){
  8465. if(node.tagName == 'br'){
  8466. htmlstr += '\n'
  8467. }else if(!dtd.$empty[node.tagName]){
  8468. utils.each(node.children,function(cn){
  8469. if(cn.type =='element'){
  8470. if(cn.tagName == 'br'){
  8471. htmlstr += '\n'
  8472. }else if(!dtd.$empty[node.tagName]){
  8473. htmlstr += cn.innerText();
  8474. }
  8475. }else{
  8476. htmlstr += cn.data
  8477. }
  8478. })
  8479. if(!/\n$/.test(htmlstr)){
  8480. htmlstr += '\n';
  8481. }
  8482. }
  8483. }else{
  8484. htmlstr += node.data + '\n'
  8485. }
  8486. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  8487. htmlstr = htmlstr.replace(/\n$/,'');
  8488. }
  8489. });
  8490. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  8491. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  8492. }else{
  8493. var frag = me.document.createDocumentFragment();
  8494. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  8495. if(node.type =='element'){
  8496. if(node.tagName == 'br'){
  8497. frag.appendChild(me.document.createElement('br'))
  8498. }else if(!dtd.$empty[node.tagName]){
  8499. utils.each(node.children,function(cn){
  8500. if(cn.type =='element'){
  8501. if(cn.tagName == 'br'){
  8502. frag.appendChild(me.document.createElement('br'))
  8503. }else if(!dtd.$empty[node.tagName]){
  8504. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  8505. }
  8506. }else{
  8507. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  8508. }
  8509. })
  8510. if(frag.lastChild.nodeName != 'BR'){
  8511. frag.appendChild(me.document.createElement('br'))
  8512. }
  8513. }
  8514. }else{
  8515. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  8516. }
  8517. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  8518. frag.removeChild(frag.lastChild)
  8519. }
  8520. });
  8521. rng.insertNode(frag).select();
  8522. }
  8523. return true;
  8524. }
  8525. });
  8526. //方向键的处理
  8527. me.addListener('keydown',function(cmd,evt){
  8528. var me = this,keyCode = evt.keyCode || evt.which;
  8529. if(keyCode == 40){
  8530. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  8531. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  8532. var last = pre.lastChild
  8533. while(last && last.nodeName == 'BR'){
  8534. last = last.previousSibling;
  8535. }
  8536. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  8537. me.execCommand('insertparagraph');
  8538. domUtils.preventDefault(evt)
  8539. }
  8540. }
  8541. }
  8542. });
  8543. //trace:3395
  8544. me.addListener('delkeydown',function(type,evt){
  8545. var rng = this.selection.getRange();
  8546. rng.txtToElmBoundary(true);
  8547. var start = rng.startContainer;
  8548. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  8549. var p = me.document.createElement('p');
  8550. domUtils.fillNode(me.document,p);
  8551. start.parentNode.insertBefore(p,start);
  8552. domUtils.remove(start);
  8553. rng.setStart(p,0).setCursor(false,true);
  8554. domUtils.preventDefault(evt);
  8555. return true;
  8556. }
  8557. })
  8558. };
  8559. ///import core
  8560. ///commands 清空文档
  8561. ///commandsName ClearDoc
  8562. ///commandsTitle 清空文档
  8563. /**
  8564. *
  8565. * 清空文档
  8566. * @function
  8567. * @name baidu.editor.execCommand
  8568. * @param {String} cmdName cleardoc清空文档
  8569. */
  8570. UE.commands['cleardoc'] = {
  8571. execCommand : function( cmdName) {
  8572. var me = this,
  8573. enterTag = me.options.enterTag,
  8574. range = me.selection.getRange();
  8575. if(enterTag == "br"){
  8576. me.body.innerHTML = "<br/>";
  8577. range.setStart(me.body,0).setCursor();
  8578. }else{
  8579. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  8580. range.setStart(me.body.firstChild,0).setCursor(false,true);
  8581. }
  8582. setTimeout(function(){
  8583. me.fireEvent("clearDoc");
  8584. },0);
  8585. }
  8586. };
  8587. ///import core
  8588. ///commands 锚点
  8589. ///commandsName Anchor
  8590. ///commandsTitle 锚点
  8591. ///commandsDialog dialogs\anchor
  8592. /**
  8593. * 锚点
  8594. * @function
  8595. * @name baidu.editor.execCommands
  8596. * @param {String} cmdName cmdName="anchor"插入锚点
  8597. */
  8598. UE.plugins['anchor'] = function (){
  8599. var me = this;
  8600. me.ready(function(){
  8601. utils.cssRule('anchor',
  8602. '.anchorclass{background: url(\''
  8603. + me.options.UEDITOR_HOME_URL +
  8604. 'themes/default/images/anchor.gif\') no-repeat scroll left center transparent;border: 1px dotted #0000FF;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  8605. me.document)
  8606. });
  8607. me.addOutputRule(function(root){
  8608. utils.each(root.getNodesByTagName('img'),function(a){
  8609. var val;
  8610. if(val = a.getAttr('anchorname')){
  8611. a.tagName = 'a';
  8612. a.setAttr({
  8613. anchorname : '',
  8614. name : val,
  8615. 'class' : ''
  8616. })
  8617. }
  8618. })
  8619. });
  8620. me.addInputRule(function(root){
  8621. utils.each(root.getNodesByTagName('a'),function(a){
  8622. var val;
  8623. if((val = a.getAttr('name')) && !a.getAttr('href')){
  8624. a.tagName = 'img';
  8625. a.setAttr({
  8626. anchorname :a.getAttr('name'),
  8627. 'class' : 'anchorclass'
  8628. });
  8629. a.setAttr('name')
  8630. }
  8631. })
  8632. });
  8633. me.commands['anchor'] = {
  8634. execCommand:function (cmd, name) {
  8635. var range = this.selection.getRange(),img = range.getClosedNode();
  8636. if (img && img.getAttribute('anchorname')) {
  8637. if (name) {
  8638. img.setAttribute('anchorname', name);
  8639. } else {
  8640. range.setStartBefore(img).setCursor();
  8641. domUtils.remove(img);
  8642. }
  8643. } else {
  8644. if (name) {
  8645. //只在选区的开始插入
  8646. var anchor = this.document.createElement('img');
  8647. range.collapse(true);
  8648. domUtils.setAttributes(anchor,{
  8649. 'anchorname':name,
  8650. 'class':'anchorclass'
  8651. });
  8652. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  8653. }
  8654. }
  8655. }
  8656. };
  8657. };
  8658. ///import core
  8659. ///commands 字数统计
  8660. ///commandsName WordCount,wordCount
  8661. ///commandsTitle 字数统计
  8662. /**
  8663. * Created by JetBrains WebStorm.
  8664. * User: taoqili
  8665. * Date: 11-9-7
  8666. * Time: 下午8:18
  8667. * To change this template use File | Settings | File Templates.
  8668. */
  8669. UE.plugins['wordcount'] = function(){
  8670. var me = this;
  8671. me.addListener('contentchange',function(){
  8672. me.fireEvent('wordcount');
  8673. });
  8674. var timer;
  8675. me.addListener('ready',function(){
  8676. var me = this;
  8677. domUtils.on(me.body,"keyup",function(evt){
  8678. var code = evt.keyCode||evt.which,
  8679. //忽略的按键,ctr,alt,shift,方向键
  8680. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  8681. if(code in ignores) return;
  8682. clearTimeout(timer);
  8683. timer = setTimeout(function(){
  8684. me.fireEvent('wordcount');
  8685. },200)
  8686. })
  8687. });
  8688. };
  8689. ///import core
  8690. ///commands 添加分页功能
  8691. ///commandsName PageBreak
  8692. ///commandsTitle 分页
  8693. /**
  8694. * @description 添加分页功能
  8695. * @author zhanyi
  8696. */
  8697. UE.plugins['pagebreak'] = function () {
  8698. var me = this,
  8699. notBreakTags = ['td'];
  8700. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  8701. function fillNode(node){
  8702. if(domUtils.isEmptyBlock(node)){
  8703. var firstChild = node.firstChild,tmpNode;
  8704. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  8705. tmpNode = firstChild;
  8706. firstChild = firstChild.firstChild;
  8707. }
  8708. !tmpNode && (tmpNode = node);
  8709. domUtils.fillNode(me.document,tmpNode);
  8710. }
  8711. }
  8712. //分页符样式添加
  8713. me.ready(function(){
  8714. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  8715. });
  8716. function isHr(node){
  8717. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  8718. }
  8719. me.addInputRule(function(root){
  8720. root.traversal(function(node){
  8721. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  8722. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  8723. node.parentNode.insertBefore(hr,node);
  8724. node.parentNode.removeChild(node)
  8725. }
  8726. })
  8727. });
  8728. me.addOutputRule(function(node){
  8729. utils.each(node.getNodesByTagName('hr'),function(n){
  8730. if(n.getAttr('class') == 'pagebreak'){
  8731. var txt = UE.uNode.createText(me.options.pageBreakTag);
  8732. n.parentNode.insertBefore(txt,n);
  8733. n.parentNode.removeChild(n);
  8734. }
  8735. })
  8736. });
  8737. me.commands['pagebreak'] = {
  8738. execCommand:function () {
  8739. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  8740. domUtils.setAttributes(hr,{
  8741. 'class' : 'pagebreak',
  8742. noshade:"noshade",
  8743. size:"5"
  8744. });
  8745. domUtils.unSelectable(hr);
  8746. //table单独处理
  8747. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  8748. parents = [], pN;
  8749. if (node) {
  8750. switch (node.tagName) {
  8751. case 'TD':
  8752. pN = node.parentNode;
  8753. if (!pN.previousSibling) {
  8754. var table = domUtils.findParentByTagName(pN, 'table');
  8755. // var tableWrapDiv = table.parentNode;
  8756. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  8757. // && tableWrapDiv.tagName == 'DIV'
  8758. // && tableWrapDiv.getAttribute('dropdrag')
  8759. // ){
  8760. // domUtils.remove(tableWrapDiv,true);
  8761. // }
  8762. table.parentNode.insertBefore(hr, table);
  8763. parents = domUtils.findParents(hr, true);
  8764. } else {
  8765. pN.parentNode.insertBefore(hr, pN);
  8766. parents = domUtils.findParents(hr);
  8767. }
  8768. pN = parents[1];
  8769. if (hr !== pN) {
  8770. domUtils.breakParent(hr, pN);
  8771. }
  8772. //table要重写绑定一下拖拽
  8773. me.fireEvent('afteradjusttable',me.document);
  8774. }
  8775. } else {
  8776. if (!range.collapsed) {
  8777. range.deleteContents();
  8778. var start = range.startContainer;
  8779. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  8780. range.setStartBefore(start).collapse(true);
  8781. domUtils.remove(start);
  8782. start = range.startContainer;
  8783. }
  8784. }
  8785. range.insertNode(hr);
  8786. var pN = hr.parentNode, nextNode;
  8787. while (!domUtils.isBody(pN)) {
  8788. domUtils.breakParent(hr, pN);
  8789. nextNode = hr.nextSibling;
  8790. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  8791. domUtils.remove(nextNode);
  8792. }
  8793. pN = hr.parentNode;
  8794. }
  8795. nextNode = hr.nextSibling;
  8796. var pre = hr.previousSibling;
  8797. if(isHr(pre)){
  8798. domUtils.remove(pre);
  8799. }else{
  8800. pre && fillNode(pre);
  8801. }
  8802. if(!nextNode){
  8803. var p = me.document.createElement('p');
  8804. hr.parentNode.appendChild(p);
  8805. domUtils.fillNode(me.document,p);
  8806. range.setStart(p,0).collapse(true);
  8807. }else{
  8808. if(isHr(nextNode)){
  8809. domUtils.remove(nextNode);
  8810. }else{
  8811. fillNode(nextNode);
  8812. }
  8813. range.setEndAfter(hr).collapse(false);
  8814. }
  8815. range.select(true);
  8816. }
  8817. }
  8818. };
  8819. };
  8820. ///import core
  8821. ///commands 本地图片引导上传
  8822. ///commandsName WordImage
  8823. ///commandsTitle 本地图片引导上传
  8824. ///commandsDialog dialogs\wordimage
  8825. UE.plugins["wordimage"] = function () {
  8826. var me = this,
  8827. images;
  8828. me.addInputRule(function (root) {
  8829. utils.each(root.getNodesByTagName('img'), function (img) {
  8830. var attrs = img.attrs,
  8831. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  8832. opt = me.options,
  8833. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  8834. if (attrs['_src'] && attrs['_src'].indexOf("file:///")!==-1) {
  8835. img.setAttr({
  8836. width:attrs.width,
  8837. height:attrs.height,
  8838. alt:attrs.alt,
  8839. word_img:attrs._src,
  8840. src:src,
  8841. _src:src,
  8842. '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'
  8843. })
  8844. }
  8845. })
  8846. });
  8847. me.commands['wordimage'] = {
  8848. execCommand:function () {
  8849. images = domUtils.getElementsByTagName(me.document.body, "img");
  8850. var urlList = [];
  8851. for (var i = 0, ci; ci = images[i++];) {
  8852. var url = ci.getAttribute("word_img");
  8853. url && urlList.push(url);
  8854. }
  8855. if (images.length) {
  8856. this["word_img"] = urlList;
  8857. }
  8858. },
  8859. queryCommandState:function () {
  8860. images = domUtils.getElementsByTagName(me.document.body, "img");
  8861. for (var i = 0, ci; ci = images[i++];) {
  8862. if (ci.getAttribute("word_img")) {
  8863. return 1;
  8864. }
  8865. }
  8866. return -1;
  8867. }
  8868. };
  8869. };
  8870. UE.plugins['dragdrop'] = function (){
  8871. var me = this;
  8872. me.ready(function(){
  8873. domUtils.on(this.body,'dragend',function(){
  8874. var rng = me.selection.getRange();
  8875. var node = rng.getClosedNode()||me.selection.getStart();
  8876. if(node && node.tagName == 'IMG'){
  8877. var pre = node.previousSibling,next;
  8878. while(next = node.nextSibling){
  8879. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  8880. domUtils.remove(next)
  8881. }else{
  8882. break;
  8883. }
  8884. }
  8885. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  8886. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  8887. pre.appendChild(node);
  8888. domUtils.moveChild(next,pre);
  8889. domUtils.remove(next);
  8890. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  8891. next.insertBefore(node,next.firstChild);
  8892. }
  8893. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  8894. domUtils.remove(pre)
  8895. }
  8896. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  8897. domUtils.remove(next)
  8898. }
  8899. rng.selectNode(node).select();
  8900. me.fireEvent('saveScene');
  8901. }
  8902. }
  8903. })
  8904. });
  8905. me.addListener('keyup', function(type, evt) {
  8906. var keyCode = evt.keyCode || evt.which;
  8907. if (keyCode == 13) {
  8908. var rng = me.selection.getRange(),node;
  8909. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  8910. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  8911. domUtils.removeStyle(node,'text-align')
  8912. }
  8913. }
  8914. }
  8915. })
  8916. };
  8917. ///import core
  8918. ///commands 撤销和重做
  8919. ///commandsName Undo,Redo
  8920. ///commandsTitle 撤销,重做
  8921. /**
  8922. * @description 回退
  8923. * @author zhanyi
  8924. */
  8925. UE.plugins['undo'] = function () {
  8926. var saveSceneTimer;
  8927. var me = this,
  8928. maxUndoCount = me.options.maxUndoCount || 20,
  8929. maxInputCount = me.options.maxInputCount || 20,
  8930. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  8931. var noNeedFillCharTags = {
  8932. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  8933. };
  8934. var orgState = me.options.autoClearEmptyNode;
  8935. function compareAddr(indexA, indexB) {
  8936. if (indexA.length != indexB.length)
  8937. return 0;
  8938. for (var i = 0, l = indexA.length; i < l; i++) {
  8939. if (indexA[i] != indexB[i])
  8940. return 0
  8941. }
  8942. return 1;
  8943. }
  8944. function compareRangeAddress(rngAddrA, rngAddrB) {
  8945. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  8946. return 0;
  8947. }
  8948. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  8949. return 0;
  8950. }
  8951. return 1;
  8952. }
  8953. function UndoManager() {
  8954. this.list = [];
  8955. this.index = 0;
  8956. this.hasUndo = false;
  8957. this.hasRedo = false;
  8958. this.undo = function () {
  8959. if (this.hasUndo) {
  8960. if (!this.list[this.index - 1] && this.list.length == 1) {
  8961. this.reset();
  8962. return;
  8963. }
  8964. while (this.list[this.index].content == this.list[this.index - 1].content) {
  8965. this.index--;
  8966. if (this.index == 0) {
  8967. return this.restore(0);
  8968. }
  8969. }
  8970. this.restore(--this.index);
  8971. }
  8972. };
  8973. this.redo = function () {
  8974. if (this.hasRedo) {
  8975. while (this.list[this.index].content == this.list[this.index + 1].content) {
  8976. this.index++;
  8977. if (this.index == this.list.length - 1) {
  8978. return this.restore(this.index);
  8979. }
  8980. }
  8981. this.restore(++this.index);
  8982. }
  8983. };
  8984. this.restore = function () {
  8985. var me = this.editor;
  8986. var scene = this.list[this.index];
  8987. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  8988. me.options.autoClearEmptyNode = false;
  8989. me.filterInputRule(root);
  8990. me.options.autoClearEmptyNode = orgState;
  8991. //trace:873
  8992. //去掉展位符
  8993. me.document.body.innerHTML = root.toHtml();
  8994. me.fireEvent('afterscencerestore');
  8995. //处理undo后空格不展位的问题
  8996. if (browser.ie) {
  8997. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  8998. if(domUtils.isEmptyNode(node)){
  8999. domUtils.fillNode(me.document, node);
  9000. }
  9001. })
  9002. }
  9003. try{
  9004. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  9005. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  9006. }catch(e){}
  9007. this.update();
  9008. this.clearKey();
  9009. //不能把自己reset了
  9010. me.fireEvent('reset', true);
  9011. };
  9012. this.getScene = function () {
  9013. var me = this.editor;
  9014. var rng = me.selection.getRange(),
  9015. rngAddress = rng.createAddress(false,true);
  9016. me.fireEvent('beforegetscene');
  9017. var root = UE.htmlparser(me.body.innerHTML);
  9018. me.options.autoClearEmptyNode = false;
  9019. me.filterOutputRule(root);
  9020. me.options.autoClearEmptyNode = orgState;
  9021. var cont = root.toHtml();
  9022. //trace:3461
  9023. //这个会引起回退时导致空格丢失的情况
  9024. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  9025. me.fireEvent('aftergetscene');
  9026. return {
  9027. address:rngAddress,
  9028. content:cont
  9029. }
  9030. };
  9031. this.save = function (notCompareRange,notSetCursor) {
  9032. clearTimeout(saveSceneTimer);
  9033. var currentScene = this.getScene(notSetCursor),
  9034. lastScene = this.list[this.index];
  9035. //内容相同位置相同不存
  9036. if (lastScene && lastScene.content == currentScene.content &&
  9037. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  9038. ) {
  9039. return;
  9040. }
  9041. this.list = this.list.slice(0, this.index + 1);
  9042. this.list.push(currentScene);
  9043. //如果大于最大数量了,就把最前的剔除
  9044. if (this.list.length > maxUndoCount) {
  9045. this.list.shift();
  9046. }
  9047. this.index = this.list.length - 1;
  9048. this.clearKey();
  9049. //跟新undo/redo状态
  9050. this.update();
  9051. };
  9052. this.update = function () {
  9053. this.hasRedo = !!this.list[this.index + 1];
  9054. this.hasUndo = !!this.list[this.index - 1];
  9055. };
  9056. this.reset = function () {
  9057. this.list = [];
  9058. this.index = 0;
  9059. this.hasUndo = false;
  9060. this.hasRedo = false;
  9061. this.clearKey();
  9062. };
  9063. this.clearKey = function () {
  9064. keycont = 0;
  9065. lastKeyCode = null;
  9066. };
  9067. }
  9068. me.undoManger = new UndoManager();
  9069. me.undoManger.editor = me;
  9070. function saveScene() {
  9071. this.undoManger.save();
  9072. }
  9073. me.addListener('saveScene', function () {
  9074. var args = Array.prototype.splice.call(arguments,1);
  9075. this.undoManger.save.apply(this.undoManger,args);
  9076. });
  9077. me.addListener('beforeexeccommand', saveScene);
  9078. me.addListener('afterexeccommand', saveScene);
  9079. me.addListener('reset', function (type, exclude) {
  9080. if (!exclude) {
  9081. this.undoManger.reset();
  9082. }
  9083. });
  9084. me.commands['redo'] = me.commands['undo'] = {
  9085. execCommand:function (cmdName) {
  9086. this.undoManger[cmdName]();
  9087. },
  9088. queryCommandState:function (cmdName) {
  9089. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  9090. },
  9091. notNeedUndo:1
  9092. };
  9093. var keys = {
  9094. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  9095. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  9096. 37:1, 38:1, 39:1, 40:1
  9097. },
  9098. keycont = 0,
  9099. lastKeyCode;
  9100. //输入法状态下不计算字符数
  9101. var inputType = false;
  9102. me.addListener('ready', function () {
  9103. domUtils.on(this.body, 'compositionstart', function () {
  9104. inputType = true;
  9105. });
  9106. domUtils.on(this.body, 'compositionend', function () {
  9107. inputType = false;
  9108. })
  9109. });
  9110. //快捷键
  9111. me.addshortcutkey({
  9112. "Undo":"ctrl+90", //undo
  9113. "Redo":"ctrl+89" //redo
  9114. });
  9115. var isCollapsed = true;
  9116. me.addListener('keydown', function (type, evt) {
  9117. var me = this;
  9118. var keyCode = evt.keyCode || evt.which;
  9119. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  9120. if (inputType)
  9121. return;
  9122. if(!me.selection.getRange().collapsed){
  9123. me.undoManger.save(false,true);
  9124. isCollapsed = false;
  9125. return;
  9126. }
  9127. if (me.undoManger.list.length == 0) {
  9128. me.undoManger.save(true);
  9129. }
  9130. clearTimeout(saveSceneTimer);
  9131. function save(cont){
  9132. if (cont.selection.getRange().collapsed)
  9133. cont.fireEvent('contentchange');
  9134. cont.undoManger.save(false,true);
  9135. cont.fireEvent('selectionchange');
  9136. }
  9137. saveSceneTimer = setTimeout(function(){
  9138. if(inputType){
  9139. var interalTimer = setInterval(function(){
  9140. if(!inputType){
  9141. save(me);
  9142. clearInterval(interalTimer)
  9143. }
  9144. },300)
  9145. return;
  9146. }
  9147. save(me);
  9148. },200);
  9149. lastKeyCode = keyCode;
  9150. keycont++;
  9151. if (keycont >= maxInputCount ) {
  9152. save(me)
  9153. }
  9154. }
  9155. });
  9156. me.addListener('keyup', function (type, evt) {
  9157. var keyCode = evt.keyCode || evt.which;
  9158. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  9159. if (inputType)
  9160. return;
  9161. if(!isCollapsed){
  9162. this.undoManger.save(false,true);
  9163. isCollapsed = true;
  9164. }
  9165. }
  9166. });
  9167. };
  9168. ///import core
  9169. ///import plugins/inserthtml.js
  9170. ///import plugins/undo.js
  9171. ///import plugins/serialize.js
  9172. ///commands 粘贴
  9173. ///commandsName PastePlain
  9174. ///commandsTitle 纯文本粘贴模式
  9175. /*
  9176. ** @description 粘贴
  9177. * @author zhanyi
  9178. */
  9179. UE.plugins['paste'] = function () {
  9180. function getClipboardData(callback) {
  9181. var doc = this.document;
  9182. if (doc.getElementById('baidu_pastebin')) {
  9183. return;
  9184. }
  9185. var range = this.selection.getRange(),
  9186. bk = range.createBookmark(),
  9187. //创建剪贴的容器div
  9188. pastebin = doc.createElement('div');
  9189. pastebin.id = 'baidu_pastebin';
  9190. // Safari 要求div必须有内容,才能粘贴内容进来
  9191. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  9192. doc.body.appendChild(pastebin);
  9193. //trace:717 隐藏的span不能得到top
  9194. //bk.start.innerHTML = '&nbsp;';
  9195. bk.start.style.display = '';
  9196. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  9197. //要在现在光标平行的位置加入,否则会出现跳动的问题
  9198. domUtils.getXY(bk.start).y + 'px';
  9199. range.selectNodeContents(pastebin).select(true);
  9200. setTimeout(function () {
  9201. if (browser.webkit) {
  9202. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  9203. if (domUtils.isEmptyNode(pi)) {
  9204. domUtils.remove(pi);
  9205. } else {
  9206. pastebin = pi;
  9207. break;
  9208. }
  9209. }
  9210. }
  9211. try {
  9212. pastebin.parentNode.removeChild(pastebin);
  9213. } catch (e) {
  9214. }
  9215. range.moveToBookmark(bk).select(true);
  9216. callback(pastebin);
  9217. }, 0);
  9218. }
  9219. var me = this;
  9220. var txtContent, htmlContent, address;
  9221. function filter(div) {
  9222. var html;
  9223. if (div.firstChild) {
  9224. //去掉cut中添加的边界值
  9225. var nodes = domUtils.getElementsByTagName(div, 'span');
  9226. for (var i = 0, ni; ni = nodes[i++];) {
  9227. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  9228. domUtils.remove(ni);
  9229. }
  9230. }
  9231. if (browser.webkit) {
  9232. var brs = div.querySelectorAll('div br');
  9233. for (var i = 0, bi; bi = brs[i++];) {
  9234. var pN = bi.parentNode;
  9235. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  9236. pN.innerHTML = '<p><br/></p>';
  9237. domUtils.remove(pN);
  9238. }
  9239. }
  9240. var divs = div.querySelectorAll('#baidu_pastebin');
  9241. for (var i = 0, di; di = divs[i++];) {
  9242. var tmpP = me.document.createElement('p');
  9243. di.parentNode.insertBefore(tmpP, di);
  9244. while (di.firstChild) {
  9245. tmpP.appendChild(di.firstChild);
  9246. }
  9247. domUtils.remove(di);
  9248. }
  9249. var metas = div.querySelectorAll('meta');
  9250. for (var i = 0, ci; ci = metas[i++];) {
  9251. domUtils.remove(ci);
  9252. }
  9253. var brs = div.querySelectorAll('br');
  9254. for (i = 0; ci = brs[i++];) {
  9255. if (/^apple-/i.test(ci.className)) {
  9256. domUtils.remove(ci);
  9257. }
  9258. }
  9259. }
  9260. if (browser.gecko) {
  9261. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  9262. for (i = 0; ci = dirtyNodes[i++];) {
  9263. ci.removeAttribute('_moz_dirty');
  9264. }
  9265. }
  9266. if (!browser.ie) {
  9267. var spans = div.querySelectorAll('span.Apple-style-span');
  9268. for (var i = 0, ci; ci = spans[i++];) {
  9269. domUtils.remove(ci, true);
  9270. }
  9271. }
  9272. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  9273. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  9274. //过滤word粘贴过来的冗余属性
  9275. html = UE.filterWord(html);
  9276. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  9277. var root = UE.htmlparser(html);
  9278. //如果给了过滤规则就先进行过滤
  9279. if (me.options.filterRules) {
  9280. UE.filterNode(root, me.options.filterRules);
  9281. }
  9282. //执行默认的处理
  9283. me.filterInputRule(root);
  9284. //针对chrome的处理
  9285. if (browser.webkit) {
  9286. var br = root.lastChild();
  9287. if (br && br.type == 'element' && br.tagName == 'br') {
  9288. root.removeChild(br)
  9289. }
  9290. utils.each(me.body.querySelectorAll('div'), function (node) {
  9291. if (domUtils.isEmptyBlock(node)) {
  9292. domUtils.remove(node)
  9293. }
  9294. })
  9295. }
  9296. html = {'html': root.toHtml()};
  9297. me.fireEvent('beforepaste', html, root);
  9298. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  9299. if(!html.html){
  9300. return;
  9301. }
  9302. root = UE.htmlparser(html.html,true);
  9303. //如果开启了纯文本模式
  9304. if (me.queryCommandState('pasteplain') === 1) {
  9305. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  9306. } else {
  9307. //文本模式
  9308. UE.filterNode(root, me.options.filterTxtRules);
  9309. txtContent = root.toHtml();
  9310. //完全模式
  9311. htmlContent = html.html;
  9312. address = me.selection.getRange().createAddress(true);
  9313. me.execCommand('insertHtml', htmlContent, true);
  9314. }
  9315. me.fireEvent("afterpaste", html);
  9316. }
  9317. }
  9318. me.addListener('pasteTransfer', function (cmd, plainType) {
  9319. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  9320. var range = me.selection.getRange();
  9321. range.moveToAddress(address, true);
  9322. if (!range.collapsed) {
  9323. while (!domUtils.isBody(range.startContainer)
  9324. ) {
  9325. var start = range.startContainer;
  9326. if(start.nodeType == 1){
  9327. start = start.childNodes[range.startOffset];
  9328. if(!start){
  9329. range.setStartBefore(range.startContainer);
  9330. continue;
  9331. }
  9332. var pre = start.previousSibling;
  9333. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  9334. range.setStartBefore(pre)
  9335. }
  9336. }
  9337. if(range.startOffset == 0){
  9338. range.setStartBefore(range.startContainer);
  9339. }else{
  9340. break;
  9341. }
  9342. }
  9343. while (!domUtils.isBody(range.endContainer)
  9344. ) {
  9345. var end = range.endContainer;
  9346. if(end.nodeType == 1){
  9347. end = end.childNodes[range.endOffset];
  9348. if(!end){
  9349. range.setEndAfter(range.endContainer);
  9350. continue;
  9351. }
  9352. var next = end.nextSibling;
  9353. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  9354. range.setEndAfter(next)
  9355. }
  9356. }
  9357. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  9358. range.setEndAfter(range.endContainer);
  9359. }else{
  9360. break;
  9361. }
  9362. }
  9363. }
  9364. range.deleteContents();
  9365. range.select(true);
  9366. me.__hasEnterExecCommand = true;
  9367. var html = htmlContent;
  9368. if (plainType === 2) {
  9369. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  9370. tagName = tagName.toLowerCase();
  9371. if ({img: 1}[tagName]) {
  9372. return a;
  9373. }
  9374. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  9375. if ({
  9376. 'src': 1,
  9377. 'href': 1,
  9378. 'name': 1
  9379. }[atr.toLowerCase()]) {
  9380. return atr + '=' + val + ' '
  9381. }
  9382. return ''
  9383. });
  9384. if ({
  9385. 'span': 1,
  9386. 'div': 1
  9387. }[tagName]) {
  9388. return ''
  9389. } else {
  9390. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  9391. }
  9392. });
  9393. } else if (plainType) {
  9394. html = txtContent;
  9395. }
  9396. me.execCommand('inserthtml', html, true);
  9397. me.__hasEnterExecCommand = false;
  9398. var rng = me.selection.getRange();
  9399. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  9400. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  9401. ) {
  9402. rng.setStartBefore(rng.startContainer);
  9403. }
  9404. var tmpAddress = rng.createAddress(true);
  9405. address.endAddress = tmpAddress.startAddress;
  9406. }
  9407. });
  9408. me.addListener('ready', function () {
  9409. domUtils.on(me.body, 'cut', function () {
  9410. var range = me.selection.getRange();
  9411. if (!range.collapsed && me.undoManger) {
  9412. me.undoManger.save();
  9413. }
  9414. });
  9415. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  9416. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  9417. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  9418. return;
  9419. }
  9420. getClipboardData.call(me, function (div) {
  9421. filter(div);
  9422. });
  9423. });
  9424. });
  9425. };
  9426. ///import core
  9427. ///commands 有序列表,无序列表
  9428. ///commandsName InsertOrderedList,InsertUnorderedList
  9429. ///commandsTitle 有序列表,无序列表
  9430. /**
  9431. * 有序列表
  9432. * @function
  9433. * @name baidu.editor.execCommand
  9434. * @param {String} cmdName insertorderlist插入有序列表
  9435. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  9436. * @author zhanyi
  9437. */
  9438. /**
  9439. * 无序链接
  9440. * @function
  9441. * @name baidu.editor.execCommand
  9442. * @param {String} cmdName insertunorderlist插入无序列表
  9443. * * @param {String} style 值为:circle,disc,square
  9444. * @author zhanyi
  9445. */
  9446. UE.plugins['list'] = function () {
  9447. var me = this,
  9448. notExchange = {
  9449. 'TD':1,
  9450. 'PRE':1,
  9451. 'BLOCKQUOTE':1
  9452. };
  9453. var customStyle = {
  9454. 'cn' : 'cn-1-',
  9455. 'cn1' : 'cn-2-',
  9456. 'cn2' : 'cn-3-',
  9457. 'num': 'num-1-',
  9458. 'num1' : 'num-2-',
  9459. 'num2' : 'num-3-',
  9460. 'dash' : 'dash',
  9461. 'dot':'dot'
  9462. };
  9463. me.setOpt( {
  9464. 'insertorderedlist':{
  9465. 'num':'',
  9466. 'num1':'',
  9467. 'num2':'',
  9468. 'cn':'',
  9469. 'cn1':'',
  9470. 'cn2':'',
  9471. 'decimal':'',
  9472. 'lower-alpha':'',
  9473. 'lower-roman':'',
  9474. 'upper-alpha':'',
  9475. 'upper-roman':''
  9476. },
  9477. 'insertunorderedlist':{
  9478. 'circle':'',
  9479. 'disc':'',
  9480. 'square':'',
  9481. 'dash' : '',
  9482. 'dot':''
  9483. },
  9484. listDefaultPaddingLeft : '30',
  9485. listiconpath : 'http://bs.baidu.com/listicon/',
  9486. maxListLevel : -1//-1不限制
  9487. } );
  9488. function listToArray(list){
  9489. var arr = [];
  9490. for(var p in list){
  9491. arr.push(p)
  9492. }
  9493. return arr;
  9494. }
  9495. var listStyle = {
  9496. 'OL':listToArray(me.options.insertorderedlist),
  9497. 'UL':listToArray(me.options.insertunorderedlist)
  9498. };
  9499. var liiconpath = me.options.listiconpath;
  9500. //根据用户配置,调整customStyle
  9501. for(var s in customStyle){
  9502. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  9503. delete customStyle[s];
  9504. }
  9505. }
  9506. me.ready(function () {
  9507. var customCss = [];
  9508. for(var p in customStyle){
  9509. if(p == 'dash' || p == 'dot'){
  9510. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  9511. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  9512. }else{
  9513. for(var i= 0;i<99;i++){
  9514. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  9515. }
  9516. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  9517. }
  9518. switch(p){
  9519. case 'cn':
  9520. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  9521. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9522. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  9523. break;
  9524. case 'cn1':
  9525. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  9526. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9527. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  9528. break;
  9529. case 'cn2':
  9530. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  9531. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  9532. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  9533. break;
  9534. case 'num':
  9535. case 'num1':
  9536. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  9537. break;
  9538. case 'num2':
  9539. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  9540. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9541. break;
  9542. case 'dash':
  9543. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  9544. break;
  9545. case 'dot':
  9546. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  9547. }
  9548. }
  9549. customCss.push('.list-paddingleft-1{padding-left:0}');
  9550. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  9551. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  9552. //如果不给宽度会在自定应样式里出现滚动条
  9553. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  9554. });
  9555. //单独处理剪切的问题
  9556. me.ready(function(){
  9557. domUtils.on(me.body,'cut',function(){
  9558. setTimeout(function(){
  9559. var rng = me.selection.getRange(),li;
  9560. //trace:3416
  9561. if(!rng.collapsed){
  9562. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  9563. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  9564. var pn = li.parentNode,node;
  9565. if(node = pn.previousSibling){
  9566. domUtils.remove(pn);
  9567. rng.setStartAtLast(node).collapse(true);
  9568. rng.select(true);
  9569. }else if(node = pn.nextSibling){
  9570. domUtils.remove(pn);
  9571. rng.setStartAtFirst(node).collapse(true);
  9572. rng.select(true);
  9573. }else{
  9574. var tmpNode = me.document.createElement('p');
  9575. domUtils.fillNode(me.document,tmpNode);
  9576. pn.parentNode.insertBefore(tmpNode,pn);
  9577. domUtils.remove(pn);
  9578. rng.setStart(tmpNode,0).collapse(true);
  9579. rng.select(true);
  9580. }
  9581. }
  9582. }
  9583. }
  9584. })
  9585. })
  9586. });
  9587. function getStyle(node){
  9588. var cls = node.className;
  9589. if(domUtils.hasClass(node,/custom_/)){
  9590. return cls.match(/custom_(\w+)/)[1]
  9591. }
  9592. return domUtils.getStyle(node, 'list-style-type')
  9593. }
  9594. me.addListener('beforepaste',function(type,html){
  9595. var me = this,
  9596. rng = me.selection.getRange(),li;
  9597. var root = UE.htmlparser(html.html,true);
  9598. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  9599. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  9600. utils.each(root.getNodesByTagName(tagName),function(n){
  9601. n.tagName = list.tagName;
  9602. n.setAttr();
  9603. if(n.parentNode === root){
  9604. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  9605. }else{
  9606. var className = n.parentNode.getAttr('class');
  9607. if(className && /custom_/.test(className)){
  9608. type = className.match(/custom_(\w+)/)[1]
  9609. }else{
  9610. type = n.parentNode.getStyle('list-style-type');
  9611. }
  9612. if(!type){
  9613. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  9614. }
  9615. }
  9616. var index = utils.indexOf(listStyle[list.tagName], type);
  9617. if(n.parentNode !== root)
  9618. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  9619. var currentStyle = listStyle[list.tagName][index];
  9620. if(customStyle[currentStyle]){
  9621. n.setAttr('class', 'custom_' + currentStyle)
  9622. }else{
  9623. n.setStyle('list-style-type',currentStyle)
  9624. }
  9625. })
  9626. }
  9627. html.html = root.toHtml();
  9628. });
  9629. //进入编辑器的li要套p标签
  9630. me.addInputRule(function(root){
  9631. utils.each(root.getNodesByTagName('li'),function(li){
  9632. var tmpP = UE.uNode.createElement('p');
  9633. for(var i= 0,ci;ci=li.children[i];){
  9634. if(ci.type == 'text' || dtd.p[ci.tagName]){
  9635. tmpP.appendChild(ci);
  9636. }else{
  9637. if(tmpP.firstChild()){
  9638. li.insertBefore(tmpP,ci);
  9639. tmpP = UE.uNode.createElement('p');
  9640. i = i + 2;
  9641. }else{
  9642. i++;
  9643. }
  9644. }
  9645. }
  9646. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  9647. li.appendChild(tmpP);
  9648. }
  9649. //trace:3357
  9650. //p不能为空
  9651. if (!tmpP.firstChild()) {
  9652. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9653. }
  9654. //去掉末尾的空白
  9655. var p = li.firstChild();
  9656. var lastChild = p.lastChild();
  9657. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  9658. p.removeChild(lastChild)
  9659. }
  9660. });
  9661. var orderlisttype = {
  9662. 'num1':/^\d+\)/,
  9663. 'decimal':/^\d+\./,
  9664. 'lower-alpha':/^[a-z]+\)/,
  9665. 'upper-alpha':/^[A-Z]+\./,
  9666. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  9667. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  9668. },
  9669. unorderlisttype = {
  9670. 'square':'n'
  9671. };
  9672. function checkListType(content,container){
  9673. var span = container.firstChild();
  9674. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  9675. for(var p in unorderlisttype){
  9676. if(unorderlisttype[p] == span.data){
  9677. return p
  9678. }
  9679. }
  9680. return 'disc'
  9681. }
  9682. for(var p in orderlisttype){
  9683. if(orderlisttype[p].test(content)){
  9684. return p;
  9685. }
  9686. }
  9687. }
  9688. utils.each(root.getNodesByTagName('p'),function(node){
  9689. if(node.getAttr('class') != 'MsoListParagraph'){
  9690. return
  9691. }
  9692. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  9693. node.setStyle('margin','');
  9694. node.setStyle('margin-left','');
  9695. node.setAttr('class','');
  9696. function appendLi(list,p,type){
  9697. if(list.tagName == 'ol'){
  9698. if(browser.ie){
  9699. var first = p.firstChild();
  9700. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  9701. p.removeChild(first);
  9702. }
  9703. }else{
  9704. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  9705. }
  9706. }else{
  9707. p.removeChild(p.firstChild())
  9708. }
  9709. var li = UE.uNode.createElement('li');
  9710. li.appendChild(p);
  9711. list.appendChild(li);
  9712. }
  9713. var tmp = node,type,cacheNode = node;
  9714. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  9715. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  9716. if(customStyle[type]){
  9717. list.setAttr('class','custom_'+type)
  9718. }else{
  9719. list.setStyle('list-style-type',type)
  9720. }
  9721. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  9722. tmp = node.nextSibling();
  9723. if(!tmp){
  9724. node.parentNode.insertBefore(list,node)
  9725. }
  9726. appendLi(list,node,type);
  9727. node = tmp;
  9728. }
  9729. if(!list.parentNode && node && node.parentNode){
  9730. node.parentNode.insertBefore(list,node)
  9731. }
  9732. }
  9733. var span = cacheNode.firstChild();
  9734. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  9735. span.parentNode.removeChild(span)
  9736. }
  9737. })
  9738. });
  9739. //调整索引标签
  9740. me.addListener('contentchange',function(){
  9741. adjustListStyle(me.document)
  9742. });
  9743. function adjustListStyle(doc,ignore){
  9744. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  9745. if(!domUtils.inDoc(node,doc))
  9746. return;
  9747. var parent = node.parentNode;
  9748. if(parent.tagName == node.tagName){
  9749. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  9750. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  9751. if(nodeStyleType == parentStyleType){
  9752. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  9753. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  9754. setListStyle(node,listStyle[node.tagName][styleIndex])
  9755. }
  9756. }
  9757. var index = 0,type = 2;
  9758. if( domUtils.hasClass(node,/custom_/)){
  9759. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  9760. type = 1;
  9761. }
  9762. }else{
  9763. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  9764. type = 3;
  9765. }
  9766. }
  9767. var style = domUtils.getStyle(node, 'list-style-type');
  9768. style && (node.style.cssText = 'list-style-type:' + style);
  9769. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  9770. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  9771. li.style.cssText && (li.style.cssText = '');
  9772. if(!li.firstChild){
  9773. domUtils.remove(li);
  9774. return;
  9775. }
  9776. if(li.parentNode !== node){
  9777. return;
  9778. }
  9779. index++;
  9780. if(domUtils.hasClass(node,/custom_/) ){
  9781. var paddingLeft = 1,currentStyle = getStyle(node);
  9782. if(node.tagName == 'OL'){
  9783. if(currentStyle){
  9784. switch(currentStyle){
  9785. case 'cn' :
  9786. case 'cn1':
  9787. case 'cn2':
  9788. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  9789. paddingLeft = 2
  9790. }else if(index > 20){
  9791. paddingLeft = 3
  9792. }
  9793. break;
  9794. case 'num2' :
  9795. if(index > 9){
  9796. paddingLeft = 2
  9797. }
  9798. }
  9799. }
  9800. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  9801. }else{
  9802. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  9803. }
  9804. }else{
  9805. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  9806. }
  9807. var className = li.getAttribute('class');
  9808. if(className !== null && !className.replace(/\s/g,'')){
  9809. domUtils.removeAttributes(li,'class')
  9810. }
  9811. });
  9812. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  9813. })
  9814. }
  9815. function adjustList(list, tag, style,ignoreEmpty) {
  9816. var nextList = list.nextSibling;
  9817. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  9818. domUtils.moveChild(nextList, list);
  9819. if (nextList.childNodes.length == 0) {
  9820. domUtils.remove(nextList);
  9821. }
  9822. }
  9823. if(nextList && domUtils.isFillChar(nextList)){
  9824. domUtils.remove(nextList);
  9825. }
  9826. var preList = list.previousSibling;
  9827. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  9828. domUtils.moveChild(list, preList);
  9829. }
  9830. if(preList && domUtils.isFillChar(preList)){
  9831. domUtils.remove(preList);
  9832. }
  9833. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  9834. if(getStyle(list)){
  9835. adjustListStyle(list.ownerDocument,true)
  9836. }
  9837. }
  9838. function setListStyle(list,style){
  9839. if(customStyle[style]){
  9840. list.className = 'custom_' + style;
  9841. }
  9842. try{
  9843. domUtils.setStyle(list, 'list-style-type', style);
  9844. }catch(e){}
  9845. }
  9846. function clearEmptySibling(node) {
  9847. var tmpNode = node.previousSibling;
  9848. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  9849. domUtils.remove(tmpNode);
  9850. }
  9851. tmpNode = node.nextSibling;
  9852. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  9853. domUtils.remove(tmpNode);
  9854. }
  9855. }
  9856. me.addListener('keydown', function (type, evt) {
  9857. function preventAndSave() {
  9858. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  9859. me.fireEvent('contentchange');
  9860. me.undoManger && me.undoManger.save();
  9861. }
  9862. function findList(node,filterFn){
  9863. while(node && !domUtils.isBody(node)){
  9864. if(filterFn(node)){
  9865. return null
  9866. }
  9867. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  9868. return node;
  9869. }
  9870. node = node.parentNode;
  9871. }
  9872. return null;
  9873. }
  9874. var keyCode = evt.keyCode || evt.which;
  9875. if (keyCode == 13 && !evt.shiftKey) {//回车
  9876. var rng = me.selection.getRange(),
  9877. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  9878. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  9879. if(parent && parent.tagName != 'PRE' && !li){
  9880. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  9881. if(/^\s*1\s*\.[^\d]/.test(html)){
  9882. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  9883. rng.setStartAtLast(parent).collapse(true).select();
  9884. me.__hasEnterExecCommand = true;
  9885. me.execCommand('insertorderedlist');
  9886. me.__hasEnterExecCommand = false;
  9887. }
  9888. }
  9889. var range = me.selection.getRange(),
  9890. start = findList(range.startContainer,function (node) {
  9891. return node.tagName == 'TABLE';
  9892. }),
  9893. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  9894. return node.tagName == 'TABLE';
  9895. });
  9896. if (start && end && start === end) {
  9897. if (!range.collapsed) {
  9898. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9899. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  9900. if (start && end && start === end) {
  9901. range.deleteContents();
  9902. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9903. if (li && domUtils.isEmptyBlock(li)) {
  9904. pre = li.previousSibling;
  9905. next = li.nextSibling;
  9906. p = me.document.createElement('p');
  9907. domUtils.fillNode(me.document, p);
  9908. parentList = li.parentNode;
  9909. if (pre && next) {
  9910. range.setStart(next, 0).collapse(true).select(true);
  9911. domUtils.remove(li);
  9912. } else {
  9913. if (!pre && !next || !pre) {
  9914. parentList.parentNode.insertBefore(p, parentList);
  9915. } else {
  9916. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  9917. }
  9918. domUtils.remove(li);
  9919. if (!parentList.firstChild) {
  9920. domUtils.remove(parentList);
  9921. }
  9922. range.setStart(p, 0).setCursor();
  9923. }
  9924. preventAndSave();
  9925. return;
  9926. }
  9927. } else {
  9928. var tmpRange = range.cloneRange(),
  9929. bk = tmpRange.collapse(false).createBookmark();
  9930. range.deleteContents();
  9931. tmpRange.moveToBookmark(bk);
  9932. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  9933. clearEmptySibling(li);
  9934. tmpRange.select();
  9935. preventAndSave();
  9936. return;
  9937. }
  9938. }
  9939. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9940. if (li) {
  9941. if (domUtils.isEmptyBlock(li)) {
  9942. bk = range.createBookmark();
  9943. var parentList = li.parentNode;
  9944. if (li !== parentList.lastChild) {
  9945. domUtils.breakParent(li, parentList);
  9946. clearEmptySibling(li);
  9947. } else {
  9948. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  9949. if (domUtils.isEmptyNode(parentList)) {
  9950. domUtils.remove(parentList);
  9951. }
  9952. }
  9953. //嵌套不处理
  9954. if (!dtd.$list[li.parentNode.tagName]) {
  9955. if (!domUtils.isBlockElm(li.firstChild)) {
  9956. p = me.document.createElement('p');
  9957. li.parentNode.insertBefore(p, li);
  9958. while (li.firstChild) {
  9959. p.appendChild(li.firstChild);
  9960. }
  9961. domUtils.remove(li);
  9962. } else {
  9963. domUtils.remove(li, true);
  9964. }
  9965. }
  9966. range.moveToBookmark(bk).select();
  9967. } else {
  9968. var first = li.firstChild;
  9969. if (!first || !domUtils.isBlockElm(first)) {
  9970. var p = me.document.createElement('p');
  9971. !li.firstChild && domUtils.fillNode(me.document, p);
  9972. while (li.firstChild) {
  9973. p.appendChild(li.firstChild);
  9974. }
  9975. li.appendChild(p);
  9976. first = p;
  9977. }
  9978. var span = me.document.createElement('span');
  9979. range.insertNode(span);
  9980. domUtils.breakParent(span, li);
  9981. var nextLi = span.nextSibling;
  9982. first = nextLi.firstChild;
  9983. if (!first) {
  9984. p = me.document.createElement('p');
  9985. domUtils.fillNode(me.document, p);
  9986. nextLi.appendChild(p);
  9987. first = p;
  9988. }
  9989. if (domUtils.isEmptyNode(first)) {
  9990. first.innerHTML = '';
  9991. domUtils.fillNode(me.document, first);
  9992. }
  9993. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  9994. domUtils.remove(span);
  9995. var pre = nextLi.previousSibling;
  9996. if (pre && domUtils.isEmptyBlock(pre)) {
  9997. pre.innerHTML = '<p></p>';
  9998. domUtils.fillNode(me.document, pre.firstChild);
  9999. }
  10000. }
  10001. // }
  10002. preventAndSave();
  10003. }
  10004. }
  10005. }
  10006. if (keyCode == 8) {
  10007. //修中ie中li下的问题
  10008. range = me.selection.getRange();
  10009. if (range.collapsed && domUtils.isStartInblock(range)) {
  10010. tmpRange = range.cloneRange().trimBoundary();
  10011. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  10012. //要在li的最左边,才能处理
  10013. if (li && domUtils.isStartInblock(tmpRange)) {
  10014. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  10015. if (start && start !== li.firstChild) {
  10016. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  10017. domUtils.breakParent(start,parentList);
  10018. clearEmptySibling(start);
  10019. me.fireEvent('contentchange');
  10020. range.setStart(start,0).setCursor(false,true);
  10021. me.fireEvent('saveScene');
  10022. domUtils.preventDefault(evt);
  10023. return;
  10024. }
  10025. if (li && (pre = li.previousSibling)) {
  10026. if (keyCode == 46 && li.childNodes.length) {
  10027. return;
  10028. }
  10029. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  10030. if (dtd.$list[pre.tagName]) {
  10031. pre = pre.lastChild;
  10032. }
  10033. me.undoManger && me.undoManger.save();
  10034. first = li.firstChild;
  10035. if (domUtils.isBlockElm(first)) {
  10036. if (domUtils.isEmptyNode(first)) {
  10037. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  10038. pre.appendChild(first);
  10039. range.setStart(first, 0).setCursor(false, true);
  10040. //first不是唯一的节点
  10041. while (li.firstChild) {
  10042. pre.appendChild(li.firstChild);
  10043. }
  10044. } else {
  10045. span = me.document.createElement('span');
  10046. range.insertNode(span);
  10047. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  10048. if (domUtils.isEmptyBlock(pre)) {
  10049. pre.innerHTML = '';
  10050. }
  10051. domUtils.moveChild(li, pre);
  10052. range.setStartBefore(span).collapse(true).select(true);
  10053. domUtils.remove(span);
  10054. }
  10055. } else {
  10056. if (domUtils.isEmptyNode(li)) {
  10057. var p = me.document.createElement('p');
  10058. pre.appendChild(p);
  10059. range.setStart(p, 0).setCursor();
  10060. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  10061. } else {
  10062. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  10063. while (li.firstChild) {
  10064. pre.appendChild(li.firstChild);
  10065. }
  10066. }
  10067. }
  10068. domUtils.remove(li);
  10069. me.fireEvent('contentchange');
  10070. me.fireEvent('saveScene');
  10071. domUtils.preventDefault(evt);
  10072. return;
  10073. }
  10074. //trace:980
  10075. if (li && !li.previousSibling) {
  10076. var parentList = li.parentNode;
  10077. var bk = range.createBookmark();
  10078. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  10079. parentList.parentNode.insertBefore(li,parentList);
  10080. if(domUtils.isEmptyNode(parentList)){
  10081. domUtils.remove(parentList)
  10082. }
  10083. }else{
  10084. while(li.firstChild){
  10085. parentList.parentNode.insertBefore(li.firstChild,parentList);
  10086. }
  10087. domUtils.remove(li);
  10088. if(domUtils.isEmptyNode(parentList)){
  10089. domUtils.remove(parentList)
  10090. }
  10091. }
  10092. range.moveToBookmark(bk).setCursor(false,true);
  10093. me.fireEvent('contentchange');
  10094. me.fireEvent('saveScene');
  10095. domUtils.preventDefault(evt);
  10096. return;
  10097. }
  10098. }
  10099. }
  10100. }
  10101. });
  10102. me.addListener('keyup',function(type, evt){
  10103. var keyCode = evt.keyCode || evt.which;
  10104. if (keyCode == 8) {
  10105. var rng = me.selection.getRange(),list;
  10106. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  10107. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  10108. }
  10109. }
  10110. });
  10111. //处理tab键
  10112. me.addListener('tabkeydown',function(){
  10113. var range = me.selection.getRange();
  10114. //控制级数
  10115. function checkLevel(li){
  10116. if(me.options.maxListLevel != -1){
  10117. var level = li.parentNode,levelNum = 0;
  10118. while(/[ou]l/i.test(level.tagName)){
  10119. levelNum++;
  10120. level = level.parentNode;
  10121. }
  10122. if(levelNum >= me.options.maxListLevel){
  10123. return true;
  10124. }
  10125. }
  10126. }
  10127. //只以开始为准
  10128. //todo 后续改进
  10129. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  10130. if(li){
  10131. var bk;
  10132. if(range.collapsed){
  10133. if(checkLevel(li))
  10134. return true;
  10135. var parentLi = li.parentNode,
  10136. list = me.document.createElement(parentLi.tagName),
  10137. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  10138. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  10139. var currentStyle = listStyle[list.tagName][index];
  10140. setListStyle(list,currentStyle);
  10141. if(domUtils.isStartInblock(range)){
  10142. me.fireEvent('saveScene');
  10143. bk = range.createBookmark();
  10144. parentLi.insertBefore(list, li);
  10145. list.appendChild(li);
  10146. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  10147. me.fireEvent('contentchange');
  10148. range.moveToBookmark(bk).select(true);
  10149. return true;
  10150. }
  10151. }else{
  10152. me.fireEvent('saveScene');
  10153. bk = range.createBookmark();
  10154. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  10155. if(domUtils.isTagNode(ci,'ol ul')){
  10156. closeList = ci;
  10157. break;
  10158. }
  10159. }
  10160. var current = li;
  10161. if(bk.end){
  10162. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  10163. if(checkLevel(current)){
  10164. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  10165. continue;
  10166. }
  10167. var parentLi = current.parentNode,
  10168. list = me.document.createElement(parentLi.tagName),
  10169. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  10170. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  10171. var currentStyle = listStyle[list.tagName][currentIndex];
  10172. setListStyle(list,currentStyle);
  10173. parentLi.insertBefore(list, current);
  10174. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  10175. li = current.nextSibling;
  10176. list.appendChild(current);
  10177. if(!li || domUtils.isTagNode(li,'ol ul')){
  10178. if(li){
  10179. while(li = li.firstChild){
  10180. if(li.tagName == 'LI'){
  10181. break;
  10182. }
  10183. }
  10184. }else{
  10185. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  10186. }
  10187. break;
  10188. }
  10189. current = li;
  10190. }
  10191. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  10192. current = li;
  10193. }
  10194. }
  10195. me.fireEvent('contentchange');
  10196. range.moveToBookmark(bk).select();
  10197. return true;
  10198. }
  10199. }
  10200. });
  10201. function getLi(start){
  10202. while(start && !domUtils.isBody(start)){
  10203. if(start.nodeName == 'TABLE'){
  10204. return null;
  10205. }
  10206. if(start.nodeName == 'LI'){
  10207. return start
  10208. }
  10209. start = start.parentNode;
  10210. }
  10211. }
  10212. me.commands['insertorderedlist'] =
  10213. me.commands['insertunorderedlist'] = {
  10214. execCommand:function (command, style) {
  10215. if (!style) {
  10216. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  10217. }
  10218. var me = this,
  10219. range = this.selection.getRange(),
  10220. filterFn = function (node) {
  10221. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  10222. },
  10223. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  10224. frag = me.document.createDocumentFragment();
  10225. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  10226. //range.shrinkBoundary();//.adjustmentBoundary();
  10227. range.adjustmentBoundary().shrinkBoundary();
  10228. var bko = range.createBookmark(true),
  10229. start = getLi(me.document.getElementById(bko.start)),
  10230. modifyStart = 0,
  10231. end = getLi(me.document.getElementById(bko.end)),
  10232. modifyEnd = 0,
  10233. startParent, endParent,
  10234. list, tmp;
  10235. if (start || end) {
  10236. start && (startParent = start.parentNode);
  10237. if (!bko.end) {
  10238. end = start;
  10239. }
  10240. end && (endParent = end.parentNode);
  10241. if (startParent === endParent) {
  10242. while (start !== end) {
  10243. tmp = start;
  10244. start = start.nextSibling;
  10245. if (!domUtils.isBlockElm(tmp.firstChild)) {
  10246. var p = me.document.createElement('p');
  10247. while (tmp.firstChild) {
  10248. p.appendChild(tmp.firstChild);
  10249. }
  10250. tmp.appendChild(p);
  10251. }
  10252. frag.appendChild(tmp);
  10253. }
  10254. tmp = me.document.createElement('span');
  10255. startParent.insertBefore(tmp, end);
  10256. if (!domUtils.isBlockElm(end.firstChild)) {
  10257. p = me.document.createElement('p');
  10258. while (end.firstChild) {
  10259. p.appendChild(end.firstChild);
  10260. }
  10261. end.appendChild(p);
  10262. }
  10263. frag.appendChild(end);
  10264. domUtils.breakParent(tmp, startParent);
  10265. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  10266. domUtils.remove(tmp.previousSibling);
  10267. }
  10268. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  10269. domUtils.remove(tmp.nextSibling)
  10270. }
  10271. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  10272. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  10273. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.childNodes[i++];) {
  10274. if(domUtils.isTagNode(ci,'ol ul')){
  10275. utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  10276. while(li.firstChild){
  10277. tmpFrag.appendChild(li.firstChild);
  10278. }
  10279. });
  10280. }else{
  10281. while (ci.firstChild) {
  10282. tmpFrag.appendChild(ci.firstChild);
  10283. }
  10284. }
  10285. }
  10286. tmp.parentNode.insertBefore(tmpFrag, tmp);
  10287. } else {
  10288. list = me.document.createElement(tag);
  10289. setListStyle(list,style);
  10290. list.appendChild(frag);
  10291. tmp.parentNode.insertBefore(list, tmp);
  10292. }
  10293. domUtils.remove(tmp);
  10294. list && adjustList(list, tag, style);
  10295. range.moveToBookmark(bko).select();
  10296. return;
  10297. }
  10298. //开始
  10299. if (start) {
  10300. while (start) {
  10301. tmp = start.nextSibling;
  10302. if (domUtils.isTagNode(start, 'ol ul')) {
  10303. frag.appendChild(start);
  10304. } else {
  10305. var tmpfrag = me.document.createDocumentFragment(),
  10306. hasBlock = 0;
  10307. while (start.firstChild) {
  10308. if (domUtils.isBlockElm(start.firstChild)) {
  10309. hasBlock = 1;
  10310. }
  10311. tmpfrag.appendChild(start.firstChild);
  10312. }
  10313. if (!hasBlock) {
  10314. var tmpP = me.document.createElement('p');
  10315. tmpP.appendChild(tmpfrag);
  10316. frag.appendChild(tmpP);
  10317. } else {
  10318. frag.appendChild(tmpfrag);
  10319. }
  10320. domUtils.remove(start);
  10321. }
  10322. start = tmp;
  10323. }
  10324. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  10325. if (domUtils.isEmptyNode(startParent)) {
  10326. range.setStartBefore(startParent);
  10327. domUtils.remove(startParent);
  10328. } else {
  10329. range.setStartAfter(startParent);
  10330. }
  10331. modifyStart = 1;
  10332. }
  10333. if (end && domUtils.inDoc(endParent, me.document)) {
  10334. //结束
  10335. start = endParent.firstChild;
  10336. while (start && start !== end) {
  10337. tmp = start.nextSibling;
  10338. if (domUtils.isTagNode(start, 'ol ul')) {
  10339. frag.appendChild(start);
  10340. } else {
  10341. tmpfrag = me.document.createDocumentFragment();
  10342. hasBlock = 0;
  10343. while (start.firstChild) {
  10344. if (domUtils.isBlockElm(start.firstChild)) {
  10345. hasBlock = 1;
  10346. }
  10347. tmpfrag.appendChild(start.firstChild);
  10348. }
  10349. if (!hasBlock) {
  10350. tmpP = me.document.createElement('p');
  10351. tmpP.appendChild(tmpfrag);
  10352. frag.appendChild(tmpP);
  10353. } else {
  10354. frag.appendChild(tmpfrag);
  10355. }
  10356. domUtils.remove(start);
  10357. }
  10358. start = tmp;
  10359. }
  10360. var tmpDiv = domUtils.createElement(me.document, 'div', {
  10361. 'tmpDiv':1
  10362. });
  10363. domUtils.moveChild(end, tmpDiv);
  10364. frag.appendChild(tmpDiv);
  10365. domUtils.remove(end);
  10366. endParent.parentNode.insertBefore(frag, endParent);
  10367. range.setEndBefore(endParent);
  10368. if (domUtils.isEmptyNode(endParent)) {
  10369. domUtils.remove(endParent);
  10370. }
  10371. modifyEnd = 1;
  10372. }
  10373. }
  10374. if (!modifyStart) {
  10375. range.setStartBefore(me.document.getElementById(bko.start));
  10376. }
  10377. if (bko.end && !modifyEnd) {
  10378. range.setEndAfter(me.document.getElementById(bko.end));
  10379. }
  10380. range.enlarge(true, function (node) {
  10381. return notExchange[node.tagName];
  10382. });
  10383. frag = me.document.createDocumentFragment();
  10384. var bk = range.createBookmark(),
  10385. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  10386. tmpRange = range.cloneRange(),
  10387. tmpNode,
  10388. block = domUtils.isBlockElm;
  10389. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  10390. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  10391. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  10392. while (current.firstChild) {
  10393. frag.appendChild(current.firstChild);
  10394. }
  10395. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  10396. domUtils.remove(current);
  10397. current = tmpNode;
  10398. continue;
  10399. }
  10400. tmpNode = current;
  10401. tmpRange.setStartBefore(current);
  10402. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  10403. tmpNode = current;
  10404. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10405. return !notExchange[node.tagName];
  10406. });
  10407. }
  10408. if (current && block(current)) {
  10409. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  10410. if (tmp && domUtils.isBookmarkNode(tmp)) {
  10411. current = domUtils.getNextDomNode(tmp, false, filterFn);
  10412. tmpNode = tmp;
  10413. }
  10414. }
  10415. tmpRange.setEndAfter(tmpNode);
  10416. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  10417. var li = range.document.createElement('li');
  10418. li.appendChild(tmpRange.extractContents());
  10419. if(domUtils.isEmptyNode(li)){
  10420. var tmpNode = range.document.createElement('p');
  10421. while(li.firstChild){
  10422. tmpNode.appendChild(li.firstChild)
  10423. }
  10424. li.appendChild(tmpNode);
  10425. }
  10426. frag.appendChild(li);
  10427. } else {
  10428. current = domUtils.getNextDomNode(current, true, filterFn);
  10429. }
  10430. }
  10431. range.moveToBookmark(bk).collapse(true);
  10432. list = me.document.createElement(tag);
  10433. setListStyle(list,style);
  10434. list.appendChild(frag);
  10435. range.insertNode(list);
  10436. //当前list上下看能否合并
  10437. adjustList(list, tag, style);
  10438. //去掉冗余的tmpDiv
  10439. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  10440. if (ci.getAttribute('tmpDiv')) {
  10441. domUtils.remove(ci, true)
  10442. }
  10443. }
  10444. range.moveToBookmark(bko).select();
  10445. },
  10446. queryCommandState:function (command) {
  10447. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  10448. var path = this.selection.getStartElementPath();
  10449. for(var i= 0,ci;ci = path[i++];){
  10450. if(ci.nodeName == 'TABLE'){
  10451. return 0
  10452. }
  10453. if(tag == ci.nodeName.toLowerCase()){
  10454. return 1
  10455. };
  10456. }
  10457. return 0;
  10458. },
  10459. queryCommandValue:function (command) {
  10460. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  10461. var path = this.selection.getStartElementPath(),
  10462. node;
  10463. for(var i= 0,ci;ci = path[i++];){
  10464. if(ci.nodeName == 'TABLE'){
  10465. node = null;
  10466. break;
  10467. }
  10468. if(tag == ci.nodeName.toLowerCase()){
  10469. node = ci;
  10470. break;
  10471. };
  10472. }
  10473. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  10474. }
  10475. };
  10476. };
  10477. ///import core
  10478. ///import plugins/serialize.js
  10479. ///import plugins/undo.js
  10480. ///commands 查看源码
  10481. ///commandsName Source
  10482. ///commandsTitle 查看源码
  10483. (function (){
  10484. var sourceEditors = {
  10485. textarea: function (editor, holder){
  10486. var textarea = holder.ownerDocument.createElement('textarea');
  10487. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  10488. // todo: IE下只有onresize属性可用... 很纠结
  10489. if (browser.ie && browser.version < 8) {
  10490. textarea.style.width = holder.offsetWidth + 'px';
  10491. textarea.style.height = holder.offsetHeight + 'px';
  10492. holder.onresize = function (){
  10493. textarea.style.width = holder.offsetWidth + 'px';
  10494. textarea.style.height = holder.offsetHeight + 'px';
  10495. };
  10496. }
  10497. holder.appendChild(textarea);
  10498. return {
  10499. setContent: function (content){
  10500. textarea.value = content;
  10501. },
  10502. getContent: function (){
  10503. return textarea.value;
  10504. },
  10505. select: function (){
  10506. var range;
  10507. if (browser.ie) {
  10508. range = textarea.createTextRange();
  10509. range.collapse(true);
  10510. range.select();
  10511. } else {
  10512. //todo: chrome下无法设置焦点
  10513. textarea.setSelectionRange(0, 0);
  10514. textarea.focus();
  10515. }
  10516. },
  10517. dispose: function (){
  10518. holder.removeChild(textarea);
  10519. // todo
  10520. holder.onresize = null;
  10521. textarea = null;
  10522. holder = null;
  10523. }
  10524. };
  10525. },
  10526. codemirror: function (editor, holder){
  10527. var codeEditor = window.CodeMirror(holder, {
  10528. mode: "text/html",
  10529. tabMode: "indent",
  10530. lineNumbers: true,
  10531. lineWrapping:true
  10532. });
  10533. var dom = codeEditor.getWrapperElement();
  10534. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  10535. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  10536. codeEditor.refresh();
  10537. return {
  10538. getCodeMirror:function(){
  10539. return codeEditor;
  10540. },
  10541. setContent: function (content){
  10542. codeEditor.setValue(content);
  10543. },
  10544. getContent: function (){
  10545. return codeEditor.getValue();
  10546. },
  10547. select: function (){
  10548. codeEditor.focus();
  10549. },
  10550. dispose: function (){
  10551. holder.removeChild(dom);
  10552. dom = null;
  10553. codeEditor = null;
  10554. }
  10555. };
  10556. }
  10557. };
  10558. UE.plugins['source'] = function (){
  10559. var me = this;
  10560. var opt = this.options;
  10561. var sourceMode = false;
  10562. var sourceEditor;
  10563. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  10564. me.setOpt({
  10565. sourceEditorFirst:false
  10566. });
  10567. function createSourceEditor(holder){
  10568. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  10569. }
  10570. var bakCssText;
  10571. //解决在源码模式下getContent不能得到最新的内容问题
  10572. var oldGetContent = me.getContent,
  10573. bakAddress;
  10574. me.commands['source'] = {
  10575. execCommand: function (){
  10576. sourceMode = !sourceMode;
  10577. if (sourceMode) {
  10578. bakAddress = me.selection.getRange().createAddress(false,true);
  10579. me.undoManger && me.undoManger.save(true);
  10580. if(browser.gecko){
  10581. me.body.contentEditable = false;
  10582. }
  10583. bakCssText = me.iframe.style.cssText;
  10584. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  10585. me.fireEvent('beforegetcontent');
  10586. var root = UE.htmlparser(me.body.innerHTML);
  10587. me.filterOutputRule(root);
  10588. root.traversal(function (node) {
  10589. if (node.type == 'element') {
  10590. switch (node.tagName) {
  10591. case 'td':
  10592. case 'th':
  10593. case 'caption':
  10594. if(node.children && node.children.length == 1){
  10595. if(node.firstChild().tagName == 'br' ){
  10596. node.removeChild(node.firstChild())
  10597. }
  10598. };
  10599. break;
  10600. case 'pre':
  10601. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  10602. }
  10603. }
  10604. });
  10605. me.fireEvent('aftergetcontent');
  10606. var content = root.toHtml(true);
  10607. sourceEditor = createSourceEditor(me.iframe.parentNode);
  10608. sourceEditor.setContent(content);
  10609. setTimeout(function (){
  10610. sourceEditor.select();
  10611. me.addListener('fullscreenchanged', function(){
  10612. try{
  10613. sourceEditor.getCodeMirror().refresh()
  10614. }catch(e){}
  10615. });
  10616. });
  10617. //重置getContent,源码模式下取值也能是最新的数据
  10618. me.getContent = function (){
  10619. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  10620. };
  10621. } else {
  10622. me.iframe.style.cssText = bakCssText;
  10623. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  10624. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  10625. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  10626. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  10627. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  10628. }
  10629. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  10630. });
  10631. me.setContent(cont);
  10632. sourceEditor.dispose();
  10633. sourceEditor = null;
  10634. //还原getContent方法
  10635. me.getContent = oldGetContent;
  10636. var first = me.body.firstChild;
  10637. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  10638. if(!first){
  10639. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  10640. first = me.body.firstChild;
  10641. }
  10642. //要在ifm为显示时ff才能取到selection,否则报错
  10643. //这里不能比较位置了
  10644. me.undoManger && me.undoManger.save(true);
  10645. if(browser.gecko){
  10646. var input = document.createElement('input');
  10647. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  10648. document.body.appendChild(input);
  10649. me.body.contentEditable = false;
  10650. setTimeout(function(){
  10651. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  10652. input.focus();
  10653. setTimeout(function(){
  10654. me.body.contentEditable = true;
  10655. me.selection.getRange().moveToAddress(bakAddress).select(true);
  10656. domUtils.remove(input);
  10657. });
  10658. });
  10659. }else{
  10660. //ie下有可能报错,比如在代码顶头的情况
  10661. try{
  10662. me.selection.getRange().moveToAddress(bakAddress).select(true);
  10663. }catch(e){}
  10664. }
  10665. }
  10666. this.fireEvent('sourcemodechanged', sourceMode);
  10667. },
  10668. queryCommandState: function (){
  10669. return sourceMode|0;
  10670. },
  10671. notNeedUndo : 1
  10672. };
  10673. var oldQueryCommandState = me.queryCommandState;
  10674. me.queryCommandState = function (cmdName){
  10675. cmdName = cmdName.toLowerCase();
  10676. if (sourceMode) {
  10677. //源码模式下可以开启的命令
  10678. return cmdName in {
  10679. 'source' : 1,
  10680. 'fullscreen' : 1
  10681. } ? 1 : -1
  10682. }
  10683. return oldQueryCommandState.apply(this, arguments);
  10684. };
  10685. if(opt.sourceEditor == "codemirror"){
  10686. me.addListener("ready",function(){
  10687. utils.loadFile(document,{
  10688. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  10689. tag : "script",
  10690. type : "text/javascript",
  10691. defer : "defer"
  10692. },function(){
  10693. if(opt.sourceEditorFirst){
  10694. setTimeout(function(){
  10695. me.execCommand("source");
  10696. },0);
  10697. }
  10698. });
  10699. utils.loadFile(document,{
  10700. tag : "link",
  10701. rel : "stylesheet",
  10702. type : "text/css",
  10703. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  10704. });
  10705. });
  10706. }
  10707. };
  10708. })();
  10709. ///import core
  10710. ///import plugins/undo.js
  10711. ///commands 设置回车标签p或br
  10712. ///commandsName EnterKey
  10713. ///commandsTitle 设置回车标签p或br
  10714. /**
  10715. * @description 处理回车
  10716. * @author zhanyi
  10717. */
  10718. UE.plugins['enterkey'] = function() {
  10719. var hTag,
  10720. me = this,
  10721. tag = me.options.enterTag;
  10722. me.addListener('keyup', function(type, evt) {
  10723. var keyCode = evt.keyCode || evt.which;
  10724. if (keyCode == 13) {
  10725. var range = me.selection.getRange(),
  10726. start = range.startContainer,
  10727. doSave;
  10728. //修正在h1-h6里边回车后不能嵌套p的问题
  10729. if (!browser.ie) {
  10730. if (/h\d/i.test(hTag)) {
  10731. if (browser.gecko) {
  10732. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  10733. if (!h) {
  10734. me.document.execCommand('formatBlock', false, '<p>');
  10735. doSave = 1;
  10736. }
  10737. } else {
  10738. //chrome remove div
  10739. if (start.nodeType == 1) {
  10740. var tmp = me.document.createTextNode(''),div;
  10741. range.insertNode(tmp);
  10742. div = domUtils.findParentByTagName(tmp, 'div', true);
  10743. if (div) {
  10744. var p = me.document.createElement('p');
  10745. while (div.firstChild) {
  10746. p.appendChild(div.firstChild);
  10747. }
  10748. div.parentNode.insertBefore(p, div);
  10749. domUtils.remove(div);
  10750. range.setStartBefore(tmp).setCursor();
  10751. doSave = 1;
  10752. }
  10753. domUtils.remove(tmp);
  10754. }
  10755. }
  10756. if (me.undoManger && doSave) {
  10757. me.undoManger.save();
  10758. }
  10759. }
  10760. //没有站位符,会出现多行的问题
  10761. browser.opera && range.select();
  10762. }else{
  10763. me.fireEvent('saveScene',true,true)
  10764. }
  10765. }
  10766. });
  10767. me.addListener('keydown', function(type, evt) {
  10768. var keyCode = evt.keyCode || evt.which;
  10769. if (keyCode == 13) {//回车
  10770. if(me.fireEvent('beforeenterkeydown')){
  10771. domUtils.preventDefault(evt);
  10772. return;
  10773. }
  10774. me.fireEvent('saveScene',true,true);
  10775. hTag = '';
  10776. var range = me.selection.getRange();
  10777. if (!range.collapsed) {
  10778. //跨td不能删
  10779. var start = range.startContainer,
  10780. end = range.endContainer,
  10781. startTd = domUtils.findParentByTagName(start, 'td', true),
  10782. endTd = domUtils.findParentByTagName(end, 'td', true);
  10783. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  10784. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  10785. return;
  10786. }
  10787. }
  10788. if (tag == 'p') {
  10789. if (!browser.ie) {
  10790. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  10791. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  10792. //trace:2431
  10793. if (!start && !browser.opera) {
  10794. me.document.execCommand('formatBlock', false, '<p>');
  10795. if (browser.gecko) {
  10796. range = me.selection.getRange();
  10797. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  10798. start && domUtils.removeDirtyAttr(start);
  10799. }
  10800. } else {
  10801. hTag = start.tagName;
  10802. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  10803. }
  10804. }
  10805. } else {
  10806. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  10807. if (!range.collapsed) {
  10808. range.deleteContents();
  10809. start = range.startContainer;
  10810. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  10811. while (start.nodeType == 1) {
  10812. if (dtd.$empty[start.tagName]) {
  10813. range.setStartBefore(start).setCursor();
  10814. if (me.undoManger) {
  10815. me.undoManger.save();
  10816. }
  10817. return false;
  10818. }
  10819. if (!start.firstChild) {
  10820. var br = range.document.createElement('br');
  10821. start.appendChild(br);
  10822. range.setStart(start, 0).setCursor();
  10823. if (me.undoManger) {
  10824. me.undoManger.save();
  10825. }
  10826. return false;
  10827. }
  10828. start = start.firstChild;
  10829. }
  10830. if (start === range.startContainer.childNodes[range.startOffset]) {
  10831. br = range.document.createElement('br');
  10832. range.insertNode(br).setCursor();
  10833. } else {
  10834. range.setStart(start, 0).setCursor();
  10835. }
  10836. } else {
  10837. br = range.document.createElement('br');
  10838. range.insertNode(br).setStartAfter(br).setCursor();
  10839. }
  10840. } else {
  10841. br = range.document.createElement('br');
  10842. range.insertNode(br);
  10843. var parent = br.parentNode;
  10844. if (parent.lastChild === br) {
  10845. br.parentNode.insertBefore(br.cloneNode(true), br);
  10846. range.setStartBefore(br);
  10847. } else {
  10848. range.setStartAfter(br);
  10849. }
  10850. range.setCursor();
  10851. }
  10852. }
  10853. }
  10854. });
  10855. };
  10856. /*
  10857. * 处理特殊键的兼容性问题
  10858. */
  10859. UE.plugins['keystrokes'] = function() {
  10860. var me = this;
  10861. var collapsed = true;
  10862. me.addListener('keydown', function(type, evt) {
  10863. var keyCode = evt.keyCode || evt.which,
  10864. rng = me.selection.getRange();
  10865. //处理全选的情况
  10866. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  10867. || keyCode >= 48 && keyCode <= 57 ||
  10868. keyCode >= 96 && keyCode <= 111 || {
  10869. 13:1,
  10870. 8:1,
  10871. 46:1
  10872. }[keyCode])
  10873. ){
  10874. var tmpNode = rng.startContainer;
  10875. if(domUtils.isFillChar(tmpNode)){
  10876. rng.setStartBefore(tmpNode)
  10877. }
  10878. tmpNode = rng.endContainer;
  10879. if(domUtils.isFillChar(tmpNode)){
  10880. rng.setEndAfter(tmpNode)
  10881. }
  10882. rng.txtToElmBoundary();
  10883. //结束边界可能放到了br的前边,要把br包含进来
  10884. // x[xxx]<br/>
  10885. if(rng.endContainer && rng.endContainer.nodeType == 1){
  10886. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  10887. if(tmpNode && domUtils.isBr(tmpNode)){
  10888. rng.setEndAfter(tmpNode);
  10889. }
  10890. }
  10891. if(rng.startOffset == 0){
  10892. tmpNode = rng.startContainer;
  10893. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  10894. tmpNode = rng.endContainer;
  10895. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  10896. me.fireEvent('saveScene');
  10897. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  10898. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  10899. me._selectionChange();
  10900. return;
  10901. }
  10902. }
  10903. }
  10904. }
  10905. //处理backspace
  10906. if (keyCode == 8) {
  10907. rng = me.selection.getRange();
  10908. collapsed = rng.collapsed;
  10909. if(me.fireEvent('delkeydown',evt)){
  10910. return;
  10911. }
  10912. var start,end;
  10913. //避免按两次删除才能生效的问题
  10914. if(rng.collapsed && rng.inFillChar()){
  10915. start = rng.startContainer;
  10916. if(domUtils.isFillChar(start)){
  10917. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  10918. domUtils.remove(start)
  10919. }else{
  10920. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  10921. rng.startOffset--;
  10922. rng.collapse(true).select(true)
  10923. }
  10924. }
  10925. //解决选中control元素不能删除的问题
  10926. if (start = rng.getClosedNode()) {
  10927. me.fireEvent('saveScene');
  10928. rng.setStartBefore(start);
  10929. domUtils.remove(start);
  10930. rng.setCursor();
  10931. me.fireEvent('saveScene');
  10932. domUtils.preventDefault(evt);
  10933. return;
  10934. }
  10935. //阻止在table上的删除
  10936. if (!browser.ie) {
  10937. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  10938. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  10939. if (start && !end || !start && end || start !== end) {
  10940. evt.preventDefault();
  10941. return;
  10942. }
  10943. }
  10944. }
  10945. //处理tab键的逻辑
  10946. if (keyCode == 9) {
  10947. //不处理以下标签
  10948. var excludeTagNameForTabKey = {
  10949. 'ol' : 1,
  10950. 'ul' : 1,
  10951. 'table':1
  10952. };
  10953. //处理组件里的tab按下事件
  10954. if(me.fireEvent('tabkeydown',evt)){
  10955. domUtils.preventDefault(evt);
  10956. return;
  10957. }
  10958. var range = me.selection.getRange();
  10959. me.fireEvent('saveScene');
  10960. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  10961. txt += tabNode;
  10962. }
  10963. var span = me.document.createElement('span');
  10964. span.innerHTML = txt + domUtils.fillChar;
  10965. if (range.collapsed) {
  10966. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  10967. } else {
  10968. //普通的情况
  10969. start = domUtils.findParent(range.startContainer, filterFn);
  10970. end = domUtils.findParent(range.endContainer, filterFn);
  10971. if (start && end && start === end) {
  10972. range.deleteContents();
  10973. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  10974. } else {
  10975. var bookmark = range.createBookmark(),
  10976. filterFn = function(node) {
  10977. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  10978. };
  10979. range.enlarge(true);
  10980. var bookmark2 = range.createBookmark(),
  10981. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  10982. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10983. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  10984. current = domUtils.getNextDomNode(current, false, filterFn);
  10985. }
  10986. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  10987. }
  10988. }
  10989. domUtils.preventDefault(evt)
  10990. }
  10991. //trace:1634
  10992. //ff的del键在容器空的时候,也会删除
  10993. if(browser.gecko && keyCode == 46){
  10994. range = me.selection.getRange();
  10995. if(range.collapsed){
  10996. start = range.startContainer;
  10997. if(domUtils.isEmptyBlock(start)){
  10998. var parent = start.parentNode;
  10999. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  11000. start = parent;
  11001. parent = parent.parentNode;
  11002. }
  11003. if(start === parent.lastChild)
  11004. evt.preventDefault();
  11005. return;
  11006. }
  11007. }
  11008. }
  11009. });
  11010. me.addListener('keyup', function(type, evt) {
  11011. var keyCode = evt.keyCode || evt.which,
  11012. rng,me = this;
  11013. if(keyCode == 8){
  11014. if(me.fireEvent('delkeyup')){
  11015. return;
  11016. }
  11017. rng = me.selection.getRange();
  11018. if(rng.collapsed){
  11019. var tmpNode,
  11020. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  11021. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  11022. if(domUtils.isEmptyBlock(tmpNode)){
  11023. var pre = tmpNode.previousSibling;
  11024. if(pre && pre.nodeName != 'TABLE'){
  11025. domUtils.remove(tmpNode);
  11026. rng.setStartAtLast(pre).setCursor(false,true);
  11027. return;
  11028. }else{
  11029. var next = tmpNode.nextSibling;
  11030. if(next && next.nodeName != 'TABLE'){
  11031. domUtils.remove(tmpNode);
  11032. rng.setStartAtFirst(next).setCursor(false,true);
  11033. return;
  11034. }
  11035. }
  11036. }
  11037. }
  11038. //处理当删除到body时,要重新给p标签展位
  11039. if(domUtils.isBody(rng.startContainer)){
  11040. var tmpNode = domUtils.createElement(me.document,'p',{
  11041. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  11042. });
  11043. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  11044. }
  11045. }
  11046. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  11047. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  11048. if(browser.ie){
  11049. var span = rng.document.createElement('span');
  11050. rng.insertNode(span).setStartBefore(span).collapse(true);
  11051. rng.select();
  11052. domUtils.remove(span)
  11053. }else{
  11054. rng.select()
  11055. }
  11056. }
  11057. }
  11058. })
  11059. };
  11060. ///import core
  11061. ///commands 修复chrome下图片不能点击的问题
  11062. ///commandsName FixImgClick
  11063. ///commandsTitle 修复chrome下图片不能点击的问题
  11064. //修复chrome下图片不能点击的问题
  11065. //todo 可以改大小
  11066. UE.plugins['fiximgclick'] = function() {
  11067. var me = this;
  11068. if ( browser.webkit ) {
  11069. me.addListener( 'click', function( type, e ) {
  11070. if ( e.target.tagName == 'IMG' ) {
  11071. var range = new dom.Range( me.document );
  11072. range.selectNode( e.target ).select();
  11073. }
  11074. } );
  11075. }
  11076. };
  11077. ///import core
  11078. ///commands 为非ie浏览器自动添加a标签
  11079. ///commandsName AutoLink
  11080. ///commandsTitle 自动增加链接
  11081. /**
  11082. * @description 为非ie浏览器自动添加a标签
  11083. * @author zhanyi
  11084. */
  11085. UE.plugins['autolink'] = function() {
  11086. var cont = 0;
  11087. if (browser.ie) {
  11088. return;
  11089. }
  11090. var me = this;
  11091. me.addListener('reset',function(){
  11092. cont = 0;
  11093. });
  11094. me.addListener('keydown', function(type, evt) {
  11095. var keyCode = evt.keyCode || evt.which;
  11096. if (keyCode == 32 || keyCode == 13) {
  11097. var sel = me.selection.getNative(),
  11098. range = sel.getRangeAt(0).cloneRange(),
  11099. offset,
  11100. charCode;
  11101. var start = range.startContainer;
  11102. while (start.nodeType == 1 && range.startOffset > 0) {
  11103. start = range.startContainer.childNodes[range.startOffset - 1];
  11104. if (!start){
  11105. break;
  11106. }
  11107. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  11108. range.collapse(true);
  11109. start = range.startContainer;
  11110. }
  11111. do{
  11112. if (range.startOffset == 0) {
  11113. start = range.startContainer.previousSibling;
  11114. while (start && start.nodeType == 1) {
  11115. start = start.lastChild;
  11116. }
  11117. if (!start || domUtils.isFillChar(start)){
  11118. break;
  11119. }
  11120. offset = start.nodeValue.length;
  11121. } else {
  11122. start = range.startContainer;
  11123. offset = range.startOffset;
  11124. }
  11125. range.setStart(start, offset - 1);
  11126. charCode = range.toString().charCodeAt(0);
  11127. } while (charCode != 160 && charCode != 32);
  11128. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  11129. while(range.toString().length){
  11130. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  11131. break;
  11132. }
  11133. try{
  11134. range.setStart(range.startContainer,range.startOffset+1);
  11135. }catch(e){
  11136. //trace:2121
  11137. var start = range.startContainer;
  11138. while(!(next = start.nextSibling)){
  11139. if(domUtils.isBody(start)){
  11140. return;
  11141. }
  11142. start = start.parentNode;
  11143. }
  11144. range.setStart(next,0);
  11145. }
  11146. }
  11147. //range的开始边界已经在a标签里的不再处理
  11148. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  11149. return;
  11150. }
  11151. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  11152. me.undoManger && me.undoManger.save();
  11153. a.appendChild(range.extractContents());
  11154. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  11155. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  11156. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  11157. a.setAttribute('_src',utils.html(href));
  11158. a.href = utils.html(href);
  11159. range.insertNode(a);
  11160. a.parentNode.insertBefore(text, a.nextSibling);
  11161. range.setStart(text, 0);
  11162. range.collapse(true);
  11163. sel.removeAllRanges();
  11164. sel.addRange(range);
  11165. me.undoManger && me.undoManger.save();
  11166. }
  11167. }
  11168. });
  11169. };
  11170. ///import core
  11171. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  11172. ///commandsName AutoHeight,autoHeightEnabled
  11173. ///commandsTitle 自动增高
  11174. /**
  11175. * @description 自动伸展
  11176. * @author zhanyi
  11177. */
  11178. UE.plugins['autoheight'] = function () {
  11179. var me = this;
  11180. //提供开关,就算加载也可以关闭
  11181. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  11182. if (!me.autoHeightEnabled) {
  11183. return;
  11184. }
  11185. var bakOverflow,
  11186. span, tmpNode,
  11187. lastHeight = 0,
  11188. options = me.options,
  11189. currentHeight,
  11190. timer;
  11191. function adjustHeight() {
  11192. var me = this;
  11193. clearTimeout(timer);
  11194. if(isFullscreen)return;
  11195. timer = setTimeout(function () {
  11196. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  11197. if (!span) {
  11198. span = me.document.createElement('span');
  11199. //trace:1764
  11200. span.style.cssText = 'display:block;width:0;margin:0;padding:0;border:0;clear:both;';
  11201. span.innerHTML = '.';
  11202. }
  11203. tmpNode = span.cloneNode(true);
  11204. me.body.appendChild(tmpNode);
  11205. currentHeight = Math.max(domUtils.getXY(tmpNode).y + tmpNode.offsetHeight,Math.max(options.minFrameHeight, options.initialFrameHeight));
  11206. if (currentHeight != lastHeight) {
  11207. me.setHeight(currentHeight,true);
  11208. lastHeight = currentHeight;
  11209. }
  11210. domUtils.remove(tmpNode);
  11211. }
  11212. }, 50);
  11213. }
  11214. var isFullscreen;
  11215. me.addListener('fullscreenchanged',function(cmd,f){
  11216. isFullscreen = f
  11217. });
  11218. me.addListener('destroy', function () {
  11219. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  11220. });
  11221. me.enableAutoHeight = function () {
  11222. var me = this;
  11223. if (!me.autoHeightEnabled) {
  11224. return;
  11225. }
  11226. var doc = me.document;
  11227. me.autoHeightEnabled = true;
  11228. bakOverflow = doc.body.style.overflowY;
  11229. doc.body.style.overflowY = 'hidden';
  11230. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  11231. //ff不给事件算得不对
  11232. setTimeout(function () {
  11233. adjustHeight.call(me);
  11234. }, browser.gecko ? 100 : 0);
  11235. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11236. };
  11237. me.disableAutoHeight = function () {
  11238. me.body.style.overflowY = bakOverflow || '';
  11239. me.removeListener('contentchange', adjustHeight);
  11240. me.removeListener('keyup', adjustHeight);
  11241. me.removeListener('mouseup', adjustHeight);
  11242. me.autoHeightEnabled = false;
  11243. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11244. };
  11245. me.addListener('ready', function () {
  11246. me.enableAutoHeight();
  11247. //trace:1764
  11248. var timer;
  11249. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  11250. clearTimeout(timer);
  11251. timer = setTimeout(function () {
  11252. adjustHeight.call(this);
  11253. }, 100);
  11254. });
  11255. });
  11256. };
  11257. ///import core
  11258. ///commands 悬浮工具栏
  11259. ///commandsName AutoFloat,autoFloatEnabled
  11260. ///commandsTitle 悬浮工具栏
  11261. /*
  11262. * modified by chengchao01
  11263. *
  11264. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  11265. */
  11266. UE.plugins['autofloat'] = function() {
  11267. var me = this,
  11268. lang = me.getLang();
  11269. me.setOpt({
  11270. topOffset:0
  11271. });
  11272. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  11273. topOffset = me.options.topOffset;
  11274. //如果不固定toolbar的位置,则直接退出
  11275. if(!optsAutoFloatEnabled){
  11276. return;
  11277. }
  11278. var uiUtils = UE.ui.uiUtils,
  11279. LteIE6 = browser.ie && browser.version <= 6,
  11280. quirks = browser.quirks;
  11281. function checkHasUI(){
  11282. if(!UE.ui){
  11283. alert(lang.autofloatMsg);
  11284. return 0;
  11285. }
  11286. return 1;
  11287. }
  11288. function fixIE6FixedPos(){
  11289. var docStyle = document.body.style;
  11290. docStyle.backgroundImage = 'url("about:blank")';
  11291. docStyle.backgroundAttachment = 'fixed';
  11292. }
  11293. var bakCssText,
  11294. placeHolder = document.createElement('div'),
  11295. toolbarBox,orgTop,
  11296. getPosition,
  11297. flag =true; //ie7模式下需要偏移
  11298. function setFloating(){
  11299. var toobarBoxPos = domUtils.getXY(toolbarBox),
  11300. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  11301. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  11302. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  11303. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  11304. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  11305. if (LteIE6 || (quirks && browser.ie)) {
  11306. if(toolbarBox.style.position != 'absolute'){
  11307. toolbarBox.style.position = 'absolute';
  11308. }
  11309. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  11310. } else {
  11311. if (browser.ie7Compat && flag) {
  11312. flag = false;
  11313. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  11314. }
  11315. if(toolbarBox.style.position != 'fixed'){
  11316. toolbarBox.style.position = 'fixed';
  11317. toolbarBox.style.top = topOffset +"px";
  11318. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  11319. }
  11320. }
  11321. }
  11322. function unsetFloating(){
  11323. flag = true;
  11324. if(placeHolder.parentNode){
  11325. placeHolder.parentNode.removeChild(placeHolder);
  11326. }
  11327. toolbarBox.style.cssText = bakCssText;
  11328. }
  11329. function updateFloating(){
  11330. var rect3 = getPosition(me.container);
  11331. var offset=me.options.toolbarTopOffset||0;
  11332. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  11333. setFloating();
  11334. }else{
  11335. unsetFloating();
  11336. }
  11337. }
  11338. var defer_updateFloating = utils.defer(function(){
  11339. updateFloating();
  11340. },browser.ie ? 200 : 100,true);
  11341. me.addListener('destroy',function(){
  11342. domUtils.un(window, ['scroll','resize'], updateFloating);
  11343. me.removeListener('keydown', defer_updateFloating);
  11344. });
  11345. me.addListener('ready', function(){
  11346. if(checkHasUI(me)){
  11347. getPosition = uiUtils.getClientRect;
  11348. toolbarBox = me.ui.getDom('toolbarbox');
  11349. orgTop = getPosition(toolbarBox).top;
  11350. bakCssText = toolbarBox.style.cssText;
  11351. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  11352. if(LteIE6){
  11353. fixIE6FixedPos();
  11354. }
  11355. domUtils.on(window, ['scroll','resize'], updateFloating);
  11356. me.addListener('keydown', defer_updateFloating);
  11357. me.addListener('beforefullscreenchange', function (t, enabled){
  11358. if (enabled) {
  11359. unsetFloating();
  11360. }
  11361. });
  11362. me.addListener('fullscreenchanged', function (t, enabled){
  11363. if (!enabled) {
  11364. updateFloating();
  11365. }
  11366. });
  11367. me.addListener('sourcemodechanged', function (t, enabled){
  11368. setTimeout(function (){
  11369. updateFloating();
  11370. },0);
  11371. });
  11372. me.addListener("clearDoc",function(){
  11373. setTimeout(function(){
  11374. updateFloating();
  11375. },0);
  11376. })
  11377. }
  11378. });
  11379. };
  11380. /**
  11381. * @description 纯文本粘贴
  11382. * @name puretxtpaste
  11383. * @author zhanyi
  11384. */
  11385. UE.plugins['pasteplain'] = function(){
  11386. var me = this;
  11387. me.setOpt({
  11388. 'pasteplain':false,
  11389. 'filterTxtRules' : function(){
  11390. function transP(node){
  11391. node.tagName = 'p';
  11392. node.setStyle();
  11393. }
  11394. function removeNode(node){
  11395. node.parentNode.removeChild(node,true)
  11396. }
  11397. return {
  11398. //直接删除及其字节点内容
  11399. '-' : 'script style object iframe embed input select',
  11400. 'p': {$:{}},
  11401. 'br':{$:{}},
  11402. div: function (node) {
  11403. var tmpNode, p = UE.uNode.createElement('p');
  11404. while (tmpNode = node.firstChild()) {
  11405. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  11406. p.appendChild(tmpNode);
  11407. } else {
  11408. if (p.firstChild()) {
  11409. node.parentNode.insertBefore(p, node);
  11410. p = UE.uNode.createElement('p');
  11411. } else {
  11412. node.parentNode.insertBefore(tmpNode, node);
  11413. }
  11414. }
  11415. }
  11416. if (p.firstChild()) {
  11417. node.parentNode.insertBefore(p, node);
  11418. }
  11419. node.parentNode.removeChild(node);
  11420. },
  11421. ol: removeNode,
  11422. ul: removeNode,
  11423. dl:removeNode,
  11424. dt:removeNode,
  11425. dd:removeNode,
  11426. 'li':removeNode,
  11427. 'caption':transP,
  11428. 'th':transP,
  11429. 'tr':transP,
  11430. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  11431. 'td':function(node){
  11432. //没有内容的td直接删掉
  11433. var txt = !!node.innerText();
  11434. if(txt){
  11435. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  11436. }
  11437. node.parentNode.removeChild(node,node.innerText())
  11438. }
  11439. }
  11440. }()
  11441. });
  11442. //暂时这里支持一下老版本的属性
  11443. var pasteplain = me.options.pasteplain;
  11444. me.commands['pasteplain'] = {
  11445. queryCommandState: function (){
  11446. return pasteplain ? 1 : 0;
  11447. },
  11448. execCommand: function (){
  11449. pasteplain = !pasteplain|0;
  11450. },
  11451. notNeedUndo : 1
  11452. };
  11453. };
  11454. ///import core
  11455. ///import plugins/inserthtml.js
  11456. ///commands 视频
  11457. ///commandsName InsertVideo
  11458. ///commandsTitle 插入视频
  11459. ///commandsDialog dialogs\video
  11460. UE.plugins['video'] = function (){
  11461. var me =this,
  11462. div;
  11463. /**
  11464. * 创建插入视频字符窜
  11465. * @param url 视频地址
  11466. * @param width 视频宽度
  11467. * @param height 视频高度
  11468. * @param align 视频对齐
  11469. * @param toEmbed 是否以flash代替显示
  11470. * @param addParagraph 是否需要添加P 标签
  11471. */
  11472. function creatInsertStr(url,width,height,id,align,toEmbed){
  11473. return !toEmbed ?
  11474. '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' +
  11475. ' 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 + ';': '')+'" />'
  11476. :
  11477. '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  11478. ' src="' + url + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  11479. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  11480. }
  11481. function switchImgAndEmbed(root,img2embed){
  11482. utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){
  11483. if(node.getAttr('class') == 'edui-faked-video'){
  11484. var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed);
  11485. node.parentNode.replaceChild(UE.uNode.createElement(html),node)
  11486. }
  11487. })
  11488. }
  11489. me.addOutputRule(function(root){
  11490. switchImgAndEmbed(root,true)
  11491. });
  11492. me.addInputRule(function(root){
  11493. switchImgAndEmbed(root)
  11494. });
  11495. me.commands["insertvideo"] = {
  11496. execCommand: function (cmd, videoObjs){
  11497. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  11498. var html = [],id = 'tmpVedio';
  11499. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  11500. vi = videoObjs[i];
  11501. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i,null,false));
  11502. }
  11503. me.execCommand("inserthtml",html.join(""),true);
  11504. var rng = this.selection.getRange();
  11505. for(var i= 0,len=videoObjs.length;i<len;i++){
  11506. var img = this.document.getElementById('tmpVedio'+i);
  11507. domUtils.removeAttributes(img,'id');
  11508. rng.selectNode(img).select();
  11509. me.execCommand('imagefloat',videoObjs[i].align)
  11510. }
  11511. },
  11512. queryCommandState : function(){
  11513. var img = me.selection.getRange().getClosedNode(),
  11514. flag = img && (img.className == "edui-faked-video");
  11515. return flag ? 1 : 0;
  11516. }
  11517. };
  11518. };
  11519. /**
  11520. * Created with JetBrains WebStorm.
  11521. * User: taoqili
  11522. * Date: 13-1-18
  11523. * Time: 上午11:09
  11524. * To change this template use File | Settings | File Templates.
  11525. */
  11526. /**
  11527. * UE表格操作类
  11528. * @param table
  11529. * @constructor
  11530. */
  11531. (function () {
  11532. var UETable = UE.UETable = function (table) {
  11533. this.table = table;
  11534. this.indexTable = [];
  11535. this.selectedTds = [];
  11536. this.cellsRange = {};
  11537. this.update(table);
  11538. };
  11539. //===以下为静态工具方法===
  11540. UETable.removeSelectedClass = function (cells) {
  11541. utils.each(cells, function (cell) {
  11542. domUtils.removeClasses(cell, "selectTdClass");
  11543. })
  11544. };
  11545. UETable.addSelectedClass = function (cells) {
  11546. utils.each(cells, function (cell) {
  11547. domUtils.addClass(cell, "selectTdClass");
  11548. })
  11549. };
  11550. UETable.isEmptyBlock = function (node) {
  11551. var reg = new RegExp(domUtils.fillChar, 'g');
  11552. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  11553. return 0;
  11554. }
  11555. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  11556. if (node.getElementsByTagName(i).length) {
  11557. return 0;
  11558. }
  11559. }
  11560. return 1;
  11561. };
  11562. UETable.getWidth = function (cell) {
  11563. if (!cell)return 0;
  11564. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  11565. };
  11566. /**
  11567. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  11568. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  11569. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  11570. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  11571. */
  11572. UETable.getTableCellAlignState = function ( cells ) {
  11573. !utils.isArray( cells ) && ( cells = [cells] );
  11574. var result = {},
  11575. status = ['align', 'valign'],
  11576. tempStatus = null,
  11577. isSame = true;//状态是否相同
  11578. utils.each( cells, function( cellNode ){
  11579. utils.each( status, function( currentState ){
  11580. tempStatus = cellNode.getAttribute( currentState );
  11581. if( !result[ currentState ] && tempStatus ) {
  11582. result[ currentState ] = tempStatus;
  11583. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  11584. isSame = false;
  11585. return false;
  11586. }
  11587. } );
  11588. return isSame;
  11589. });
  11590. return isSame ? result : null;
  11591. };
  11592. /**
  11593. * 根据当前选区获取相关的table信息
  11594. * @return {Object}
  11595. */
  11596. UETable.getTableItemsByRange = function (editor) {
  11597. var start = editor.selection.getStart();
  11598. //ff下会选中bookmark
  11599. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 ) {
  11600. start = start.nextSibling;
  11601. }
  11602. //在table或者td边缘有可能存在选中tr的情况
  11603. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  11604. tr = cell && cell.parentNode,
  11605. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  11606. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  11607. return {
  11608. cell:cell,
  11609. tr:tr,
  11610. table:table,
  11611. caption:caption
  11612. }
  11613. };
  11614. UETable.getUETableBySelected = function (editor) {
  11615. var table = UETable.getTableItemsByRange(editor).table;
  11616. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  11617. return table.ueTable;
  11618. }
  11619. return null;
  11620. };
  11621. UETable.getDefaultValue = function (editor, table) {
  11622. var borderMap = {
  11623. thin:'0px',
  11624. medium:'1px',
  11625. thick:'2px'
  11626. },
  11627. tableBorder, tdPadding, tdBorder, tmpValue;
  11628. if (!table) {
  11629. table = editor.document.createElement('table');
  11630. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  11631. editor.body.appendChild(table);
  11632. var td = table.getElementsByTagName('td')[0];
  11633. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  11634. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11635. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  11636. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11637. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  11638. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11639. domUtils.remove(table);
  11640. return {
  11641. tableBorder:tableBorder,
  11642. tdPadding:tdPadding,
  11643. tdBorder:tdBorder
  11644. };
  11645. } else {
  11646. td = table.getElementsByTagName('td')[0];
  11647. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  11648. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11649. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  11650. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11651. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  11652. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11653. return {
  11654. tableBorder:tableBorder,
  11655. tdPadding:tdPadding,
  11656. tdBorder:tdBorder
  11657. };
  11658. }
  11659. };
  11660. /**
  11661. * 根据当前点击的td或者table获取索引对象
  11662. * @param tdOrTable
  11663. */
  11664. UETable.getUETable = function (tdOrTable) {
  11665. var tag = tdOrTable.tagName.toLowerCase();
  11666. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  11667. if (!tdOrTable.ueTable) {
  11668. tdOrTable.ueTable = new UETable(tdOrTable);
  11669. }
  11670. return tdOrTable.ueTable;
  11671. };
  11672. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  11673. if (!cell || utils.isString(cell)) {
  11674. return this.table.ownerDocument.createElement(cell || 'td');
  11675. }
  11676. var flag = domUtils.hasClass(cell, "selectTdClass");
  11677. flag && domUtils.removeClasses(cell, "selectTdClass");
  11678. var tmpCell = cell.cloneNode(true);
  11679. if (ignoreMerge) {
  11680. tmpCell.rowSpan = tmpCell.colSpan = 1;
  11681. }
  11682. //去掉宽高
  11683. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  11684. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  11685. tmpCell.style.borderLeftStyle = "";
  11686. tmpCell.style.borderTopStyle = "";
  11687. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  11688. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  11689. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  11690. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  11691. flag && domUtils.addClass(cell, "selectTdClass");
  11692. return tmpCell;
  11693. }
  11694. UETable.prototype = {
  11695. getMaxRows:function () {
  11696. var rows = this.table.rows, maxLen = 1;
  11697. for (var i = 0, row; row = rows[i]; i++) {
  11698. var currentMax = 1;
  11699. for (var j = 0, cj; cj = row.cells[j++];) {
  11700. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  11701. }
  11702. maxLen = Math.max(currentMax + i, maxLen);
  11703. }
  11704. return maxLen;
  11705. },
  11706. /**
  11707. * 获取当前表格的最大列数
  11708. */
  11709. getMaxCols:function () {
  11710. var rows = this.table.rows, maxLen = 0, cellRows = {};
  11711. for (var i = 0, row; row = rows[i]; i++) {
  11712. var cellsNum = 0;
  11713. for (var j = 0, cj; cj = row.cells[j++];) {
  11714. cellsNum += (cj.colSpan || 1);
  11715. if (cj.rowSpan && cj.rowSpan > 1) {
  11716. for (var k = 1; k < cj.rowSpan; k++) {
  11717. if (!cellRows['row_' + (i + k)]) {
  11718. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  11719. } else {
  11720. cellRows['row_' + (i + k)]++
  11721. }
  11722. }
  11723. }
  11724. }
  11725. cellsNum += cellRows['row_' + i] || 0;
  11726. maxLen = Math.max(cellsNum, maxLen);
  11727. }
  11728. return maxLen;
  11729. },
  11730. getCellColIndex:function (cell) {
  11731. },
  11732. /**
  11733. * 获取当前cell旁边的单元格,
  11734. * @param cell
  11735. * @param right
  11736. */
  11737. getHSideCell:function (cell, right) {
  11738. try {
  11739. var cellInfo = this.getCellInfo(cell),
  11740. previewRowIndex, previewColIndex;
  11741. var len = this.selectedTds.length,
  11742. range = this.cellsRange;
  11743. //首行或者首列没有前置单元格
  11744. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  11745. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  11746. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  11747. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  11748. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  11749. } catch (e) {
  11750. showError(e);
  11751. }
  11752. },
  11753. getTabNextCell:function (cell, preRowIndex) {
  11754. var cellInfo = this.getCellInfo(cell),
  11755. rowIndex = preRowIndex || cellInfo.rowIndex,
  11756. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  11757. nextCell;
  11758. try {
  11759. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  11760. } catch (e) {
  11761. try {
  11762. rowIndex = rowIndex * 1 + 1;
  11763. colIndex = 0;
  11764. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  11765. } catch (e) {
  11766. }
  11767. }
  11768. return nextCell;
  11769. },
  11770. /**
  11771. * 获取视觉上的后置单元格
  11772. * @param cell
  11773. * @param bottom
  11774. */
  11775. getVSideCell:function (cell, bottom, ignoreRange) {
  11776. try {
  11777. var cellInfo = this.getCellInfo(cell),
  11778. nextRowIndex, nextColIndex;
  11779. var len = this.selectedTds.length && !ignoreRange,
  11780. range = this.cellsRange;
  11781. //末行或者末列没有后置单元格
  11782. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  11783. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  11784. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  11785. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  11786. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  11787. } catch (e) {
  11788. showError(e);
  11789. }
  11790. },
  11791. /**
  11792. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  11793. */
  11794. getSameEndPosCells:function (cell, xOrY) {
  11795. try {
  11796. var flag = (xOrY.toLowerCase() === "x"),
  11797. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  11798. rows = this.table.rows,
  11799. cells = null, returns = [];
  11800. for (var i = 0; i < this.rowsNum; i++) {
  11801. cells = rows[i].cells;
  11802. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  11803. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  11804. //对应行的td已经被上面行rowSpan了
  11805. if (tmpEnd > end && flag) break;
  11806. if (cell == tmpCell || end == tmpEnd) {
  11807. //只获取单一的单元格
  11808. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  11809. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  11810. returns.push(tmpCell);
  11811. }
  11812. if (flag) break;
  11813. }
  11814. }
  11815. }
  11816. return returns;
  11817. } catch (e) {
  11818. showError(e);
  11819. }
  11820. },
  11821. setCellContent:function (cell, content) {
  11822. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  11823. },
  11824. cloneCell:UETable.cloneCell,
  11825. /**
  11826. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  11827. */
  11828. getSameStartPosXCells:function (cell) {
  11829. try {
  11830. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  11831. rows = this.table.rows, cells , returns = [];
  11832. for (var i = 0; i < this.rowsNum; i++) {
  11833. cells = rows[i].cells;
  11834. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  11835. var tmpStart = domUtils.getXY(tmpCell).x;
  11836. if (tmpStart > start) break;
  11837. if (tmpStart == start && tmpCell.colSpan == 1) {
  11838. returns.push(tmpCell);
  11839. break;
  11840. }
  11841. }
  11842. }
  11843. return returns;
  11844. } catch (e) {
  11845. showError(e);
  11846. }
  11847. },
  11848. /**
  11849. * 更新table对应的索引表
  11850. */
  11851. update:function (table) {
  11852. this.table = table || this.table;
  11853. this.selectedTds = [];
  11854. this.cellsRange = {};
  11855. this.indexTable = [];
  11856. var rows = this.table.rows,
  11857. rowsNum = this.getMaxRows(),
  11858. dNum = rowsNum - rows.length,
  11859. colsNum = this.getMaxCols();
  11860. while (dNum--) {
  11861. this.table.insertRow(rows.length);
  11862. }
  11863. this.rowsNum = rowsNum;
  11864. this.colsNum = colsNum;
  11865. for (var i = 0, len = rows.length; i < len; i++) {
  11866. this.indexTable[i] = new Array(colsNum);
  11867. }
  11868. //填充索引表
  11869. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  11870. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  11871. //修正整行被rowSpan时导致的行数计算错误
  11872. if (cell.rowSpan > rowsNum) {
  11873. cell.rowSpan = rowsNum;
  11874. }
  11875. var colIndex = cellIndex,
  11876. rowSpan = cell.rowSpan || 1,
  11877. colSpan = cell.colSpan || 1;
  11878. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  11879. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  11880. for (var j = 0; j < rowSpan; j++) {
  11881. for (var k = 0; k < colSpan; k++) {
  11882. this.indexTable[rowIndex + j][colIndex + k] = {
  11883. rowIndex:rowIndex,
  11884. cellIndex:cellIndex,
  11885. colIndex:colIndex,
  11886. rowSpan:rowSpan,
  11887. colSpan:colSpan
  11888. }
  11889. }
  11890. }
  11891. }
  11892. }
  11893. //修复残缺td
  11894. for (j = 0; j < rowsNum; j++) {
  11895. for (k = 0; k < colsNum; k++) {
  11896. if (this.indexTable[j][k] === undefined) {
  11897. row = rows[j];
  11898. cell = row.cells[row.cells.length - 1];
  11899. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  11900. this.setCellContent(cell);
  11901. if (cell.colSpan !== 1)cell.colSpan = 1;
  11902. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  11903. row.appendChild(cell);
  11904. this.indexTable[j][k] = {
  11905. rowIndex:j,
  11906. cellIndex:cell.cellIndex,
  11907. colIndex:k,
  11908. rowSpan:1,
  11909. colSpan:1
  11910. }
  11911. }
  11912. }
  11913. }
  11914. //当框选后删除行或者列后撤销,需要重建选区。
  11915. var tds = domUtils.getElementsByTagName(this.table, "td"),
  11916. selectTds = [];
  11917. utils.each(tds, function (td) {
  11918. if (domUtils.hasClass(td, "selectTdClass")) {
  11919. selectTds.push(td);
  11920. }
  11921. });
  11922. if (selectTds.length) {
  11923. var start = selectTds[0],
  11924. end = selectTds[selectTds.length - 1],
  11925. startInfo = this.getCellInfo(start),
  11926. endInfo = this.getCellInfo(end);
  11927. this.selectedTds = selectTds;
  11928. this.cellsRange = {
  11929. beginRowIndex:startInfo.rowIndex,
  11930. beginColIndex:startInfo.colIndex,
  11931. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  11932. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  11933. };
  11934. }
  11935. },
  11936. /**
  11937. * 获取单元格的索引信息
  11938. */
  11939. getCellInfo:function (cell) {
  11940. if (!cell) return;
  11941. var cellIndex = cell.cellIndex,
  11942. rowIndex = cell.parentNode.rowIndex,
  11943. rowInfo = this.indexTable[rowIndex],
  11944. numCols = this.colsNum;
  11945. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  11946. var cellInfo = rowInfo[colIndex];
  11947. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  11948. return cellInfo;
  11949. }
  11950. }
  11951. },
  11952. /**
  11953. * 根据行列号获取单元格
  11954. */
  11955. getCell:function (rowIndex, cellIndex) {
  11956. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  11957. },
  11958. /**
  11959. * 删除单元格
  11960. */
  11961. deleteCell:function (cell, rowIndex) {
  11962. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  11963. var row = this.table.rows[rowIndex];
  11964. row.deleteCell(cell.cellIndex);
  11965. },
  11966. /**
  11967. * 根据始末两个单元格获取被框选的所有单元格范围
  11968. */
  11969. getCellsRange:function (cellA, cellB) {
  11970. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  11971. var tmpBeginRowIndex = beginRowIndex,
  11972. tmpBeginColIndex = beginColIndex,
  11973. tmpEndRowIndex = endRowIndex,
  11974. tmpEndColIndex = endColIndex,
  11975. cellInfo, colIndex, rowIndex;
  11976. // 通过indexTable检查是否存在超出TableRange上边界的情况
  11977. if (beginRowIndex > 0) {
  11978. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  11979. cellInfo = me.indexTable[beginRowIndex][colIndex];
  11980. rowIndex = cellInfo.rowIndex;
  11981. if (rowIndex < beginRowIndex) {
  11982. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  11983. }
  11984. }
  11985. }
  11986. // 通过indexTable检查是否存在超出TableRange右边界的情况
  11987. if (endColIndex < me.colsNum) {
  11988. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  11989. cellInfo = me.indexTable[rowIndex][endColIndex];
  11990. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  11991. if (colIndex > endColIndex) {
  11992. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  11993. }
  11994. }
  11995. }
  11996. // 检查是否有超出TableRange下边界的情况
  11997. if (endRowIndex < me.rowsNum) {
  11998. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  11999. cellInfo = me.indexTable[endRowIndex][colIndex];
  12000. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  12001. if (rowIndex > endRowIndex) {
  12002. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  12003. }
  12004. }
  12005. }
  12006. // 检查是否有超出TableRange左边界的情况
  12007. if (beginColIndex > 0) {
  12008. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  12009. cellInfo = me.indexTable[rowIndex][beginColIndex];
  12010. colIndex = cellInfo.colIndex;
  12011. if (colIndex < beginColIndex) {
  12012. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  12013. }
  12014. }
  12015. }
  12016. //递归调用直至所有完成所有框选单元格的扩展
  12017. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  12018. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  12019. } else {
  12020. // 不需要扩展TableRange的情况
  12021. return {
  12022. beginRowIndex:beginRowIndex,
  12023. beginColIndex:beginColIndex,
  12024. endRowIndex:endRowIndex,
  12025. endColIndex:endColIndex
  12026. };
  12027. }
  12028. }
  12029. try {
  12030. var me = this,
  12031. cellAInfo = me.getCellInfo(cellA);
  12032. if (cellA === cellB) {
  12033. return {
  12034. beginRowIndex:cellAInfo.rowIndex,
  12035. beginColIndex:cellAInfo.colIndex,
  12036. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  12037. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  12038. };
  12039. }
  12040. var cellBInfo = me.getCellInfo(cellB);
  12041. // 计算TableRange的四个边
  12042. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  12043. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  12044. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  12045. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  12046. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  12047. } catch (e) {
  12048. //throw e;
  12049. }
  12050. },
  12051. /**
  12052. * 依据cellsRange获取对应的单元格集合
  12053. */
  12054. getCells:function (range) {
  12055. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  12056. this.clearSelected();
  12057. var beginRowIndex = range.beginRowIndex,
  12058. beginColIndex = range.beginColIndex,
  12059. endRowIndex = range.endRowIndex,
  12060. endColIndex = range.endColIndex,
  12061. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  12062. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  12063. for (var j = beginColIndex; j <= endColIndex; j++) {
  12064. cellInfo = this.indexTable[i][j];
  12065. rowIndex = cellInfo.rowIndex;
  12066. colIndex = cellInfo.colIndex;
  12067. // 如果Cells里已经包含了此Cell则跳过
  12068. var key = rowIndex + '|' + colIndex;
  12069. if (tdHash[key]) continue;
  12070. tdHash[key] = 1;
  12071. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  12072. return null;
  12073. }
  12074. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  12075. }
  12076. }
  12077. return returnTds;
  12078. },
  12079. /**
  12080. * 清理已经选中的单元格
  12081. */
  12082. clearSelected:function () {
  12083. UETable.removeSelectedClass(this.selectedTds);
  12084. this.selectedTds = [];
  12085. this.cellsRange = {};
  12086. },
  12087. /**
  12088. * 根据range设置已经选中的单元格
  12089. */
  12090. setSelected:function (range) {
  12091. var cells = this.getCells(range);
  12092. UETable.addSelectedClass(cells);
  12093. this.selectedTds = cells;
  12094. this.cellsRange = range;
  12095. },
  12096. isFullRow:function () {
  12097. var range = this.cellsRange;
  12098. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  12099. },
  12100. isFullCol:function () {
  12101. var range = this.cellsRange,
  12102. table = this.table,
  12103. ths = table.getElementsByTagName("th"),
  12104. rows = range.endRowIndex - range.beginRowIndex + 1;
  12105. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  12106. },
  12107. /**
  12108. * 获取视觉上的前置单元格,默认是左边,top传入时
  12109. * @param cell
  12110. * @param top
  12111. */
  12112. getNextCell:function (cell, bottom, ignoreRange) {
  12113. try {
  12114. var cellInfo = this.getCellInfo(cell),
  12115. nextRowIndex, nextColIndex;
  12116. var len = this.selectedTds.length && !ignoreRange,
  12117. range = this.cellsRange;
  12118. //末行或者末列没有后置单元格
  12119. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12120. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12121. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12122. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12123. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12124. } catch (e) {
  12125. showError(e);
  12126. }
  12127. },
  12128. getPreviewCell:function (cell, top) {
  12129. try {
  12130. var cellInfo = this.getCellInfo(cell),
  12131. previewRowIndex, previewColIndex;
  12132. var len = this.selectedTds.length,
  12133. range = this.cellsRange;
  12134. //首行或者首列没有前置单元格
  12135. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12136. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  12137. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  12138. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12139. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  12140. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  12141. } catch (e) {
  12142. showError(e);
  12143. }
  12144. },
  12145. /**
  12146. * 移动单元格中的内容
  12147. */
  12148. moveContent:function (cellTo, cellFrom) {
  12149. if (UETable.isEmptyBlock(cellFrom)) return;
  12150. if (UETable.isEmptyBlock(cellTo)) {
  12151. cellTo.innerHTML = cellFrom.innerHTML;
  12152. return;
  12153. }
  12154. var child = cellTo.lastChild;
  12155. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  12156. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  12157. }
  12158. while (child = cellFrom.firstChild) {
  12159. cellTo.appendChild(child);
  12160. }
  12161. },
  12162. /**
  12163. * 向右合并单元格
  12164. */
  12165. mergeRight:function (cell) {
  12166. var cellInfo = this.getCellInfo(cell),
  12167. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  12168. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  12169. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  12170. //合并
  12171. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  12172. //被合并的单元格不应存在宽度属性
  12173. cell.removeAttribute("width");
  12174. //移动内容
  12175. this.moveContent(cell, rightCell);
  12176. //删掉被合并的Cell
  12177. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  12178. this.update();
  12179. },
  12180. /**
  12181. * 向下合并单元格
  12182. */
  12183. mergeDown:function (cell) {
  12184. var cellInfo = this.getCellInfo(cell),
  12185. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  12186. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  12187. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  12188. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  12189. cell.removeAttribute("height");
  12190. this.moveContent(cell, downCell);
  12191. this.deleteCell(downCell, downCellInfo.rowIndex);
  12192. this.update();
  12193. },
  12194. /**
  12195. * 合并整个range中的内容
  12196. */
  12197. mergeRange:function () {
  12198. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  12199. var range = this.cellsRange,
  12200. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  12201. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  12202. var index = this.indexTable,
  12203. info = this.getCellInfo(leftTopCell);
  12204. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  12205. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  12206. }
  12207. // 删除剩余的Cells
  12208. var cells = this.getCells(range);
  12209. for(var i= 0,ci;ci=cells[i++];){
  12210. if (ci !== leftTopCell) {
  12211. this.moveContent(leftTopCell, ci);
  12212. this.deleteCell(ci);
  12213. }
  12214. }
  12215. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  12216. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  12217. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  12218. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  12219. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  12220. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  12221. leftTopCell.colSpan = 1;
  12222. }
  12223. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  12224. var rowIndex = leftTopCell.parentNode.rowIndex;
  12225. //解决IE下的表格操作问题
  12226. if( this.table.deleteRow ) {
  12227. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  12228. this.table.deleteRow(curIndex);
  12229. }
  12230. } else {
  12231. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  12232. var row = this.table.rows[rowIndex + 1];
  12233. row.parentNode.removeChild(row);
  12234. }
  12235. }
  12236. leftTopCell.rowSpan = 1;
  12237. }
  12238. this.update();
  12239. },
  12240. /**
  12241. * 插入一行单元格
  12242. */
  12243. insertRow:function (rowIndex, sourceCell) {
  12244. var numCols = this.colsNum,
  12245. table = this.table,
  12246. row = table.insertRow(rowIndex), cell,
  12247. width = parseInt((table.offsetWidth - numCols * 20 - numCols - 1) / numCols, 10);
  12248. //首行直接插入,无需考虑部分单元格被rowspan的情况
  12249. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  12250. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  12251. cell = this.cloneCell(sourceCell, true);
  12252. this.setCellContent(cell);
  12253. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12254. row.appendChild(cell);
  12255. }
  12256. } else {
  12257. var infoRow = this.indexTable[rowIndex],
  12258. cellIndex = 0;
  12259. for (colIndex = 0; colIndex < numCols; colIndex++) {
  12260. var cellInfo = infoRow[colIndex];
  12261. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  12262. if (cellInfo.rowIndex < rowIndex) {
  12263. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12264. cell.rowSpan = cellInfo.rowSpan + 1;
  12265. } else {
  12266. cell = this.cloneCell(sourceCell, true);
  12267. this.setCellContent(cell);
  12268. row.appendChild(cell);
  12269. }
  12270. }
  12271. }
  12272. //框选时插入不触发contentchange,需要手动更新索引。
  12273. this.update();
  12274. return row;
  12275. },
  12276. /**
  12277. * 删除一行单元格
  12278. * @param rowIndex
  12279. */
  12280. deleteRow:function (rowIndex) {
  12281. var row = this.table.rows[rowIndex],
  12282. infoRow = this.indexTable[rowIndex],
  12283. colsNum = this.colsNum,
  12284. count = 0; //处理计数
  12285. for (var colIndex = 0; colIndex < colsNum;) {
  12286. var cellInfo = infoRow[colIndex],
  12287. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12288. if (cell.rowSpan > 1) {
  12289. if (cellInfo.rowIndex == rowIndex) {
  12290. var clone = cell.cloneNode(true);
  12291. clone.rowSpan = cell.rowSpan - 1;
  12292. clone.innerHTML = "";
  12293. cell.rowSpan = 1;
  12294. var nextRowIndex = rowIndex + 1,
  12295. nextRow = this.table.rows[nextRowIndex],
  12296. insertCellIndex,
  12297. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  12298. if (preMerged < colIndex) {
  12299. insertCellIndex = colIndex - preMerged - 1;
  12300. //nextRow.insertCell(insertCellIndex);
  12301. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  12302. } else {
  12303. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  12304. }
  12305. count += 1;
  12306. //cell.parentNode.removeChild(cell);
  12307. }
  12308. }
  12309. colIndex += cell.colSpan || 1;
  12310. }
  12311. var deleteTds = [], cacheMap = {};
  12312. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  12313. var tmpRowIndex = infoRow[colIndex].rowIndex,
  12314. tmpCellIndex = infoRow[colIndex].cellIndex,
  12315. key = tmpRowIndex + "_" + tmpCellIndex;
  12316. if (cacheMap[key])continue;
  12317. cacheMap[key] = 1;
  12318. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  12319. deleteTds.push(cell);
  12320. }
  12321. var mergeTds = [];
  12322. utils.each(deleteTds, function (td) {
  12323. if (td.rowSpan == 1) {
  12324. td.parentNode.removeChild(td);
  12325. } else {
  12326. mergeTds.push(td);
  12327. }
  12328. });
  12329. utils.each(mergeTds, function (td) {
  12330. td.rowSpan--;
  12331. });
  12332. row.parentNode.removeChild(row);
  12333. //浏览器方法本身存在bug,采用自定义方法删除
  12334. //this.table.deleteRow(rowIndex);
  12335. this.update();
  12336. },
  12337. insertCol:function (colIndex, sourceCell, defaultValue) {
  12338. var rowsNum = this.rowsNum,
  12339. rowIndex = 0,
  12340. tableRow, cell,
  12341. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10);
  12342. function replaceTdToTh(rowIndex, cell, tableRow) {
  12343. if (rowIndex == 0) {
  12344. var th = cell.nextSibling || cell.previousSibling;
  12345. if (th.tagName == 'TH') {
  12346. th = cell.ownerDocument.createElement("th");
  12347. th.appendChild(cell.firstChild);
  12348. tableRow.insertBefore(th, cell);
  12349. domUtils.remove(cell)
  12350. }
  12351. }else{
  12352. if (cell.tagName == 'TH') {
  12353. var td = cell.ownerDocument.createElement("td");
  12354. td.appendChild(cell.firstChild);
  12355. tableRow.insertBefore(td, cell);
  12356. domUtils.remove(cell)
  12357. }
  12358. }
  12359. }
  12360. var preCell;
  12361. if (colIndex == 0 || colIndex == this.colsNum) {
  12362. for (; rowIndex < rowsNum; rowIndex++) {
  12363. tableRow = this.table.rows[rowIndex];
  12364. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  12365. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  12366. this.setCellContent(cell);
  12367. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12368. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  12369. if (!colIndex) {
  12370. tableRow.insertBefore(cell, tableRow.cells[0]);
  12371. } else {
  12372. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  12373. }
  12374. replaceTdToTh(rowIndex, cell, tableRow)
  12375. }
  12376. } else {
  12377. for (; rowIndex < rowsNum; rowIndex++) {
  12378. var cellInfo = this.indexTable[rowIndex][colIndex];
  12379. if (cellInfo.colIndex < colIndex) {
  12380. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12381. cell.colSpan = cellInfo.colSpan + 1;
  12382. } else {
  12383. tableRow = this.table.rows[rowIndex];
  12384. preCell = tableRow.cells[cellInfo.cellIndex];
  12385. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  12386. this.setCellContent(cell);
  12387. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12388. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  12389. //防止IE下报错
  12390. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  12391. }
  12392. replaceTdToTh(rowIndex, cell, tableRow);
  12393. }
  12394. }
  12395. //框选时插入不触发contentchange,需要手动更新索引
  12396. this.update();
  12397. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  12398. },
  12399. updateWidth:function (width, defaultValue) {
  12400. var table = this.table,
  12401. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  12402. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  12403. table.setAttribute("width", tmpWidth);
  12404. return;
  12405. }
  12406. var tds = domUtils.getElementsByTagName(this.table, "td");
  12407. utils.each(tds, function (td) {
  12408. td.setAttribute("width", width);
  12409. })
  12410. },
  12411. deleteCol:function (colIndex) {
  12412. var indexTable = this.indexTable,
  12413. tableRows = this.table.rows,
  12414. backTableWidth = this.table.getAttribute("width"),
  12415. backTdWidth = 0,
  12416. rowsNum = this.rowsNum,
  12417. cacheMap = {};
  12418. for (var rowIndex = 0; rowIndex < rowsNum;) {
  12419. var infoRow = indexTable[rowIndex],
  12420. cellInfo = infoRow[colIndex],
  12421. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  12422. // 跳过已经处理过的Cell
  12423. if (cacheMap[key])continue;
  12424. cacheMap[key] = 1;
  12425. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12426. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  12427. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  12428. if (cell.colSpan > 1) {
  12429. cell.colSpan--;
  12430. } else {
  12431. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  12432. }
  12433. rowIndex += cellInfo.rowSpan || 1;
  12434. }
  12435. this.table.setAttribute("width", backTableWidth - backTdWidth);
  12436. this.update();
  12437. },
  12438. splitToCells:function (cell) {
  12439. var me = this,
  12440. cells = this.splitToRows(cell);
  12441. utils.each(cells, function (cell) {
  12442. me.splitToCols(cell);
  12443. })
  12444. },
  12445. splitToRows:function (cell) {
  12446. var cellInfo = this.getCellInfo(cell),
  12447. rowIndex = cellInfo.rowIndex,
  12448. colIndex = cellInfo.colIndex,
  12449. results = [];
  12450. // 修改Cell的rowSpan
  12451. cell.rowSpan = 1;
  12452. results.push(cell);
  12453. // 补齐单元格
  12454. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  12455. if (i == rowIndex)continue;
  12456. var tableRow = this.table.rows[i],
  12457. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  12458. tmpCell.colSpan = cellInfo.colSpan;
  12459. this.setCellContent(tmpCell);
  12460. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12461. tmpCell.setAttribute('align', cell.getAttribute('align'));
  12462. if (cell.style.cssText) {
  12463. tmpCell.style.cssText = cell.style.cssText;
  12464. }
  12465. results.push(tmpCell);
  12466. }
  12467. this.update();
  12468. return results;
  12469. },
  12470. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  12471. var indexRow = this.indexTable[rowIndex],
  12472. num = 0;
  12473. for (var i = 0; i < colIndex;) {
  12474. var colSpan = indexRow[i].colSpan,
  12475. tmpRowIndex = indexRow[i].rowIndex;
  12476. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  12477. i += colSpan;
  12478. }
  12479. return num;
  12480. },
  12481. splitToCols:function (cell) {
  12482. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  12483. cellInfo = this.getCellInfo(cell),
  12484. rowIndex = cellInfo.rowIndex,
  12485. colIndex = cellInfo.colIndex,
  12486. results = [];
  12487. // 修改Cell的rowSpan
  12488. cell.colSpan = 1;
  12489. cell.setAttribute("width", backWidth);
  12490. results.push(cell);
  12491. // 补齐单元格
  12492. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  12493. if (j == colIndex)continue;
  12494. var tableRow = this.table.rows[rowIndex],
  12495. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  12496. tmpCell.rowSpan = cellInfo.rowSpan;
  12497. this.setCellContent(tmpCell);
  12498. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12499. tmpCell.setAttribute('align', cell.getAttribute('align'));
  12500. tmpCell.setAttribute('width', backWidth);
  12501. if (cell.style.cssText) {
  12502. tmpCell.style.cssText = cell.style.cssText;
  12503. }
  12504. //处理th的情况
  12505. if (cell.tagName == 'TH') {
  12506. var th = cell.ownerDocument.createElement('th');
  12507. th.appendChild(tmpCell.firstChild);
  12508. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12509. th.rowSpan = tmpCell.rowSpan;
  12510. tableRow.insertBefore(th, tmpCell);
  12511. domUtils.remove(tmpCell);
  12512. }
  12513. results.push(tmpCell);
  12514. }
  12515. this.update();
  12516. return results;
  12517. },
  12518. isLastCell:function (cell, rowsNum, colsNum) {
  12519. rowsNum = rowsNum || this.rowsNum;
  12520. colsNum = colsNum || this.colsNum;
  12521. var cellInfo = this.getCellInfo(cell);
  12522. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  12523. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  12524. },
  12525. getLastCell:function (cells) {
  12526. cells = cells || this.table.getElementsByTagName("td");
  12527. var firstInfo = this.getCellInfo(cells[0]);
  12528. var me = this, last = cells[0],
  12529. tr = last.parentNode,
  12530. cellsNum = 0, cols = 0, rows;
  12531. utils.each(cells, function (cell) {
  12532. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  12533. cellsNum += cell.rowSpan * cell.colSpan || 1;
  12534. });
  12535. rows = cellsNum / cols;
  12536. utils.each(cells, function (cell) {
  12537. if (me.isLastCell(cell, rows, cols)) {
  12538. last = cell;
  12539. return false;
  12540. }
  12541. });
  12542. return last;
  12543. },
  12544. selectRow:function (rowIndex) {
  12545. var indexRow = this.indexTable[rowIndex],
  12546. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  12547. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  12548. range = this.getCellsRange(start, end);
  12549. this.setSelected(range);
  12550. },
  12551. selectTable:function () {
  12552. var tds = this.table.getElementsByTagName("td"),
  12553. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  12554. this.setSelected(range);
  12555. },
  12556. sortTable:function (sortByCellIndex, compareFn) {
  12557. var table = this.table,
  12558. rows = table.rows,
  12559. trArray = [],
  12560. flag = rows[0].cells[0].tagName === "TH",
  12561. lastRowIndex = 0;
  12562. if(this.selectedTds.length){
  12563. var range = this.cellsRange,
  12564. len = range.endRowIndex + 1;
  12565. for (var i = range.beginRowIndex; i < len; i++) {
  12566. trArray[i] = rows[i];
  12567. }
  12568. trArray.splice(0,range.beginRowIndex);
  12569. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  12570. }else{
  12571. for (var i = 0,len = rows.length; i < len; i++) {
  12572. trArray[i] = rows[i];
  12573. }
  12574. }
  12575. //th不参与排序
  12576. flag && trArray.splice(0, 1);
  12577. trArray = utils.sort(trArray,function (tr1, tr2) {
  12578. var txt = function(node){
  12579. return node.innerText||node.textContent;
  12580. };
  12581. return compareFn ? (typeof compareFn === "number" ? compareFn : compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex])) : function () {
  12582. var value1 = txt(tr1.cells[sortByCellIndex]),
  12583. value2 = txt(tr2.cells[sortByCellIndex]);
  12584. return value1.localeCompare(value2);
  12585. }();
  12586. });
  12587. var fragment = table.ownerDocument.createDocumentFragment();
  12588. for (var j = 0, len = trArray.length; j < len; j++) {
  12589. fragment.appendChild(trArray[j]);
  12590. }
  12591. var tbody = table.getElementsByTagName("tbody")[0];
  12592. if(!lastRowIndex){
  12593. tbody.appendChild(fragment);
  12594. }else{
  12595. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  12596. }
  12597. },
  12598. setBackground:function (cells, value) {
  12599. if (typeof value === "string") {
  12600. utils.each(cells, function (cell) {
  12601. cell.style.backgroundColor = value;
  12602. })
  12603. } else if (typeof value === "object") {
  12604. value = utils.extend({
  12605. repeat:true,
  12606. colorList:["#ddd", "#fff"]
  12607. }, value);
  12608. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  12609. count = 0,
  12610. colors = value.colorList,
  12611. getColor = function (list, index, repeat) {
  12612. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  12613. };
  12614. for (var i = 0, cell; cell = cells[i++];) {
  12615. var cellInfo = this.getCellInfo(cell);
  12616. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  12617. }
  12618. }
  12619. },
  12620. removeBackground:function (cells) {
  12621. utils.each(cells, function (cell) {
  12622. cell.style.backgroundColor = "";
  12623. })
  12624. }
  12625. };
  12626. function showError(e) {
  12627. }
  12628. })();
  12629. /**
  12630. * Created with JetBrains PhpStorm.
  12631. * User: taoqili
  12632. * Date: 13-2-20
  12633. * Time: 下午6:25
  12634. * To change this template use File | Settings | File Templates.
  12635. */
  12636. ;
  12637. (function () {
  12638. var UT = UE.UETable,
  12639. getTableItemsByRange = function (editor) {
  12640. return UT.getTableItemsByRange(editor);
  12641. },
  12642. getUETableBySelected = function (editor) {
  12643. return UT.getUETableBySelected(editor)
  12644. },
  12645. getDefaultValue = function (editor, table) {
  12646. return UT.getDefaultValue(editor, table);
  12647. },
  12648. getUETable = function (tdOrTable) {
  12649. return UT.getUETable(tdOrTable);
  12650. };
  12651. UE.commands['inserttable'] = {
  12652. queryCommandState: function () {
  12653. return getTableItemsByRange(this).table ? -1 : 0;
  12654. },
  12655. execCommand: function (cmd, opt) {
  12656. function createTable(opt, tdWidth) {
  12657. var html = [],
  12658. rowsNum = opt.numRows,
  12659. colsNum = opt.numCols;
  12660. for (var r = 0; r < rowsNum; r++) {
  12661. html.push('<tr>');
  12662. for (var c = 0; c < colsNum; c++) {
  12663. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  12664. }
  12665. html.push('</tr>')
  12666. }
  12667. //禁止指定table-width
  12668. return '<table><tbody>' + html.join('') + '</tbody></table>'
  12669. }
  12670. if (!opt) {
  12671. opt = utils.extend({}, {
  12672. numCols: this.options.defaultCols,
  12673. numRows: this.options.defaultRows,
  12674. tdvalign: this.options.tdvalign
  12675. })
  12676. }
  12677. var me = this;
  12678. var range = this.selection.getRange(),
  12679. start = range.startContainer,
  12680. firstParentBlock = domUtils.findParent(start, function (node) {
  12681. return domUtils.isBlockElm(node);
  12682. }, true) || me.body;
  12683. var defaultValue = getDefaultValue(me),
  12684. tableWidth = firstParentBlock.offsetWidth,
  12685. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  12686. //todo其他属性
  12687. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  12688. me.execCommand("inserthtml", createTable(opt, tdWidth));
  12689. }
  12690. };
  12691. UE.commands['insertparagraphbeforetable'] = {
  12692. queryCommandState: function () {
  12693. return getTableItemsByRange(this).cell ? 0 : -1;
  12694. },
  12695. execCommand: function () {
  12696. var table = getTableItemsByRange(this).table;
  12697. if (table) {
  12698. var p = this.document.createElement("p");
  12699. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  12700. table.parentNode.insertBefore(p, table);
  12701. this.selection.getRange().setStart(p, 0).setCursor();
  12702. }
  12703. }
  12704. };
  12705. UE.commands['deletetable'] = {
  12706. queryCommandState: function () {
  12707. var rng = this.selection.getRange();
  12708. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  12709. },
  12710. execCommand: function (cmd, table) {
  12711. var rng = this.selection.getRange();
  12712. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  12713. if (table) {
  12714. var next = table.nextSibling;
  12715. if (!next) {
  12716. next = domUtils.createElement(this.document, 'p', {
  12717. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  12718. });
  12719. table.parentNode.insertBefore(next, table);
  12720. }
  12721. domUtils.remove(table);
  12722. rng = this.selection.getRange();
  12723. if (next.nodeType == 3) {
  12724. rng.setStartBefore(next)
  12725. } else {
  12726. rng.setStart(next, 0)
  12727. }
  12728. rng.setCursor(false, true)
  12729. this.fireEvent("tablehasdeleted")
  12730. }
  12731. }
  12732. };
  12733. UE.commands['cellalign'] = {
  12734. queryCommandState: function () {
  12735. return getSelectedArr(this).length ? 0 : -1
  12736. },
  12737. execCommand: function (cmd, align) {
  12738. var selectedTds = getSelectedArr(this);
  12739. if (selectedTds.length) {
  12740. for (var i = 0, ci; ci = selectedTds[i++];) {
  12741. ci.setAttribute('align', align);
  12742. }
  12743. }
  12744. }
  12745. };
  12746. UE.commands['cellvalign'] = {
  12747. queryCommandState: function () {
  12748. return getSelectedArr(this).length ? 0 : -1;
  12749. },
  12750. execCommand: function (cmd, valign) {
  12751. var selectedTds = getSelectedArr(this);
  12752. if (selectedTds.length) {
  12753. for (var i = 0, ci; ci = selectedTds[i++];) {
  12754. ci.setAttribute('vAlign', valign);
  12755. }
  12756. }
  12757. }
  12758. };
  12759. UE.commands['insertcaption'] = {
  12760. queryCommandState: function () {
  12761. var table = getTableItemsByRange(this).table;
  12762. if (table) {
  12763. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  12764. }
  12765. return -1;
  12766. },
  12767. execCommand: function () {
  12768. var table = getTableItemsByRange(this).table;
  12769. if (table) {
  12770. var caption = this.document.createElement('caption');
  12771. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  12772. table.insertBefore(caption, table.firstChild);
  12773. var range = this.selection.getRange();
  12774. range.setStart(caption, 0).setCursor();
  12775. }
  12776. }
  12777. };
  12778. UE.commands['deletecaption'] = {
  12779. queryCommandState: function () {
  12780. var rng = this.selection.getRange(),
  12781. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  12782. if (table) {
  12783. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  12784. }
  12785. return -1;
  12786. },
  12787. execCommand: function () {
  12788. var rng = this.selection.getRange(),
  12789. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  12790. if (table) {
  12791. domUtils.remove(table.getElementsByTagName('caption')[0]);
  12792. var range = this.selection.getRange();
  12793. range.setStart(table.rows[0].cells[0], 0).setCursor();
  12794. }
  12795. }
  12796. };
  12797. UE.commands['inserttitle'] = {
  12798. queryCommandState: function () {
  12799. var table = getTableItemsByRange(this).table;
  12800. if (table) {
  12801. var firstRow = table.rows[0];
  12802. return firstRow.getElementsByTagName('th').length == 0 ? 0 : -1
  12803. }
  12804. return -1;
  12805. },
  12806. execCommand: function () {
  12807. var table = getTableItemsByRange(this).table;
  12808. if (table) {
  12809. getUETable(table).insertRow(0, 'th');
  12810. }
  12811. var th = table.getElementsByTagName('th')[0];
  12812. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  12813. }
  12814. };
  12815. UE.commands['deletetitle'] = {
  12816. queryCommandState: function () {
  12817. var table = getTableItemsByRange(this).table;
  12818. if (table) {
  12819. var firstRow = table.rows[0];
  12820. return firstRow.getElementsByTagName('th').length ? 0 : -1
  12821. }
  12822. return -1;
  12823. },
  12824. execCommand: function () {
  12825. var table = getTableItemsByRange(this).table;
  12826. if (table) {
  12827. domUtils.remove(table.rows[0])
  12828. }
  12829. var td = table.getElementsByTagName('td')[0];
  12830. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  12831. }
  12832. };
  12833. UE.commands["mergeright"] = {
  12834. queryCommandState: function (cmd) {
  12835. var tableItems = getTableItemsByRange(this);
  12836. if (!tableItems.cell) return -1;
  12837. var ut = getUETable(tableItems.table);
  12838. if (ut.selectedTds.length) return -1;
  12839. var cellInfo = ut.getCellInfo(tableItems.cell),
  12840. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  12841. if (rightColIndex >= ut.colsNum) return -1;
  12842. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  12843. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  12844. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  12845. },
  12846. execCommand: function (cmd) {
  12847. var rng = this.selection.getRange(),
  12848. bk = rng.createBookmark(true);
  12849. var cell = getTableItemsByRange(this).cell,
  12850. ut = getUETable(cell);
  12851. ut.mergeRight(cell);
  12852. rng.moveToBookmark(bk).select();
  12853. }
  12854. };
  12855. UE.commands["mergedown"] = {
  12856. queryCommandState: function (cmd) {
  12857. var tableItems = getTableItemsByRange(this),
  12858. cell = tableItems.cell;
  12859. if (!cell || cell.tagName == "TH") return -1;
  12860. var ut = getUETable(tableItems.table);
  12861. if (ut.selectedTds.length)return -1;
  12862. var cellInfo = ut.getCellInfo(tableItems.cell),
  12863. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  12864. // 如果处于最下边则不能f向右合并
  12865. if (downRowIndex >= ut.rowsNum) return -1;
  12866. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  12867. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  12868. return (downCellInfo.colIndex == cellInfo.colIndex
  12869. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  12870. },
  12871. execCommand: function () {
  12872. var rng = this.selection.getRange(),
  12873. bk = rng.createBookmark(true);
  12874. var cell = getTableItemsByRange(this).cell,
  12875. ut = getUETable(cell);
  12876. ut.mergeDown(cell);
  12877. rng.moveToBookmark(bk).select();
  12878. }
  12879. };
  12880. UE.commands["mergecells"] = {
  12881. queryCommandState: function () {
  12882. return getUETableBySelected(this) ? 0 : -1;
  12883. },
  12884. execCommand: function () {
  12885. var ut = getUETableBySelected(this);
  12886. if (ut && ut.selectedTds.length) {
  12887. var cell = ut.selectedTds[0];
  12888. ut.mergeRange();
  12889. var rng = this.selection.getRange();
  12890. if (domUtils.isEmptyBlock(cell)) {
  12891. rng.setStart(cell, 0).collapse(true)
  12892. } else {
  12893. rng.selectNodeContents(cell)
  12894. }
  12895. rng.select();
  12896. }
  12897. }
  12898. };
  12899. UE.commands["insertrow"] = {
  12900. queryCommandState: function () {
  12901. var tableItems = getTableItemsByRange(this),
  12902. cell = tableItems.cell;
  12903. return cell && cell.tagName == "TD" && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  12904. },
  12905. execCommand: function () {
  12906. var rng = this.selection.getRange(),
  12907. bk = rng.createBookmark(true);
  12908. var tableItems = getTableItemsByRange(this),
  12909. cell = tableItems.cell,
  12910. table = tableItems.table,
  12911. ut = getUETable(table),
  12912. cellInfo = ut.getCellInfo(cell);
  12913. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  12914. if (!ut.selectedTds.length) {
  12915. ut.insertRow(cellInfo.rowIndex, cell);
  12916. } else {
  12917. var range = ut.cellsRange;
  12918. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  12919. ut.insertRow(range.beginRowIndex, cell);
  12920. }
  12921. }
  12922. rng.moveToBookmark(bk).select();
  12923. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12924. }
  12925. };
  12926. //后插入行
  12927. UE.commands["insertrownext"] = {
  12928. queryCommandState: function () {
  12929. var tableItems = getTableItemsByRange(this),
  12930. cell = tableItems.cell;
  12931. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  12932. },
  12933. execCommand: function () {
  12934. var rng = this.selection.getRange(),
  12935. bk = rng.createBookmark(true);
  12936. var tableItems = getTableItemsByRange(this),
  12937. cell = tableItems.cell,
  12938. table = tableItems.table,
  12939. ut = getUETable(table),
  12940. cellInfo = ut.getCellInfo(cell);
  12941. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  12942. if (!ut.selectedTds.length) {
  12943. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  12944. } else {
  12945. var range = ut.cellsRange;
  12946. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  12947. ut.insertRow(range.endRowIndex + 1, cell);
  12948. }
  12949. }
  12950. rng.moveToBookmark(bk).select();
  12951. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12952. }
  12953. };
  12954. UE.commands["deleterow"] = {
  12955. queryCommandState: function () {
  12956. var tableItems = getTableItemsByRange(this);
  12957. if (!tableItems.cell) {
  12958. return -1;
  12959. }
  12960. },
  12961. execCommand: function () {
  12962. var cell = getTableItemsByRange(this).cell,
  12963. ut = getUETable(cell),
  12964. cellsRange = ut.cellsRange,
  12965. cellInfo = ut.getCellInfo(cell),
  12966. preCell = ut.getVSideCell(cell),
  12967. nextCell = ut.getVSideCell(cell, true),
  12968. rng = this.selection.getRange();
  12969. if (utils.isEmptyObject(cellsRange)) {
  12970. ut.deleteRow(cellInfo.rowIndex);
  12971. } else {
  12972. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  12973. ut.deleteRow(cellsRange.beginRowIndex);
  12974. }
  12975. }
  12976. var table = ut.table;
  12977. if (!table.getElementsByTagName('td').length) {
  12978. var nextSibling = table.nextSibling;
  12979. domUtils.remove(table);
  12980. if (nextSibling) {
  12981. rng.setStart(nextSibling, 0).setCursor(false, true);
  12982. }
  12983. } else {
  12984. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  12985. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  12986. } else {
  12987. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  12988. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  12989. }
  12990. }
  12991. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12992. }
  12993. };
  12994. UE.commands["insertcol"] = {
  12995. queryCommandState: function (cmd) {
  12996. var tableItems = getTableItemsByRange(this),
  12997. cell = tableItems.cell;
  12998. return cell && (cell.tagName == "TD" || cell.tagName == 'TH') && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  12999. },
  13000. execCommand: function (cmd) {
  13001. var rng = this.selection.getRange(),
  13002. bk = rng.createBookmark(true);
  13003. if (this.queryCommandState(cmd) == -1)return;
  13004. var cell = getTableItemsByRange(this).cell,
  13005. ut = getUETable(cell),
  13006. cellInfo = ut.getCellInfo(cell);
  13007. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  13008. if (!ut.selectedTds.length) {
  13009. ut.insertCol(cellInfo.colIndex, cell);
  13010. } else {
  13011. var range = ut.cellsRange;
  13012. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  13013. ut.insertCol(range.beginColIndex, cell);
  13014. }
  13015. }
  13016. rng.moveToBookmark(bk).select(true);
  13017. }
  13018. };
  13019. UE.commands["insertcolnext"] = {
  13020. queryCommandState: function () {
  13021. var tableItems = getTableItemsByRange(this),
  13022. cell = tableItems.cell;
  13023. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  13024. },
  13025. execCommand: function () {
  13026. var rng = this.selection.getRange(),
  13027. bk = rng.createBookmark(true);
  13028. var cell = getTableItemsByRange(this).cell,
  13029. ut = getUETable(cell),
  13030. cellInfo = ut.getCellInfo(cell);
  13031. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  13032. if (!ut.selectedTds.length) {
  13033. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  13034. } else {
  13035. var range = ut.cellsRange;
  13036. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  13037. ut.insertCol(range.endColIndex + 1, cell);
  13038. }
  13039. }
  13040. rng.moveToBookmark(bk).select();
  13041. }
  13042. };
  13043. UE.commands["deletecol"] = {
  13044. queryCommandState: function () {
  13045. var tableItems = getTableItemsByRange(this);
  13046. if (!tableItems.cell) return -1;
  13047. },
  13048. execCommand: function () {
  13049. var cell = getTableItemsByRange(this).cell,
  13050. ut = getUETable(cell),
  13051. range = ut.cellsRange,
  13052. cellInfo = ut.getCellInfo(cell),
  13053. preCell = ut.getHSideCell(cell),
  13054. nextCell = ut.getHSideCell(cell, true);
  13055. if (utils.isEmptyObject(range)) {
  13056. ut.deleteCol(cellInfo.colIndex);
  13057. } else {
  13058. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  13059. ut.deleteCol(range.beginColIndex);
  13060. }
  13061. }
  13062. var table = ut.table,
  13063. rng = this.selection.getRange();
  13064. if (!table.getElementsByTagName('td').length) {
  13065. var nextSibling = table.nextSibling;
  13066. domUtils.remove(table);
  13067. if (nextSibling) {
  13068. rng.setStart(nextSibling, 0).setCursor(false, true);
  13069. }
  13070. } else {
  13071. if (domUtils.inDoc(cell, this.document)) {
  13072. rng.setStart(cell, 0).setCursor(false, true);
  13073. } else {
  13074. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  13075. rng.selectNodeContents(nextCell).setCursor(false, true);
  13076. } else {
  13077. if (preCell && domUtils.inDoc(preCell, this.document)) {
  13078. rng.selectNodeContents(preCell).setCursor(true, true);
  13079. }
  13080. }
  13081. }
  13082. }
  13083. }
  13084. };
  13085. UE.commands["splittocells"] = {
  13086. queryCommandState: function () {
  13087. var tableItems = getTableItemsByRange(this),
  13088. cell = tableItems.cell;
  13089. if (!cell) return -1;
  13090. var ut = getUETable(tableItems.table);
  13091. if (ut.selectedTds.length > 0) return -1;
  13092. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  13093. },
  13094. execCommand: function () {
  13095. var rng = this.selection.getRange(),
  13096. bk = rng.createBookmark(true);
  13097. var cell = getTableItemsByRange(this).cell,
  13098. ut = getUETable(cell);
  13099. ut.splitToCells(cell);
  13100. rng.moveToBookmark(bk).select();
  13101. }
  13102. };
  13103. UE.commands["splittorows"] = {
  13104. queryCommandState: function () {
  13105. var tableItems = getTableItemsByRange(this),
  13106. cell = tableItems.cell;
  13107. if (!cell) return -1;
  13108. var ut = getUETable(tableItems.table);
  13109. if (ut.selectedTds.length > 0) return -1;
  13110. return cell && cell.rowSpan > 1 ? 0 : -1;
  13111. },
  13112. execCommand: function () {
  13113. var rng = this.selection.getRange(),
  13114. bk = rng.createBookmark(true);
  13115. var cell = getTableItemsByRange(this).cell,
  13116. ut = getUETable(cell);
  13117. ut.splitToRows(cell);
  13118. rng.moveToBookmark(bk).select();
  13119. }
  13120. };
  13121. UE.commands["splittocols"] = {
  13122. queryCommandState: function () {
  13123. var tableItems = getTableItemsByRange(this),
  13124. cell = tableItems.cell;
  13125. if (!cell) return -1;
  13126. var ut = getUETable(tableItems.table);
  13127. if (ut.selectedTds.length > 0) return -1;
  13128. return cell && cell.colSpan > 1 ? 0 : -1;
  13129. },
  13130. execCommand: function () {
  13131. var rng = this.selection.getRange(),
  13132. bk = rng.createBookmark(true);
  13133. var cell = getTableItemsByRange(this).cell,
  13134. ut = getUETable(cell);
  13135. ut.splitToCols(cell);
  13136. rng.moveToBookmark(bk).select();
  13137. }
  13138. };
  13139. UE.commands["adaptbytext"] =
  13140. UE.commands["adaptbywindow"] = {
  13141. queryCommandState: function () {
  13142. return getTableItemsByRange(this).table ? 0 : -1
  13143. },
  13144. execCommand: function (cmd) {
  13145. var tableItems = getTableItemsByRange(this),
  13146. table = tableItems.table;
  13147. if (table) {
  13148. if (cmd == 'adaptbywindow') {
  13149. resetTdWidth(table, this);
  13150. } else {
  13151. var cells = domUtils.getElementsByTagName(table, "td th");
  13152. utils.each(cells, function (cell) {
  13153. cell.removeAttribute("width");
  13154. });
  13155. table.removeAttribute("width");
  13156. }
  13157. }
  13158. }
  13159. };
  13160. //平均分配各列
  13161. UE.commands['averagedistributecol'] = {
  13162. queryCommandState: function () {
  13163. var ut = getUETableBySelected(this);
  13164. if (!ut) return -1;
  13165. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  13166. },
  13167. execCommand: function (cmd) {
  13168. var me = this,
  13169. ut = getUETableBySelected(me);
  13170. function getAverageWidth() {
  13171. var tb = ut.table,
  13172. averageWidth, sumWidth = 0, colsNum = 0,
  13173. tbAttr = getDefaultValue(me, tb);
  13174. if (ut.isFullRow()) {
  13175. sumWidth = tb.offsetWidth;
  13176. colsNum = ut.colsNum;
  13177. } else {
  13178. var begin = ut.cellsRange.beginColIndex,
  13179. end = ut.cellsRange.endColIndex,
  13180. node;
  13181. for (var i = begin; i <= end;) {
  13182. node = ut.selectedTds[i];
  13183. sumWidth += node.offsetWidth;
  13184. i += node.colSpan;
  13185. colsNum += 1;
  13186. }
  13187. }
  13188. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  13189. return averageWidth;
  13190. }
  13191. function setAverageWidth(averageWidth) {
  13192. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  13193. node.setAttribute("width", "");
  13194. });
  13195. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  13196. utils.each(cells, function (node) {
  13197. if (node.colSpan == 1) {
  13198. node.setAttribute("width", averageWidth);
  13199. }
  13200. });
  13201. }
  13202. if (ut && ut.selectedTds.length) {
  13203. setAverageWidth(getAverageWidth());
  13204. }
  13205. }
  13206. };
  13207. //平均分配各行
  13208. UE.commands['averagedistributerow'] = {
  13209. queryCommandState: function () {
  13210. var ut = getUETableBySelected(this);
  13211. if (!ut) return -1;
  13212. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  13213. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  13214. },
  13215. execCommand: function (cmd) {
  13216. var me = this,
  13217. ut = getUETableBySelected(me);
  13218. function getAverageHeight() {
  13219. var averageHeight, rowNum, sumHeight = 0,
  13220. tb = ut.table,
  13221. tbAttr = getDefaultValue(me, tb),
  13222. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  13223. if (ut.isFullCol()) {
  13224. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  13225. thArr = domUtils.getElementsByTagName(tb, "th"),
  13226. captionHeight, thHeight;
  13227. if (captionArr.length > 0) {
  13228. captionHeight = captionArr[0].offsetHeight;
  13229. }
  13230. if (thArr.length > 0) {
  13231. thHeight = thArr[0].offsetHeight;
  13232. }
  13233. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  13234. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  13235. } else {
  13236. var begin = ut.cellsRange.beginRowIndex,
  13237. end = ut.cellsRange.endRowIndex,
  13238. count = 0,
  13239. trs = domUtils.getElementsByTagName(tb, "tr");
  13240. for (var i = begin; i <= end; i++) {
  13241. sumHeight += trs[i].offsetHeight;
  13242. count += 1;
  13243. }
  13244. rowNum = count;
  13245. }
  13246. //ie8下是混杂模式
  13247. if (browser.ie && browser.version < 9) {
  13248. averageHeight = Math.ceil(sumHeight / rowNum);
  13249. } else {
  13250. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  13251. }
  13252. return averageHeight;
  13253. }
  13254. function setAverageHeight(averageHeight) {
  13255. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  13256. utils.each(cells, function (node) {
  13257. if (node.rowSpan == 1) {
  13258. node.setAttribute("height", averageHeight);
  13259. }
  13260. });
  13261. }
  13262. if (ut && ut.selectedTds.length) {
  13263. setAverageHeight(getAverageHeight());
  13264. }
  13265. }
  13266. };
  13267. //单元格对齐方式
  13268. UE.commands['cellalignment'] = {
  13269. queryCommandState: function () {
  13270. return getTableItemsByRange(this).table ? 0 : -1
  13271. },
  13272. execCommand: function (cmd, data) {
  13273. var me = this,
  13274. ut = getUETableBySelected(me);
  13275. if (!ut) {
  13276. var start = me.selection.getStart(),
  13277. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  13278. if (!/caption/ig.test(cell.tagName)) {
  13279. domUtils.setAttributes(cell, data);
  13280. } else {
  13281. cell.style.textAlign = data.align;
  13282. cell.style.verticalAlign = data.vAlign;
  13283. }
  13284. me.selection.getRange().setCursor(true);
  13285. } else {
  13286. utils.each(ut.selectedTds, function (cell) {
  13287. domUtils.setAttributes(cell, data);
  13288. });
  13289. }
  13290. },
  13291. /**
  13292. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  13293. * @see UE.UETable.getTableCellAlignState
  13294. */
  13295. queryCommandValue: function (cmd) {
  13296. var activeMenuCell = getTableItemsByRange( this).cell;
  13297. if( !activeMenuCell ) {
  13298. activeMenuCell = getSelectedArr(this)[0];
  13299. }
  13300. if (!activeMenuCell) {
  13301. return null;
  13302. } else {
  13303. //获取同时选中的其他单元格
  13304. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  13305. !cells.length && ( cells = activeMenuCell );
  13306. return UE.UETable.getTableCellAlignState(cells);
  13307. }
  13308. }
  13309. };
  13310. //表格对齐方式
  13311. UE.commands['tablealignment'] = {
  13312. queryCommandState: function () {
  13313. if (browser.ie && browser.version < 8) {
  13314. return -1;
  13315. }
  13316. return getTableItemsByRange(this).table ? 0 : -1
  13317. },
  13318. execCommand: function (cmd, value) {
  13319. var me = this,
  13320. start = me.selection.getStart(),
  13321. table = start && domUtils.findParentByTagName(start, ["table"], true);
  13322. if (table) {
  13323. table.setAttribute("align",value);
  13324. }
  13325. }
  13326. };
  13327. //表格属性
  13328. UE.commands['edittable'] = {
  13329. queryCommandState: function () {
  13330. return getTableItemsByRange(this).table ? 0 : -1
  13331. },
  13332. execCommand: function (cmd, color) {
  13333. var rng = this.selection.getRange(),
  13334. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13335. if (table) {
  13336. var arr = domUtils.getElementsByTagName(table, "td").concat(
  13337. domUtils.getElementsByTagName(table, "th"),
  13338. domUtils.getElementsByTagName(table, "caption")
  13339. );
  13340. utils.each(arr, function (node) {
  13341. node.style.borderColor = color;
  13342. });
  13343. }
  13344. }
  13345. };
  13346. //单元格属性
  13347. UE.commands['edittd'] = {
  13348. queryCommandState: function () {
  13349. return getTableItemsByRange(this).table ? 0 : -1
  13350. },
  13351. execCommand: function (cmd, bkColor) {
  13352. var me = this,
  13353. ut = getUETableBySelected(me);
  13354. if (!ut) {
  13355. var start = me.selection.getStart(),
  13356. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  13357. if (cell) {
  13358. cell.style.backgroundColor = bkColor;
  13359. }
  13360. } else {
  13361. utils.each(ut.selectedTds, function (cell) {
  13362. cell.style.backgroundColor = bkColor;
  13363. });
  13364. }
  13365. }
  13366. };
  13367. UE.commands['sorttable'] = {
  13368. queryCommandState: function () {
  13369. var me = this,
  13370. tableItems = getTableItemsByRange(me);
  13371. if (!tableItems.cell) return -1;
  13372. var table = tableItems.table,
  13373. cells = table.getElementsByTagName("td");
  13374. for (var i = 0, cell; cell = cells[i++];) {
  13375. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  13376. }
  13377. return 0;
  13378. },
  13379. execCommand: function (cmd, fn) {
  13380. var me = this,
  13381. range = me.selection.getRange(),
  13382. bk = range.createBookmark(true),
  13383. tableItems = getTableItemsByRange(me),
  13384. cell = tableItems.cell,
  13385. ut = getUETable(tableItems.table),
  13386. cellInfo = ut.getCellInfo(cell);
  13387. ut.sortTable(cellInfo.cellIndex, fn);
  13388. range.moveToBookmark(bk).select();
  13389. }
  13390. };
  13391. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  13392. queryCommandState: function () {
  13393. return getTableItemsByRange(this).table ? 0 : -1;
  13394. },
  13395. execCommand: function (cmd) {
  13396. var table = getTableItemsByRange(this).table;
  13397. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  13398. }
  13399. };
  13400. UE.commands["settablebackground"] = {
  13401. queryCommandState: function () {
  13402. return getSelectedArr(this).length > 1 ? 0 : -1;
  13403. },
  13404. execCommand: function (cmd, value) {
  13405. var table, cells, ut;
  13406. cells = getSelectedArr(this);
  13407. ut = getUETable(cells[0]);
  13408. ut.setBackground(cells, value);
  13409. }
  13410. };
  13411. UE.commands["cleartablebackground"] = {
  13412. queryCommandState: function () {
  13413. var cells = getSelectedArr(this);
  13414. if (!cells.length)return -1;
  13415. for (var i = 0, cell; cell = cells[i++];) {
  13416. if (cell.style.backgroundColor !== "") return 0;
  13417. }
  13418. return -1;
  13419. },
  13420. execCommand: function () {
  13421. var cells = getSelectedArr(this),
  13422. ut = getUETable(cells[0]);
  13423. ut.removeBackground(cells);
  13424. }
  13425. };
  13426. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  13427. queryCommandState: function (cmd) {
  13428. var table = getTableItemsByRange(this).table;
  13429. if (!table) return -1;
  13430. var interlaced = table.getAttribute("interlaced");
  13431. if (cmd == "interlacetable") {
  13432. //TODO 待定
  13433. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  13434. return (interlaced === "enabled") ? -1 : 0;
  13435. } else {
  13436. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  13437. }
  13438. },
  13439. execCommand: function (cmd, classList) {
  13440. var table = getTableItemsByRange(this).table;
  13441. if (cmd == "interlacetable") {
  13442. table.setAttribute("interlaced", "enabled");
  13443. this.fireEvent("interlacetable", table, classList);
  13444. } else {
  13445. table.setAttribute("interlaced", "disabled");
  13446. this.fireEvent("uninterlacetable", table);
  13447. }
  13448. }
  13449. };
  13450. function resetTdWidth(table, editor) {
  13451. var tds = table.getElementsByTagName("td");
  13452. utils.each(tds, function (td) {
  13453. td.removeAttribute("width");
  13454. });
  13455. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  13456. setTimeout(function () {
  13457. utils.each(tds, function (td) {
  13458. (td.colSpan == 1) && td.setAttribute("width", td.offsetWidth + "");
  13459. })
  13460. }, 0);
  13461. }
  13462. function getTableWidth(editor, needIEHack, defaultValue) {
  13463. var body = editor.body;
  13464. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  13465. }
  13466. function getSelectedArr(editor) {
  13467. var cell = getTableItemsByRange(editor).cell;
  13468. if (cell) {
  13469. var ut = getUETable(cell);
  13470. return ut.selectedTds.length ? ut.selectedTds : [cell];
  13471. } else {
  13472. return [];
  13473. }
  13474. }
  13475. })();
  13476. /**
  13477. * Created with JetBrains PhpStorm.
  13478. * User: taoqili
  13479. * Date: 12-10-12
  13480. * Time: 上午10:05
  13481. * To change this template use File | Settings | File Templates.
  13482. */
  13483. UE.plugins['table'] = function () {
  13484. var me = this,
  13485. tabTimer = null,
  13486. //拖动计时器
  13487. tableDragTimer = null,
  13488. //双击计时器
  13489. tableResizeTimer = null,
  13490. //单元格最小宽度
  13491. cellMinWidth = 5,
  13492. isInResizeBuffer = false,
  13493. //单元格边框大小
  13494. cellBorderWidth = 5,
  13495. //鼠标偏移距离
  13496. offsetOfTableCell = 10,
  13497. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  13498. singleClickState = 0,
  13499. userActionStatus = null,
  13500. //双击允许的时间范围
  13501. dblclickTime = 360,
  13502. UT = UE.UETable,
  13503. getUETable = function (tdOrTable) {
  13504. return UT.getUETable(tdOrTable);
  13505. },
  13506. getUETableBySelected = function (editor) {
  13507. return UT.getUETableBySelected(editor);
  13508. },
  13509. getDefaultValue = function (editor, table) {
  13510. return UT.getDefaultValue(editor, table);
  13511. },
  13512. removeSelectedClass = function (cells) {
  13513. return UT.removeSelectedClass(cells);
  13514. };
  13515. function showError(e) {
  13516. // throw e;
  13517. }
  13518. me.ready(function(){
  13519. var me = this;
  13520. var orgGetText = me.selection.getText;
  13521. me.selection.getText = function(){
  13522. var table = getUETableBySelected(me);
  13523. if(table){
  13524. var str = '';
  13525. utils.each(table.selectedTds,function(td){
  13526. str += td[browser.ie?'innerText':'textContent'];
  13527. })
  13528. return str;
  13529. }else{
  13530. return orgGetText.call(me.selection)
  13531. }
  13532. }
  13533. })
  13534. //处理拖动及框选相关方法
  13535. var startTd = null, //鼠标按下时的锚点td
  13536. currentTd = null, //当前鼠标经过时的td
  13537. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  13538. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  13539. dragButton = null,
  13540. dragOver = false,
  13541. dragLine = null, //模拟的拖动线
  13542. dragTd = null; //发生拖动的目标td
  13543. var mousedown = false,
  13544. //todo 判断混乱模式
  13545. needIEHack = true;
  13546. me.setOpt({
  13547. 'maxColNum':20,
  13548. 'maxRowNum':100,
  13549. 'defaultCols':5,
  13550. 'defaultRows':5,
  13551. 'tdvalign':'top',
  13552. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  13553. 'tableDragable':false,
  13554. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  13555. });
  13556. me.getUETable = getUETable;
  13557. var commands = {
  13558. 'deletetable':1,
  13559. 'inserttable':1,
  13560. 'cellvalign':1,
  13561. 'insertcaption':1,
  13562. 'deletecaption':1,
  13563. 'inserttitle':1,
  13564. 'deletetitle':1,
  13565. "mergeright":1,
  13566. "mergedown":1,
  13567. "mergecells":1,
  13568. "insertrow":1,
  13569. "insertrownext":1,
  13570. "deleterow":1,
  13571. "insertcol":1,
  13572. "insertcolnext":1,
  13573. "deletecol":1,
  13574. "splittocells":1,
  13575. "splittorows":1,
  13576. "splittocols":1,
  13577. "adaptbytext":1,
  13578. "adaptbywindow":1,
  13579. "adaptbycustomer":1,
  13580. "insertparagraph":1,
  13581. "insertparagraphbeforetable":1,
  13582. "averagedistributecol":1,
  13583. "averagedistributerow":1
  13584. };
  13585. me.ready(function () {
  13586. utils.cssRule('table',
  13587. //选中的td上的样式
  13588. '.selectTdClass{background-color:#edf5fa !important}' +
  13589. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  13590. //插入的表格的默认样式
  13591. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  13592. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  13593. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  13594. 'th{border-top:2px solid #BBB;background:#F7F7F7;}' +
  13595. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  13596. 'td p{margin:0;padding:0;}', me.document);
  13597. var tableCopyList, isFullCol, isFullRow;
  13598. //注册del/backspace事件
  13599. me.addListener('keydown', function (cmd, evt) {
  13600. var me = this;
  13601. var keyCode = evt.keyCode || evt.which;
  13602. if (keyCode == 8) {
  13603. var ut = getUETableBySelected(me);
  13604. if (ut && ut.selectedTds.length) {
  13605. if (ut.isFullCol()) {
  13606. me.execCommand('deletecol')
  13607. } else if (ut.isFullRow()) {
  13608. me.execCommand('deleterow')
  13609. } else {
  13610. me.fireEvent('delcells');
  13611. }
  13612. domUtils.preventDefault(evt);
  13613. }
  13614. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  13615. range = me.selection.getRange();
  13616. if (range.collapsed && caption && isEmptyBlock(caption)) {
  13617. me.fireEvent('saveScene');
  13618. var table = caption.parentNode;
  13619. domUtils.remove(caption);
  13620. if (table) {
  13621. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  13622. }
  13623. me.fireEvent('saveScene');
  13624. }
  13625. }
  13626. if (keyCode == 46) {
  13627. ut = getUETableBySelected(me);
  13628. if (ut) {
  13629. me.fireEvent('saveScene');
  13630. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  13631. domUtils.fillNode(me.document, ci)
  13632. }
  13633. me.fireEvent('saveScene');
  13634. domUtils.preventDefault(evt);
  13635. }
  13636. }
  13637. if (keyCode == 13) {
  13638. var rng = me.selection.getRange(),
  13639. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  13640. if (caption) {
  13641. var table = domUtils.findParentByTagName(caption, 'table');
  13642. if (!rng.collapsed) {
  13643. rng.deleteContents();
  13644. me.fireEvent('saveScene');
  13645. } else {
  13646. if (caption) {
  13647. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  13648. }
  13649. }
  13650. domUtils.preventDefault(evt);
  13651. return;
  13652. }
  13653. if (rng.collapsed) {
  13654. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13655. if (table) {
  13656. var cell = table.rows[0].cells[0],
  13657. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  13658. preNode = table.previousSibling;
  13659. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  13660. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  13661. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  13662. me.execCommand('insertparagraphbeforetable');
  13663. domUtils.preventDefault(evt);
  13664. }
  13665. }
  13666. }
  13667. }
  13668. }
  13669. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  13670. tableCopyList = null;
  13671. var ut = getUETableBySelected(me);
  13672. if (ut) {
  13673. var tds = ut.selectedTds;
  13674. isFullCol = ut.isFullCol();
  13675. isFullRow = ut.isFullRow();
  13676. tableCopyList = [
  13677. [ut.cloneCell(tds[0],null,true)]
  13678. ];
  13679. for (var i = 1, ci; ci = tds[i]; i++) {
  13680. if (ci.parentNode !== tds[i - 1].parentNode) {
  13681. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  13682. } else {
  13683. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  13684. }
  13685. }
  13686. }
  13687. }
  13688. });
  13689. me.addListener("tablehasdeleted",function(){
  13690. toggleDraggableState(this, false, "", null);
  13691. if (dragButton)domUtils.remove(dragButton);
  13692. });
  13693. me.addListener('beforepaste', function (cmd, html) {
  13694. var me = this;
  13695. var rng = me.selection.getRange();
  13696. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  13697. var div = me.document.createElement("div");
  13698. div.innerHTML = html.html;
  13699. html.html = div[browser.ie ? 'innerText' : 'textContent'];
  13700. return;
  13701. }
  13702. var table = getUETableBySelected(me);
  13703. if (tableCopyList) {
  13704. me.fireEvent('saveScene');
  13705. var rng = me.selection.getRange();
  13706. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  13707. if (td) {
  13708. var ut = getUETable(td);
  13709. if (isFullRow) {
  13710. var rowIndex = ut.getCellInfo(td).rowIndex;
  13711. if (td.tagName == 'TH') {
  13712. rowIndex++;
  13713. }
  13714. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13715. var tr = ut.insertRow(rowIndex++, "td");
  13716. for (var j = 0, cj; cj = ci[j]; j++) {
  13717. var cell = tr.cells[j];
  13718. if (!cell) {
  13719. cell = tr.insertCell(j)
  13720. }
  13721. cell.innerHTML = cj.innerHTML;
  13722. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  13723. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  13724. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  13725. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  13726. }
  13727. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  13728. if (!ci[j])
  13729. break;
  13730. cj.innerHTML = ci[j].innerHTML;
  13731. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  13732. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  13733. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  13734. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  13735. }
  13736. }
  13737. } else {
  13738. if (isFullCol) {
  13739. cellInfo = ut.getCellInfo(td);
  13740. var maxColNum = 0;
  13741. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  13742. maxColNum += cj.colSpan || 1;
  13743. }
  13744. me.__hasEnterExecCommand = true;
  13745. for (i = 0; i < maxColNum; i++) {
  13746. me.execCommand('insertcol');
  13747. }
  13748. me.__hasEnterExecCommand = false;
  13749. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  13750. if (td.tagName == 'TH') {
  13751. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  13752. }
  13753. }
  13754. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13755. tmpNode = td;
  13756. for (var j = 0, cj; cj = ci[j++];) {
  13757. if (td) {
  13758. td.innerHTML = cj.innerHTML;
  13759. //todo 定制处理
  13760. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  13761. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  13762. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  13763. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  13764. preNode = td;
  13765. td = td.nextSibling;
  13766. } else {
  13767. var cloneTd = cj.cloneNode(true);
  13768. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  13769. preNode.parentNode.appendChild(cloneTd)
  13770. }
  13771. }
  13772. td = ut.getNextCell(tmpNode, true, true);
  13773. if (!tableCopyList[i])
  13774. break;
  13775. if (!td) {
  13776. var cellInfo = ut.getCellInfo(tmpNode);
  13777. ut.table.insertRow(ut.table.rows.length);
  13778. ut.update();
  13779. td = ut.getVSideCell(tmpNode, true);
  13780. }
  13781. }
  13782. }
  13783. ut.update();
  13784. } else {
  13785. table = me.document.createElement('table');
  13786. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13787. var tr = table.insertRow(table.rows.length);
  13788. for (var j = 0, cj; cj = ci[j++];) {
  13789. cloneTd = UT.cloneCell(cj,null,true);
  13790. domUtils.removeAttributes(cloneTd, ['class']);
  13791. tr.appendChild(cloneTd)
  13792. }
  13793. if (j == 2 && cloneTd.rowSpan > 1) {
  13794. cloneTd.rowSpan = 1;
  13795. }
  13796. }
  13797. var defaultValue = getDefaultValue(me),
  13798. width = me.body.offsetWidth -
  13799. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  13800. me.execCommand('insertHTML', '<table ' +
  13801. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  13802. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  13803. }
  13804. me.fireEvent('contentchange');
  13805. me.fireEvent('saveScene');
  13806. html.html = '';
  13807. return true;
  13808. } else {
  13809. var div = me.document.createElement("div"), tables;
  13810. div.innerHTML = html.html;
  13811. tables = div.getElementsByTagName("table");
  13812. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  13813. utils.each(tables, function (t) {
  13814. domUtils.remove(t)
  13815. });
  13816. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  13817. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  13818. }
  13819. } else {
  13820. utils.each(tables, function (table) {
  13821. removeStyleSize(table, true);
  13822. domUtils.removeAttributes(table, ['style', 'border']);
  13823. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  13824. if (isEmptyBlock(td)) {
  13825. domUtils.fillNode(me.document, td);
  13826. }
  13827. removeStyleSize(td, true);
  13828. // domUtils.removeAttributes(td, ['style'])
  13829. });
  13830. });
  13831. }
  13832. html.html = div.innerHTML;
  13833. }
  13834. });
  13835. me.addListener('afterpaste', function () {
  13836. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  13837. if (table.offsetWidth > me.body.offsetWidth) {
  13838. var defaultValue = getDefaultValue(me, table);
  13839. 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'
  13840. }
  13841. })
  13842. });
  13843. me.addListener('blur', function () {
  13844. tableCopyList = null;
  13845. });
  13846. var timer;
  13847. me.addListener('keydown', function () {
  13848. clearTimeout(timer);
  13849. timer = setTimeout(function () {
  13850. var rng = me.selection.getRange(),
  13851. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  13852. if (cell) {
  13853. var table = cell.parentNode.parentNode.parentNode;
  13854. if (table.offsetWidth > table.getAttribute("width")) {
  13855. cell.style.wordBreak = "break-all";
  13856. }
  13857. }
  13858. }, 100);
  13859. });
  13860. me.addListener("selectionchange", function () {
  13861. toggleDraggableState(me, false, "", null);
  13862. });
  13863. //内容变化时触发索引更新
  13864. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  13865. me.addListener("contentchange", function () {
  13866. var me = this;
  13867. //尽可能排除一些不需要更新的状况
  13868. hideDragLine(me);
  13869. if (getUETableBySelected(me))return;
  13870. var rng = me.selection.getRange();
  13871. var start = rng.startContainer;
  13872. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  13873. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  13874. if (me.fireEvent("excludetable", table) === true) return;
  13875. table.ueTable = new UT(table);
  13876. utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  13877. if (domUtils.isEmptyBlock(td) && td !== start) {
  13878. domUtils.fillNode(me.document, td);
  13879. if (browser.ie && browser.version == 6) {
  13880. td.innerHTML = '&nbsp;'
  13881. }
  13882. }
  13883. });
  13884. utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  13885. if (domUtils.isEmptyBlock(th) && th !== start) {
  13886. domUtils.fillNode(me.document, th);
  13887. if (browser.ie && browser.version == 6) {
  13888. th.innerHTML = '&nbsp;'
  13889. }
  13890. }
  13891. });
  13892. table.onmouseover = function () {
  13893. me.fireEvent('tablemouseover', table);
  13894. };
  13895. table.onmousemove = function () {
  13896. me.fireEvent('tablemousemove', table);
  13897. me.options.tableDragable && toggleDragButton(true, this, me);
  13898. };
  13899. table.onmouseout = function () {
  13900. me.fireEvent('tablemouseout', table);
  13901. toggleDraggableState(me, false, "", null);
  13902. hideDragLine(me);
  13903. };
  13904. table.onclick = function (evt) {
  13905. evt = me.window.event || evt;
  13906. var target = getParentTdOrTh(evt.target || evt.srcElement);
  13907. if (!target)return;
  13908. var ut = getUETable(target),
  13909. table = ut.table,
  13910. cellInfo = ut.getCellInfo(target),
  13911. cellsRange,
  13912. rng = me.selection.getRange();
  13913. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  13914. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  13915. // ut.setSelected(cellsRange);
  13916. // return;
  13917. // }
  13918. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  13919. //
  13920. // return;
  13921. // }
  13922. if (inTableSide(table, target, evt, true)) {
  13923. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  13924. if (evt.shiftKey && ut.selectedTds.length) {
  13925. if (ut.selectedTds[0] !== endTdCol) {
  13926. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  13927. ut.setSelected(cellsRange);
  13928. } else {
  13929. rng && rng.selectNodeContents(endTdCol).select();
  13930. }
  13931. } else {
  13932. if (target !== endTdCol) {
  13933. cellsRange = ut.getCellsRange(target, endTdCol);
  13934. ut.setSelected(cellsRange);
  13935. } else {
  13936. rng && rng.selectNodeContents(endTdCol).select();
  13937. }
  13938. }
  13939. return;
  13940. }
  13941. if (inTableSide(table, target, evt)) {
  13942. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  13943. if (evt.shiftKey && ut.selectedTds.length) {
  13944. if (ut.selectedTds[0] !== endTdRow) {
  13945. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  13946. ut.setSelected(cellsRange);
  13947. } else {
  13948. rng && rng.selectNodeContents(endTdRow).select();
  13949. }
  13950. } else {
  13951. if (target !== endTdRow) {
  13952. cellsRange = ut.getCellsRange(target, endTdRow);
  13953. ut.setSelected(cellsRange);
  13954. } else {
  13955. rng && rng.selectNodeContents(endTdRow).select();
  13956. }
  13957. }
  13958. }
  13959. };
  13960. });
  13961. switchBorderColor(me, true);
  13962. });
  13963. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  13964. domUtils.on(me.document, "mouseout", function (evt) {
  13965. var target = evt.target || evt.srcElement;
  13966. if (target.tagName == "TABLE") {
  13967. toggleDraggableState(me, false, "", null);
  13968. }
  13969. });
  13970. /**
  13971. * 表格隔行变色
  13972. */
  13973. me.addListener("interlacetable",function(type,table,classList){
  13974. if(!table) return;
  13975. var me = this,
  13976. rows = table.rows,
  13977. len = rows.length,
  13978. getClass = function(list,index,repeat){
  13979. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  13980. };
  13981. for(var i = 0;i<len;i++){
  13982. rows[i].className = getClass( classList|| me.options.classList,i,true);
  13983. }
  13984. });
  13985. me.addListener("uninterlacetable",function(type,table){
  13986. if(!table) return;
  13987. var me = this,
  13988. rows = table.rows,
  13989. classList = me.options.classList,
  13990. len = rows.length;
  13991. for(var i = 0;i<len;i++){
  13992. domUtils.removeClasses( rows[i], classList );
  13993. }
  13994. });
  13995. me.addListener("mousedown", mouseDownEvent);
  13996. me.addListener("mouseup", mouseUpEvent);
  13997. //拖动的时候不出发mouseup
  13998. domUtils.on( me.body, 'dragstart', function( evt ){
  13999. mouseUpEvent.call( me, 'dragstart', evt );
  14000. });
  14001. var currentRowIndex = 0;
  14002. me.addListener("mousedown", function () {
  14003. currentRowIndex = 0;
  14004. });
  14005. me.addListener('tabkeydown', function () {
  14006. var range = this.selection.getRange(),
  14007. common = range.getCommonAncestor(true, true),
  14008. table = domUtils.findParentByTagName(common, 'table');
  14009. if (table) {
  14010. if (domUtils.findParentByTagName(common, 'caption', true)) {
  14011. var cell = domUtils.getElementsByTagName(table, 'th td');
  14012. if (cell && cell.length) {
  14013. range.setStart(cell[0], 0).setCursor(false, true)
  14014. }
  14015. } else {
  14016. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  14017. ua = getUETable(cell);
  14018. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  14019. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  14020. if (nextCell) {
  14021. if (isEmptyBlock(nextCell)) {
  14022. range.setStart(nextCell, 0).setCursor(false, true)
  14023. } else {
  14024. range.selectNodeContents(nextCell).select()
  14025. }
  14026. } else {
  14027. me.fireEvent('saveScene');
  14028. me.__hasEnterExecCommand = true;
  14029. this.execCommand('insertrownext');
  14030. me.__hasEnterExecCommand = false;
  14031. range = this.selection.getRange();
  14032. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  14033. me.fireEvent('saveScene');
  14034. }
  14035. }
  14036. return true;
  14037. }
  14038. });
  14039. browser.ie && me.addListener('selectionchange', function () {
  14040. toggleDraggableState(this, false, "", null);
  14041. });
  14042. me.addListener("keydown", function (type, evt) {
  14043. var me = this;
  14044. //处理在表格的最后一个输入tab产生新的表格
  14045. var keyCode = evt.keyCode || evt.which;
  14046. if (keyCode == 8 || keyCode == 46) {
  14047. return;
  14048. }
  14049. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  14050. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  14051. var ut = getUETableBySelected(me);
  14052. if (!ut) return;
  14053. notCtrlKey && ut.clearSelected();
  14054. });
  14055. me.addListener("beforegetcontent", function () {
  14056. switchBorderColor(this, false);
  14057. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  14058. if (domUtils.isEmptyNode(ci)) {
  14059. ci.innerHTML = '&nbsp;'
  14060. }
  14061. });
  14062. });
  14063. me.addListener("aftergetcontent", function () {
  14064. switchBorderColor(this, true);
  14065. });
  14066. me.addListener("getAllHtml", function () {
  14067. removeSelectedClass(me.document.getElementsByTagName("td"));
  14068. });
  14069. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  14070. me.addListener("fullscreenchanged", function (type, fullscreen) {
  14071. if (!fullscreen) {
  14072. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  14073. tables = domUtils.getElementsByTagName(this.body, "table");
  14074. utils.each(tables, function (table) {
  14075. if (table.offsetWidth < me.body.offsetWidth) return false;
  14076. var tds = domUtils.getElementsByTagName(table, "td"),
  14077. backWidths = [];
  14078. utils.each(tds, function (td) {
  14079. backWidths.push(td.offsetWidth);
  14080. });
  14081. for (var i = 0, td; td = tds[i]; i++) {
  14082. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  14083. }
  14084. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  14085. });
  14086. }
  14087. });
  14088. //重写execCommand命令,用于处理框选时的处理
  14089. var oldExecCommand = me.execCommand;
  14090. me.execCommand = function (cmd, datatat) {
  14091. var me = this,
  14092. args = arguments;
  14093. cmd = cmd.toLowerCase();
  14094. var ut = getUETableBySelected(me), tds,
  14095. range = new dom.Range(me.document),
  14096. cmdFun = me.commands[cmd] || UE.commands[cmd],
  14097. result;
  14098. if (!cmdFun) return;
  14099. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  14100. me.__hasEnterExecCommand = true;
  14101. me.fireEvent("beforeexeccommand", cmd);
  14102. tds = ut.selectedTds;
  14103. var lastState = -2, lastValue = -2, value, state;
  14104. for (var i = 0, td; td = tds[i]; i++) {
  14105. if (isEmptyBlock(td)) {
  14106. range.setStart(td, 0).setCursor(false, true)
  14107. } else {
  14108. range.selectNode(td).select(true);
  14109. }
  14110. state = me.queryCommandState(cmd);
  14111. value = me.queryCommandValue(cmd);
  14112. if (state != -1) {
  14113. if (lastState !== state || lastValue !== value) {
  14114. me._ignoreContentChange = true;
  14115. result = oldExecCommand.apply(me, arguments);
  14116. me._ignoreContentChange = false;
  14117. }
  14118. lastState = me.queryCommandState(cmd);
  14119. lastValue = me.queryCommandValue(cmd);
  14120. if (domUtils.isEmptyBlock(td)) {
  14121. domUtils.fillNode(me.document, td)
  14122. }
  14123. }
  14124. }
  14125. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  14126. me.fireEvent('contentchange');
  14127. me.fireEvent("afterexeccommand", cmd);
  14128. me.__hasEnterExecCommand = false;
  14129. me._selectionChange();
  14130. } else {
  14131. result = oldExecCommand.apply(me, arguments);
  14132. }
  14133. return result;
  14134. };
  14135. });
  14136. /**
  14137. * 删除obj的宽高style,改成属性宽高
  14138. * @param obj
  14139. * @param replaceToProperty
  14140. */
  14141. function removeStyleSize(obj, replaceToProperty) {
  14142. removeStyle(obj, "width", true);
  14143. removeStyle(obj, "height", true);
  14144. }
  14145. function removeStyle(obj, styleName, replaceToProperty) {
  14146. if (obj.style[styleName]) {
  14147. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  14148. obj.style[styleName] = "";
  14149. }
  14150. }
  14151. function getParentTdOrTh(ele) {
  14152. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  14153. var td;
  14154. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  14155. return null;
  14156. }
  14157. function isEmptyBlock(node) {
  14158. var reg = new RegExp(domUtils.fillChar, 'g');
  14159. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  14160. return 0;
  14161. }
  14162. for (var n in dtd.$isNotEmpty) {
  14163. if (node.getElementsByTagName(n).length) {
  14164. return 0;
  14165. }
  14166. }
  14167. return 1;
  14168. }
  14169. function mouseCoords(evt) {
  14170. if (evt.pageX || evt.pageY) {
  14171. return { x:evt.pageX, y:evt.pageY };
  14172. }
  14173. return {
  14174. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  14175. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  14176. };
  14177. }
  14178. function mouseMoveEvent(evt) {
  14179. if( isEditorDisabled() ) {
  14180. return;
  14181. }
  14182. try {
  14183. //普通状态下鼠标移动
  14184. var target = getParentTdOrTh(evt.target || evt.srcElement),
  14185. pos;
  14186. //区分用户的行为是拖动还是双击
  14187. if( isInResizeBuffer ) {
  14188. me.body.style.webkitUserSelect = 'none';
  14189. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  14190. clearTableDragTimer();
  14191. isInResizeBuffer = false;
  14192. singleClickState = 0;
  14193. //drag action
  14194. tableBorderDrag(evt);
  14195. }
  14196. }
  14197. //修改单元格大小时的鼠标移动
  14198. if (onDrag && dragTd) {
  14199. singleClickState = 0;
  14200. me.body.style.webkitUserSelect = 'none';
  14201. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  14202. pos = mouseCoords(evt);
  14203. toggleDraggableState(me, true, onDrag, pos, target);
  14204. if (onDrag == "h") {
  14205. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  14206. } else if (onDrag == "v") {
  14207. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  14208. }
  14209. return;
  14210. }
  14211. //当鼠标处于table上时,修改移动过程中的光标状态
  14212. if (target) {
  14213. //针对使用table作为容器的组件不触发拖拽效果
  14214. if (me.fireEvent('excludetable', target) === true)
  14215. return;
  14216. pos = mouseCoords(evt);
  14217. var state = getRelation(target, pos),
  14218. table = domUtils.findParentByTagName(target, "table", true);
  14219. if (inTableSide(table, target, evt, true)) {
  14220. if (me.fireEvent("excludetable", table) === true) return;
  14221. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  14222. } else if (inTableSide(table, target, evt)) {
  14223. if (me.fireEvent("excludetable", table) === true) return;
  14224. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  14225. } else {
  14226. me.body.style.cursor = "text";
  14227. var curCell = target;
  14228. if (/\d/.test(state)) {
  14229. state = state.replace(/\d/, '');
  14230. target = getUETable(target).getPreviewCell(target, state == "v");
  14231. }
  14232. //位于第一行的顶部或者第一列的左边时不可拖动
  14233. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  14234. }
  14235. } else {
  14236. toggleDragButton(false, table, me);
  14237. }
  14238. } catch (e) {
  14239. showError(e);
  14240. }
  14241. }
  14242. var dragButtonTimer;
  14243. function toggleDragButton(show, table, editor) {
  14244. if (!show) {
  14245. if (dragOver)return;
  14246. dragButtonTimer = setTimeout(function () {
  14247. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  14248. }, 2000);
  14249. } else {
  14250. createDragButton(table, editor);
  14251. }
  14252. }
  14253. function createDragButton(table, editor) {
  14254. var pos = domUtils.getXY(table),
  14255. doc = table.ownerDocument;
  14256. if (dragButton && dragButton.parentNode)return dragButton;
  14257. dragButton = doc.createElement("div");
  14258. dragButton.contentEditable = false;
  14259. dragButton.innerHTML = "";
  14260. 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;";
  14261. domUtils.unSelectable(dragButton);
  14262. dragButton.onmouseover = function (evt) {
  14263. dragOver = true;
  14264. };
  14265. dragButton.onmouseout = function (evt) {
  14266. dragOver = false;
  14267. };
  14268. domUtils.on(dragButton, 'click', function (type, evt) {
  14269. doClick(evt, this);
  14270. });
  14271. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  14272. doDblClick(evt);
  14273. });
  14274. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  14275. domUtils.preventDefault(evt);
  14276. });
  14277. var timer;
  14278. function doClick(evt, button) {
  14279. // 部分浏览器下需要清理
  14280. clearTimeout(timer);
  14281. timer = setTimeout(function () {
  14282. editor.fireEvent("tableClicked", table, button);
  14283. }, 300);
  14284. }
  14285. function doDblClick(evt) {
  14286. clearTimeout(timer);
  14287. var ut = getUETable(table),
  14288. start = table.rows[0].cells[0],
  14289. end = ut.getLastCell(),
  14290. range = ut.getCellsRange(start, end);
  14291. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  14292. ut.setSelected(range);
  14293. }
  14294. doc.body.appendChild(dragButton);
  14295. }
  14296. // function inPosition(table, pos) {
  14297. // var tablePos = domUtils.getXY(table),
  14298. // width = table.offsetWidth,
  14299. // height = table.offsetHeight;
  14300. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  14301. // return "topLeft";
  14302. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  14303. // return "bottomRight";
  14304. // }
  14305. // }
  14306. function inTableSide(table, cell, evt, top) {
  14307. var pos = mouseCoords(evt),
  14308. state = getRelation(cell, pos);
  14309. if (top) {
  14310. var caption = table.getElementsByTagName("caption")[0],
  14311. capHeight = caption ? caption.offsetHeight : 0;
  14312. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  14313. } else {
  14314. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  14315. }
  14316. }
  14317. /**
  14318. * 获取拖动时允许的X轴坐标
  14319. * @param dragTd
  14320. * @param evt
  14321. */
  14322. function getPermissionX(dragTd, evt) {
  14323. var ut = getUETable(dragTd);
  14324. if (ut) {
  14325. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  14326. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  14327. mouseX = mouseCoords(evt).x,
  14328. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  14329. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  14330. left += cellMinWidth;
  14331. right -= cellMinWidth;
  14332. return mouseX < left ? left : mouseX > right ? right : mouseX;
  14333. }
  14334. }
  14335. /**
  14336. * 获取拖动时允许的Y轴坐标
  14337. */
  14338. function getPermissionY(dragTd, evt) {
  14339. try {
  14340. var top = domUtils.getXY(dragTd).y,
  14341. mousePosY = mouseCoords(evt).y;
  14342. return mousePosY < top ? top : mousePosY;
  14343. } catch (e) {
  14344. showError(e);
  14345. }
  14346. }
  14347. /**
  14348. * 移动状态切换
  14349. */
  14350. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  14351. try {
  14352. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  14353. if (browser.ie) {
  14354. if (dir && !mousedown && !getUETableBySelected(editor)) {
  14355. getDragLine(editor, editor.document);
  14356. showDragLineAt(dir, cell);
  14357. } else {
  14358. hideDragLine(editor)
  14359. }
  14360. }
  14361. onBorder = draggable;
  14362. } catch (e) {
  14363. showError(e);
  14364. }
  14365. }
  14366. /**
  14367. * 获取与UETable相关的resize line
  14368. * @param uetable UETable对象
  14369. */
  14370. function getResizeLineByUETable() {
  14371. var lineId = '_UETableResizeLine',
  14372. line = this.document.getElementById( lineId );
  14373. if( !line ) {
  14374. line = this.document.createElement("div");
  14375. line.id = lineId;
  14376. line.contnetEditable = false;
  14377. line.setAttribute("unselectable", "on");
  14378. var styles = {
  14379. width: 2*cellBorderWidth + 1 + 'px',
  14380. position: 'absolute',
  14381. 'z-index': 100000,
  14382. cursor: 'col-resize',
  14383. background: 'red',
  14384. display: 'none'
  14385. };
  14386. //切换状态
  14387. line.onmouseout = function(){
  14388. this.style.display = 'none';
  14389. };
  14390. utils.extend( line.style, styles );
  14391. this.document.body.appendChild( line );
  14392. }
  14393. return line;
  14394. }
  14395. /**
  14396. * 更新resize-line
  14397. */
  14398. function updateResizeLine( cell, uetable ) {
  14399. var line = getResizeLineByUETable.call( this ),
  14400. table = uetable.table,
  14401. styles = {
  14402. top: domUtils.getXY( table ).y + 'px',
  14403. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  14404. display: 'block',
  14405. height: table.offsetHeight + 'px'
  14406. };
  14407. utils.extend( line.style, styles );
  14408. }
  14409. /**
  14410. * 显示resize-line
  14411. */
  14412. function showResizeLine( cell ) {
  14413. var uetable = getUETable( cell );
  14414. updateResizeLine.call( this, cell, uetable );
  14415. }
  14416. /**
  14417. * 获取鼠标与当前单元格的相对位置
  14418. * @param ele
  14419. * @param mousePos
  14420. */
  14421. function getRelation(ele, mousePos) {
  14422. var elePos = domUtils.getXY(ele);
  14423. if( !elePos ) {
  14424. return '';
  14425. }
  14426. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  14427. return "h";
  14428. }
  14429. if (mousePos.x - elePos.x < cellBorderWidth) {
  14430. return 'h1'
  14431. }
  14432. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  14433. return "v";
  14434. }
  14435. if (mousePos.y - elePos.y < cellBorderWidth) {
  14436. return 'v1'
  14437. }
  14438. return '';
  14439. }
  14440. function mouseDownEvent(type, evt) {
  14441. if( isEditorDisabled() ) {
  14442. return ;
  14443. }
  14444. userActionStatus = {
  14445. x: evt.clientX,
  14446. y: evt.clientY
  14447. };
  14448. //右键菜单单独处理
  14449. if (evt.button == 2) {
  14450. var ut = getUETableBySelected(me),
  14451. flag = false;
  14452. if (ut) {
  14453. var td = getTargetTd(me, evt);
  14454. utils.each(ut.selectedTds, function (ti) {
  14455. if (ti === td) {
  14456. flag = true;
  14457. }
  14458. });
  14459. if (!flag) {
  14460. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  14461. ut.clearSelected()
  14462. } else {
  14463. td = ut.selectedTds[0];
  14464. setTimeout(function () {
  14465. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  14466. }, 0);
  14467. }
  14468. }
  14469. } else {
  14470. tableClickHander( evt );
  14471. }
  14472. }
  14473. //清除表格的计时器
  14474. function clearTableTimer() {
  14475. tabTimer && clearTimeout( tabTimer );
  14476. tabTimer = null;
  14477. }
  14478. //双击收缩
  14479. function tableDbclickHandler(evt) {
  14480. singleClickState = 0;
  14481. evt = evt || me.window.event;
  14482. var target = getParentTdOrTh(evt.target || evt.srcElement);
  14483. if (target) {
  14484. var h;
  14485. if (h = getRelation(target, mouseCoords(evt))) {
  14486. hideDragLine( me );
  14487. if (h == 'h1') {
  14488. h = 'h';
  14489. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  14490. me.execCommand('adaptbywindow');
  14491. } else {
  14492. target = getUETable(target).getPreviewCell(target);
  14493. if (target) {
  14494. var rng = me.selection.getRange();
  14495. rng.selectNodeContents(target).setCursor(true, true)
  14496. }
  14497. }
  14498. }
  14499. if (h == 'h') {
  14500. var ut = getUETable(target),
  14501. table = ut.table,
  14502. cells = getCellsByMoveBorder( target, table, true );
  14503. cells = extractArray( cells, 'left' );
  14504. ut.width = ut.offsetWidth;
  14505. var oldWidth = [],
  14506. newWidth = [];
  14507. utils.each( cells, function( cell ){
  14508. oldWidth.push( cell.offsetWidth );
  14509. } );
  14510. utils.each( cells, function( cell ){
  14511. cell.removeAttribute("width");
  14512. } );
  14513. window.setTimeout( function(){
  14514. //是否允许改变
  14515. var changeable = true;
  14516. utils.each( cells, function( cell, index ){
  14517. var width = cell.offsetWidth;
  14518. if( width > oldWidth[index] ) {
  14519. changeable = false;
  14520. return false;
  14521. }
  14522. newWidth.push( width );
  14523. } );
  14524. var change = changeable ? newWidth : oldWidth;
  14525. utils.each( cells, function( cell, index ){
  14526. cell.width = change[index] - getTabcellSpace();
  14527. } );
  14528. }, 0 );
  14529. // minWidth -= cellMinWidth;
  14530. //
  14531. // table.removeAttribute("width");
  14532. // utils.each(cells, function (cell) {
  14533. // cell.style.width = "";
  14534. // cell.width -= minWidth;
  14535. // });
  14536. }
  14537. }
  14538. }
  14539. }
  14540. function tableClickHander( evt ) {
  14541. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  14542. //trace:3113
  14543. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  14544. utils.each(me.document.getElementsByTagName('table'), function (t) {
  14545. t.ueTable = null;
  14546. });
  14547. startTd = getTargetTd(me, evt);
  14548. if( !startTd ) return;
  14549. var table = domUtils.findParentByTagName(startTd, "table", true);
  14550. ut = getUETable(table);
  14551. ut && ut.clearSelected();
  14552. //判断当前鼠标状态
  14553. if (!onBorder) {
  14554. me.document.body.style.webkitUserSelect = '';
  14555. mousedown = true;
  14556. me.addListener('mouseover', mouseOverEvent);
  14557. } else {
  14558. //边框上的动作处理
  14559. borderActionHandler( evt );
  14560. }
  14561. }
  14562. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  14563. function borderActionHandler( evt ) {
  14564. if ( browser.ie ) {
  14565. evt = reconstruct(evt );
  14566. }
  14567. clearTableDragTimer();
  14568. //是否正在等待resize的缓冲中
  14569. isInResizeBuffer = true;
  14570. tableDragTimer = setTimeout(function(){
  14571. tableBorderDrag( evt );
  14572. }, dblclickTime);
  14573. }
  14574. function extractArray( originArr, key ) {
  14575. var result = [],
  14576. tmp = null;
  14577. for( var i = 0, len = originArr.length; i<len; i++ ) {
  14578. tmp = originArr[ i ][ key ];
  14579. if( tmp ) {
  14580. result.push( tmp );
  14581. }
  14582. }
  14583. return result;
  14584. }
  14585. function clearTableDragTimer() {
  14586. tableDragTimer && clearTimeout(tableDragTimer);
  14587. tableDragTimer = null;
  14588. }
  14589. function reconstruct( obj ) {
  14590. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  14591. newObj = {};
  14592. if( obj ) {
  14593. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  14594. val=obj[ key ];
  14595. val && (newObj[ key ] = val);
  14596. }
  14597. }
  14598. return newObj;
  14599. }
  14600. //边框拖动
  14601. function tableBorderDrag( evt ) {
  14602. isInResizeBuffer = false;
  14603. if( !startTd ) return;
  14604. var state = Math.abs( userActionStatus.x - evt.clientX ) >= Math.abs( userActionStatus.y - evt.clientY ) ? 'h' : 'v';
  14605. // var state = getRelation(startTd, mouseCoords(evt));
  14606. if (/\d/.test(state)) {
  14607. state = state.replace(/\d/, '');
  14608. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  14609. }
  14610. hideDragLine(me);
  14611. getDragLine(me, me.document);
  14612. me.fireEvent('saveScene');
  14613. showDragLineAt(state, startTd);
  14614. mousedown = true;
  14615. //拖动开始
  14616. onDrag = state;
  14617. dragTd = startTd;
  14618. }
  14619. function mouseUpEvent(type, evt) {
  14620. if( isEditorDisabled() ) {
  14621. return ;
  14622. }
  14623. clearTableDragTimer();
  14624. isInResizeBuffer = false;
  14625. if( onBorder ) {
  14626. singleClickState = ++singleClickState % 3;
  14627. userActionStatus = {
  14628. x: evt.clientX,
  14629. y: evt.clientY
  14630. };
  14631. tableResizeTimer = setTimeout(function(){
  14632. singleClickState > 0 && singleClickState--;
  14633. }, dblclickTime );
  14634. if( singleClickState === 2 ) {
  14635. singleClickState = 0;
  14636. tableDbclickHandler(evt);
  14637. return;
  14638. }
  14639. }
  14640. if (evt.button == 2)return;
  14641. var me = this;
  14642. //清除表格上原生跨选问题
  14643. var range = me.selection.getRange(),
  14644. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  14645. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  14646. if (start || end) {
  14647. if (start === end) {
  14648. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  14649. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  14650. if (start !== end) {
  14651. me.selection.clearRange()
  14652. }
  14653. } else {
  14654. me.selection.clearRange()
  14655. }
  14656. }
  14657. mousedown = false;
  14658. me.document.body.style.webkitUserSelect = '';
  14659. //拖拽状态下的mouseUP
  14660. if ( onDrag && dragTd ) {
  14661. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  14662. singleClickState = 0;
  14663. dragLine = me.document.getElementById('ue_tableDragLine');
  14664. var dragTdPos = domUtils.getXY(dragTd),
  14665. dragLinePos = domUtils.getXY(dragLine);
  14666. switch (onDrag) {
  14667. case "h":
  14668. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  14669. break;
  14670. case "v":
  14671. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  14672. break;
  14673. default:
  14674. }
  14675. onDrag = "";
  14676. dragTd = null;
  14677. hideDragLine(me);
  14678. me.fireEvent('saveScene');
  14679. return;
  14680. }
  14681. //正常状态下的mouseup
  14682. if (!startTd) {
  14683. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  14684. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  14685. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  14686. if (me.fireEvent("excludetable", target) === true) return;
  14687. range = new dom.Range(me.document);
  14688. range.setStart(target, 0).setCursor(false, true);
  14689. }
  14690. } else {
  14691. var ut = getUETable(startTd),
  14692. cell = ut ? ut.selectedTds[0] : null;
  14693. if (cell) {
  14694. range = new dom.Range(me.document);
  14695. if (domUtils.isEmptyBlock(cell)) {
  14696. range.setStart(cell, 0).setCursor(false, true);
  14697. } else {
  14698. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  14699. }
  14700. } else {
  14701. range = me.selection.getRange().shrinkBoundary();
  14702. if (!range.collapsed) {
  14703. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  14704. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  14705. //在table里边的不能清除
  14706. if (start && !end || !start && end || start && end && start !== end) {
  14707. range.setCursor(false, true);
  14708. }
  14709. }
  14710. }
  14711. startTd = null;
  14712. me.removeListener('mouseover', mouseOverEvent);
  14713. }
  14714. me._selectionChange(250, evt);
  14715. }
  14716. function mouseOverEvent(type, evt) {
  14717. if( isEditorDisabled() ) {
  14718. return;
  14719. }
  14720. var me = this,
  14721. tar = evt.target || evt.srcElement;
  14722. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  14723. //需要判断两个TD是否位于同一个表格内
  14724. if (startTd && currentTd &&
  14725. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  14726. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  14727. var ut = getUETable(currentTd);
  14728. if (startTd != currentTd) {
  14729. me.document.body.style.webkitUserSelect = 'none';
  14730. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  14731. var range = ut.getCellsRange(startTd, currentTd);
  14732. ut.setSelected(range);
  14733. } else {
  14734. me.document.body.style.webkitUserSelect = '';
  14735. ut.clearSelected();
  14736. }
  14737. }
  14738. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14739. }
  14740. function setCellHeight(cell, height, backHeight) {
  14741. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  14742. tmpHeight = backHeight + height;
  14743. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  14744. if (cell.style.height) cell.style.height = "";
  14745. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  14746. }
  14747. function getWidth(cell) {
  14748. if (!cell)return 0;
  14749. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  14750. }
  14751. function changeColWidth(cell, changeValue) {
  14752. var ut = getUETable(cell);
  14753. if (ut) {
  14754. //根据当前移动的边框获取相关的单元格
  14755. var table = ut.table,
  14756. cells = getCellsByMoveBorder( cell, table );
  14757. table.style.width = "";
  14758. table.removeAttribute("width");
  14759. //修正改变量
  14760. changeValue = correctChangeValue( changeValue, cell, cells );
  14761. if (cell.nextSibling) {
  14762. var i=0;
  14763. utils.each( cells, function( cellGroup ){
  14764. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  14765. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  14766. } );
  14767. } else {
  14768. utils.each( cells, function( cellGroup ){
  14769. cellGroup.left.width -= -changeValue;
  14770. } );
  14771. }
  14772. }
  14773. }
  14774. function isEditorDisabled() {
  14775. return me.body.contentEditable === "false";
  14776. }
  14777. function changeRowHeight(td, changeValue) {
  14778. if (Math.abs(changeValue) < 10) return;
  14779. var ut = getUETable(td);
  14780. if (ut) {
  14781. var cells = ut.getSameEndPosCells(td, "y"),
  14782. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  14783. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  14784. for (var i = 0, cell; cell = cells[i++];) {
  14785. setCellHeight(cell, changeValue, backHeight);
  14786. }
  14787. }
  14788. }
  14789. /**
  14790. * 获取调整单元格大小的相关单元格
  14791. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  14792. */
  14793. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  14794. if( !table ) {
  14795. table = domUtils.findParentByTagName( cell, 'table' );
  14796. }
  14797. if( !table ) {
  14798. return null;
  14799. }
  14800. //获取到该单元格所在行的序列号
  14801. var index = domUtils.getNodeIndex( cell ),
  14802. temp = cell,
  14803. rows = table.rows,
  14804. colIndex = 0;
  14805. while( temp ) {
  14806. //获取到当前单元格在未发生单元格合并时的序列
  14807. if( temp.nodeType === 1 ) {
  14808. colIndex += (temp.colSpan || 1);
  14809. }
  14810. temp = temp.previousSibling;
  14811. }
  14812. temp = null;
  14813. //记录想关的单元格
  14814. var borderCells = [];
  14815. utils.each(rows, function( tabRow ){
  14816. var cells = tabRow.cells,
  14817. currIndex = 0;
  14818. utils.each( cells, function( tabCell ){
  14819. currIndex += (tabCell.colSpan || 1);
  14820. if( currIndex === colIndex ) {
  14821. borderCells.push({
  14822. left: tabCell,
  14823. right: tabCell.nextSibling || null
  14824. });
  14825. return false;
  14826. } else if( currIndex > colIndex ) {
  14827. if( isContainMergeCell ) {
  14828. borderCells.push({
  14829. left: tabCell
  14830. });
  14831. }
  14832. return false;
  14833. }
  14834. } );
  14835. });
  14836. return borderCells;
  14837. }
  14838. /**
  14839. * 通过给定的单元格集合获取最小的单元格width
  14840. */
  14841. function getMinWidthByTableCells( cells ) {
  14842. var minWidth = Number.MAX_VALUE;
  14843. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  14844. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  14845. }
  14846. return minWidth;
  14847. }
  14848. function correctChangeValue( changeValue, relatedCell, cells ) {
  14849. //为单元格的paading预留空间
  14850. changeValue -= getTabcellSpace();
  14851. if( changeValue < 0 ) {
  14852. return 0;
  14853. }
  14854. changeValue -= getTableCellWidth( relatedCell );
  14855. //确定方向
  14856. var direction = changeValue < 0 ? 'left':'right';
  14857. changeValue = Math.abs(changeValue);
  14858. //只关心非最后一个单元格就可以
  14859. utils.each( cells, function( cellGroup ){
  14860. var curCell = cellGroup[direction];
  14861. //为单元格保留最小空间
  14862. if( curCell ) {
  14863. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  14864. }
  14865. } );
  14866. //修正越界
  14867. changeValue = changeValue < 0 ? 0 : changeValue;
  14868. return direction === 'left' ? -changeValue : changeValue;
  14869. }
  14870. function getTableCellWidth( cell ) {
  14871. var width = 0,
  14872. //偏移纠正量
  14873. offset = 0,
  14874. width = cell.offsetWidth - getTabcellSpace();
  14875. //最后一个节点纠正一下
  14876. if( !cell.nextSibling ) {
  14877. width -= getTableCellOffset( cell );
  14878. }
  14879. width = width < 0 ? 0 : width;
  14880. try {
  14881. cell.width = width;
  14882. } catch(e) {
  14883. }
  14884. return width;
  14885. }
  14886. /**
  14887. * 获取单元格所在表格的最末单元格的偏移量
  14888. */
  14889. function getTableCellOffset( cell ) {
  14890. tab = domUtils.findParentByTagName( cell, "table", false);
  14891. if( tab.offsetVal === undefined ) {
  14892. var prev = cell.previousSibling;
  14893. if( prev ) {
  14894. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  14895. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  14896. } else {
  14897. tab.offsetVal = 0;
  14898. }
  14899. }
  14900. return tab.offsetVal;
  14901. }
  14902. function getTabcellSpace() {
  14903. if( UT.tabcellSpace === undefined ) {
  14904. var cell = null,
  14905. tab = me.document.createElement("table"),
  14906. tbody = me.document.createElement("tbody"),
  14907. trow = me.document.createElement("tr"),
  14908. tabcell = me.document.createElement("td"),
  14909. mirror = null;
  14910. tabcell.style.cssText = 'border: 0;';
  14911. tabcell.width = 1;
  14912. trow.appendChild( tabcell );
  14913. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  14914. tbody.appendChild( trow );
  14915. tab.appendChild( tbody );
  14916. tab.style.cssText = "visibility: hidden;";
  14917. me.body.appendChild( tab );
  14918. UT.paddingSpace = tabcell.offsetWidth - 1;
  14919. var tmpTabWidth = tab.offsetWidth;
  14920. tabcell.style.cssText = '';
  14921. mirror.style.cssText = '';
  14922. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  14923. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  14924. me.body.removeChild( tab );
  14925. }
  14926. getTabcellSpace = function(){ return UT.tabcellSpace; };
  14927. return UT.tabcellSpace;
  14928. }
  14929. function getDragLine(editor, doc) {
  14930. if (mousedown)return;
  14931. dragLine = editor.document.createElement("div");
  14932. domUtils.setAttributes(dragLine, {
  14933. id:"ue_tableDragLine",
  14934. unselectable:'on',
  14935. contenteditable:false,
  14936. 'onresizestart':'return false',
  14937. 'ondragstart':'return false',
  14938. 'onselectstart':'return false',
  14939. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  14940. });
  14941. editor.body.appendChild(dragLine);
  14942. }
  14943. function hideDragLine(editor) {
  14944. if (mousedown)return;
  14945. var line;
  14946. while (line = editor.document.getElementById('ue_tableDragLine')) {
  14947. domUtils.remove(line)
  14948. }
  14949. }
  14950. /**
  14951. * 依据state(v|h)在cell位置显示横线
  14952. * @param state
  14953. * @param cell
  14954. */
  14955. function showDragLineAt(state, cell) {
  14956. if (!cell) return;
  14957. var table = domUtils.findParentByTagName(cell, "table"),
  14958. caption = table.getElementsByTagName('caption'),
  14959. width = table.offsetWidth,
  14960. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  14961. tablePos = domUtils.getXY(table),
  14962. cellPos = domUtils.getXY(cell), css;
  14963. switch (state) {
  14964. case "h":
  14965. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  14966. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  14967. break;
  14968. case "v":
  14969. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  14970. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  14971. 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)';
  14972. break;
  14973. default:
  14974. }
  14975. }
  14976. /**
  14977. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  14978. * @param editor
  14979. * @param flag
  14980. */
  14981. function switchBorderColor(editor, flag) {
  14982. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  14983. for (var i = 0, node; node = tableArr[i++];) {
  14984. var td = domUtils.getElementsByTagName(node, "td");
  14985. if (td[0]) {
  14986. if (flag) {
  14987. color = (td[0].style.borderColor).replace(/\s/g, "");
  14988. if (/(#ffffff)|(rgb\(255,f55,255\))/ig.test(color))
  14989. domUtils.addClass(node, "noBorderTable")
  14990. } else {
  14991. domUtils.removeClasses(node, "noBorderTable")
  14992. }
  14993. }
  14994. }
  14995. }
  14996. function getTableWidth(editor, needIEHack, defaultValue) {
  14997. var body = editor.body;
  14998. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  14999. }
  15000. /**
  15001. * 获取当前拖动的单元格
  15002. */
  15003. function getTargetTd(editor, evt) {
  15004. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  15005. dir = null;
  15006. if( !target ) {
  15007. return null;
  15008. }
  15009. dir = getRelation( target, mouseCoords( evt ) );
  15010. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  15011. if( !target ) {
  15012. return null;
  15013. }
  15014. if( dir === 'h1' && target.previousSibling ) {
  15015. var position = domUtils.getXY( target),
  15016. cellWidth = target.offsetWidth;
  15017. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  15018. target = target.previousSibling;
  15019. }
  15020. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  15021. var position = domUtils.getXY( target),
  15022. cellHeight = target.offsetHeight;
  15023. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  15024. target = target.parentNode.previousSibling.firstChild;
  15025. }
  15026. }
  15027. //排除了非td内部以及用于代码高亮部分的td
  15028. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  15029. }
  15030. };
  15031. ///import core
  15032. ///commands 右键菜单
  15033. ///commandsName ContextMenu
  15034. ///commandsTitle 右键菜单
  15035. /**
  15036. * 右键菜单
  15037. * @function
  15038. * @name baidu.editor.plugins.contextmenu
  15039. * @author zhanyi
  15040. */
  15041. UE.plugins['contextmenu'] = function () {
  15042. var me = this,
  15043. lang = me.getLang( "contextMenu" ),
  15044. menu,
  15045. items = me.options.contextMenu || [
  15046. {label:lang['selectall'], cmdName:'selectall'},
  15047. {
  15048. label:lang.deletecode,
  15049. cmdName:'highlightcode',
  15050. icon:'deletehighlightcode'
  15051. },
  15052. {
  15053. label:lang.cleardoc,
  15054. cmdName:'cleardoc',
  15055. exec:function () {
  15056. if ( confirm( lang.confirmclear ) ) {
  15057. this.execCommand( 'cleardoc' );
  15058. }
  15059. }
  15060. },
  15061. '-',
  15062. {
  15063. label:lang.unlink,
  15064. cmdName:'unlink'
  15065. },
  15066. '-',
  15067. {
  15068. group:lang.paragraph,
  15069. icon:'justifyjustify',
  15070. subMenu:[
  15071. {
  15072. label:lang.justifyleft,
  15073. cmdName:'justify',
  15074. value:'left'
  15075. },
  15076. {
  15077. label:lang.justifyright,
  15078. cmdName:'justify',
  15079. value:'right'
  15080. },
  15081. {
  15082. label:lang.justifycenter,
  15083. cmdName:'justify',
  15084. value:'center'
  15085. },
  15086. {
  15087. label:lang.justifyjustify,
  15088. cmdName:'justify',
  15089. value:'justify'
  15090. }
  15091. ]
  15092. },
  15093. '-',
  15094. {
  15095. group:lang.table,
  15096. icon:'table',
  15097. subMenu:[
  15098. {
  15099. label:lang.inserttable,
  15100. cmdName:'inserttable'
  15101. },
  15102. {
  15103. label:lang.deletetable,
  15104. cmdName:'deletetable'
  15105. },
  15106. '-',
  15107. {
  15108. label:lang.deleterow,
  15109. cmdName:'deleterow'
  15110. },
  15111. {
  15112. label:lang.deletecol,
  15113. cmdName:'deletecol'
  15114. },
  15115. {
  15116. label:lang.insertcol,
  15117. cmdName:'insertcol'
  15118. },
  15119. {
  15120. label:lang.insertcolnext,
  15121. cmdName:'insertcolnext'
  15122. },
  15123. {
  15124. label:lang.insertrow,
  15125. cmdName:'insertrow'
  15126. },
  15127. {
  15128. label:lang.insertrownext,
  15129. cmdName:'insertrownext'
  15130. },
  15131. '-',
  15132. {
  15133. label:lang.insertcaption,
  15134. cmdName:'insertcaption'
  15135. },
  15136. {
  15137. label:lang.deletecaption,
  15138. cmdName:'deletecaption'
  15139. },
  15140. {
  15141. label:lang.inserttitle,
  15142. cmdName:'inserttitle'
  15143. },
  15144. {
  15145. label:lang.deletetitle,
  15146. cmdName:'deletetitle'
  15147. },
  15148. '-',
  15149. {
  15150. label:lang.mergecells,
  15151. cmdName:'mergecells'
  15152. },
  15153. {
  15154. label:lang.mergeright,
  15155. cmdName:'mergeright'
  15156. },
  15157. {
  15158. label:lang.mergedown,
  15159. cmdName:'mergedown'
  15160. },
  15161. '-',
  15162. {
  15163. label:lang.splittorows,
  15164. cmdName:'splittorows'
  15165. },
  15166. {
  15167. label:lang.splittocols,
  15168. cmdName:'splittocols'
  15169. },
  15170. {
  15171. label:lang.splittocells,
  15172. cmdName:'splittocells'
  15173. },
  15174. '-',
  15175. {
  15176. label:lang.averageDiseRow,
  15177. cmdName:'averagedistributerow'
  15178. },
  15179. {
  15180. label:lang.averageDisCol,
  15181. cmdName:'averagedistributecol'
  15182. },
  15183. '-',
  15184. {
  15185. label:lang.edittd,
  15186. cmdName:'edittd',
  15187. exec:function () {
  15188. if ( UE.ui['edittd'] ) {
  15189. new UE.ui['edittd']( this );
  15190. }
  15191. this.getDialog('edittd').open();
  15192. }
  15193. },
  15194. {
  15195. label:lang.edittable,
  15196. cmdName:'edittable',
  15197. exec:function () {
  15198. if ( UE.ui['edittable'] ) {
  15199. new UE.ui['edittable']( this );
  15200. }
  15201. this.getDialog('edittable').open();
  15202. }
  15203. }
  15204. ]
  15205. },
  15206. {
  15207. group:lang.tablesort,
  15208. icon:'tablesort',
  15209. subMenu:[
  15210. {
  15211. label:lang.reversecurrent,
  15212. cmdName:'sorttable',
  15213. value:1
  15214. },
  15215. {
  15216. label:lang.orderbyasc,
  15217. cmdName:'sorttable'
  15218. },
  15219. {
  15220. label:lang.reversebyasc,
  15221. cmdName:'sorttable',
  15222. exec:function(){
  15223. this.execCommand("sorttable",function(td1,td2){
  15224. var value1 = td1.innerHTML,
  15225. value2 = td2.innerHTML;
  15226. return value2.localeCompare(value1);
  15227. });
  15228. }
  15229. },
  15230. {
  15231. label:lang.orderbynum,
  15232. cmdName:'sorttable',
  15233. exec:function(){
  15234. this.execCommand("sorttable",function(td1,td2){
  15235. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  15236. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  15237. if(value1) value1 = +value1[0];
  15238. if(value2) value2 = +value2[0];
  15239. return (value1||0) - (value2||0);
  15240. });
  15241. }
  15242. },
  15243. {
  15244. label:lang.reversebynum,
  15245. cmdName:'sorttable',
  15246. exec:function(){
  15247. this.execCommand("sorttable",function(td1,td2){
  15248. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  15249. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  15250. if(value1) value1 = +value1[0];
  15251. if(value2) value2 = +value2[0];
  15252. return (value2||0) - (value1||0);
  15253. });
  15254. }
  15255. }
  15256. ]
  15257. },
  15258. {
  15259. group:lang.borderbk,
  15260. icon:'borderBack',
  15261. subMenu:[
  15262. {
  15263. label:lang.setcolor,
  15264. cmdName:"interlacetable",
  15265. exec:function(){
  15266. this.execCommand("interlacetable");
  15267. }
  15268. },
  15269. {
  15270. label:lang.unsetcolor,
  15271. cmdName:"uninterlacetable",
  15272. exec:function(){
  15273. this.execCommand("uninterlacetable");
  15274. }
  15275. },
  15276. {
  15277. label:lang.setbackground,
  15278. cmdName:"settablebackground",
  15279. exec:function(){
  15280. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  15281. }
  15282. },
  15283. {
  15284. label:lang.unsetbackground,
  15285. cmdName:"cleartablebackground",
  15286. exec:function(){
  15287. this.execCommand("cleartablebackground");
  15288. }
  15289. },
  15290. {
  15291. label:lang.redandblue,
  15292. cmdName:"settablebackground",
  15293. exec:function(){
  15294. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  15295. }
  15296. },
  15297. {
  15298. label:lang.threecolorgradient,
  15299. cmdName:"settablebackground",
  15300. exec:function(){
  15301. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  15302. }
  15303. }
  15304. ]
  15305. },
  15306. {
  15307. group:lang.aligntd,
  15308. icon:'aligntd',
  15309. subMenu:[
  15310. {
  15311. cmdName:'cellalignment',
  15312. value:{align:'left',vAlign:'top'}
  15313. },
  15314. {
  15315. cmdName:'cellalignment',
  15316. value:{align:'center',vAlign:'top'}
  15317. },
  15318. {
  15319. cmdName:'cellalignment',
  15320. value:{align:'right',vAlign:'top'}
  15321. },
  15322. {
  15323. cmdName:'cellalignment',
  15324. value:{align:'left',vAlign:'middle'}
  15325. },
  15326. {
  15327. cmdName:'cellalignment',
  15328. value:{align:'center',vAlign:'middle'}
  15329. },
  15330. {
  15331. cmdName:'cellalignment',
  15332. value:{align:'right',vAlign:'middle'}
  15333. },
  15334. {
  15335. cmdName:'cellalignment',
  15336. value:{align:'left',vAlign:'bottom'}
  15337. },
  15338. {
  15339. cmdName:'cellalignment',
  15340. value:{align:'center',vAlign:'bottom'}
  15341. },
  15342. {
  15343. cmdName:'cellalignment',
  15344. value:{align:'right',vAlign:'bottom'}
  15345. }
  15346. ]
  15347. },
  15348. {
  15349. group:lang.aligntable,
  15350. icon:'aligntable',
  15351. subMenu:[
  15352. {
  15353. cmdName:'tablealignment',
  15354. className: 'left',
  15355. label:lang.tableleft,
  15356. value:"left"
  15357. },
  15358. {
  15359. cmdName:'tablealignment',
  15360. className: 'center',
  15361. label:lang.tablecenter,
  15362. value:"center"
  15363. },
  15364. {
  15365. cmdName:'tablealignment',
  15366. className: 'right',
  15367. label:lang.tableright,
  15368. value:"right"
  15369. }
  15370. ]
  15371. },
  15372. '-',
  15373. {
  15374. label:lang.insertparagraphbefore,
  15375. cmdName:'insertparagraph',
  15376. value:true
  15377. },
  15378. {
  15379. label:lang.insertparagraphafter,
  15380. cmdName:'insertparagraph'
  15381. },
  15382. {
  15383. label:lang['copy'],
  15384. cmdName:'copy',
  15385. exec:function () {
  15386. alert( lang.copymsg );
  15387. },
  15388. query:function () {
  15389. return 0;
  15390. }
  15391. },
  15392. {
  15393. label:lang['paste'],
  15394. cmdName:'paste',
  15395. exec:function () {
  15396. alert( lang.pastemsg );
  15397. },
  15398. query:function () {
  15399. return 0;
  15400. }
  15401. },{
  15402. label:lang['highlightcode'],
  15403. cmdName:'highlightcode',
  15404. exec:function () {
  15405. if ( UE.ui['highlightcode'] ) {
  15406. new UE.ui['highlightcode']( this );
  15407. }
  15408. this.ui._dialogs['highlightcodeDialog'].open();
  15409. }
  15410. }
  15411. ];
  15412. if ( !items.length ) {
  15413. return;
  15414. }
  15415. var uiUtils = UE.ui.uiUtils;
  15416. me.addListener( 'contextmenu', function ( type, evt ) {
  15417. var offset = uiUtils.getViewportOffsetByEvent( evt );
  15418. me.fireEvent( 'beforeselectionchange' );
  15419. if ( menu ) {
  15420. menu.destroy();
  15421. }
  15422. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  15423. var last;
  15424. (function ( item ) {
  15425. if ( item == '-' ) {
  15426. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  15427. contextItems.push( '-' );
  15428. }
  15429. } else if ( item.hasOwnProperty( "group" ) ) {
  15430. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  15431. (function ( subItem ) {
  15432. if ( subItem == '-' ) {
  15433. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  15434. subMenu.push( '-' );
  15435. }else{
  15436. subMenu.splice(subMenu.length-1);
  15437. }
  15438. } else {
  15439. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  15440. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  15441. subMenu.push( {
  15442. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  15443. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  15444. onclick:subItem.exec ? function () {
  15445. subItem.exec.call( me );
  15446. } : function () {
  15447. me.execCommand( subItem.cmdName, subItem.value );
  15448. }
  15449. } );
  15450. }
  15451. }
  15452. })( cj );
  15453. }
  15454. if ( subMenu.length ) {
  15455. function getLabel(){
  15456. switch (item.icon){
  15457. case "table":
  15458. return me.getLang( "contextMenu.table" );
  15459. case "justifyjustify":
  15460. return me.getLang( "contextMenu.paragraph" );
  15461. case "aligntd":
  15462. return me.getLang("contextMenu.aligntd");
  15463. case "aligntable":
  15464. return me.getLang("contextMenu.aligntable");
  15465. case "tablesort":
  15466. return lang.tablesort;
  15467. case "borderBack":
  15468. return lang.borderbk;
  15469. default :
  15470. return '';
  15471. }
  15472. }
  15473. contextItems.push( {
  15474. //todo 修正成自动获取方式
  15475. 'label':getLabel(),
  15476. className:'edui-for-' + item.icon,
  15477. 'subMenu':{
  15478. items:subMenu,
  15479. editor:me
  15480. }
  15481. } );
  15482. }
  15483. } else {
  15484. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  15485. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  15486. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  15487. //highlight todo
  15488. if ( item.cmdName == 'highlightcode' ) {
  15489. if(me.queryCommandState( item.cmdName ) == 1 && item.icon != 'deletehighlightcode'){
  15490. return;
  15491. }
  15492. if(me.queryCommandState( item.cmdName ) != 1 && item.icon == 'deletehighlightcode'){
  15493. return;
  15494. }
  15495. }
  15496. contextItems.push( {
  15497. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  15498. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  15499. onclick:item.exec ? function () {
  15500. item.exec.call( me );
  15501. } : function () {
  15502. me.execCommand( item.cmdName, item.value );
  15503. }
  15504. } );
  15505. }
  15506. }
  15507. })( ti );
  15508. }
  15509. if ( contextItems[contextItems.length - 1] == '-' ) {
  15510. contextItems.pop();
  15511. }
  15512. menu = new UE.ui.Menu( {
  15513. items:contextItems,
  15514. className:"edui-contextmenu",
  15515. editor:me
  15516. } );
  15517. menu.render();
  15518. menu.showAt( offset );
  15519. me.fireEvent("aftershowcontextmenu",menu);
  15520. domUtils.preventDefault( evt );
  15521. if ( browser.ie ) {
  15522. var ieRange;
  15523. try {
  15524. ieRange = me.selection.getNative().createRange();
  15525. } catch ( e ) {
  15526. return;
  15527. }
  15528. if ( ieRange.item ) {
  15529. var range = new dom.Range( me.document );
  15530. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  15531. }
  15532. }
  15533. } );
  15534. };
  15535. ///import core
  15536. ///commands 弹出菜单
  15537. // commandsName popupmenu
  15538. ///commandsTitle 弹出菜单
  15539. /**
  15540. * 弹出菜单
  15541. * @function
  15542. * @name baidu.editor.plugins.popupmenu
  15543. * @author xuheng
  15544. */
  15545. UE.plugins['shortcutmenu'] = function () {
  15546. var me = this,
  15547. menu,
  15548. items = me.options.shortcutMenu || [];
  15549. if (!items.length) {
  15550. return;
  15551. }
  15552. me.addListener ('contextmenu mouseup' , function (type , e) {
  15553. var me = this,
  15554. customEvt = {
  15555. type : type ,
  15556. target : e.target || e.srcElement ,
  15557. screenX : e.screenX ,
  15558. screenY : e.screenY ,
  15559. clientX : e.clientX ,
  15560. clientY : e.clientY
  15561. };
  15562. setTimeout (function () {
  15563. var rng = me.selection.getRange ();
  15564. if (rng.collapsed === false || type == "contextmenu") {
  15565. if (!menu) {
  15566. menu = new baidu.editor.ui.ShortCutMenu ({
  15567. editor : me ,
  15568. items : items ,
  15569. theme : me.options.theme ,
  15570. className : 'edui-shortcutmenu'
  15571. });
  15572. menu.render ();
  15573. me.fireEvent ("afterrendershortcutmenu" , menu);
  15574. }
  15575. menu.show (customEvt , !!UE.plugins['contextmenu']);
  15576. }
  15577. });
  15578. if (type == 'contextmenu') {
  15579. domUtils.preventDefault (e);
  15580. if (browser.ie) {
  15581. var ieRange;
  15582. try {
  15583. ieRange = me.selection.getNative ().createRange ();
  15584. } catch (e) {
  15585. return;
  15586. }
  15587. if (ieRange.item) {
  15588. var range = new dom.Range (me.document);
  15589. range.selectNode (ieRange.item (0)).select (true , true);
  15590. }
  15591. }
  15592. }
  15593. if (type == "keydown") {
  15594. menu && !menu.isHidden && menu.hide ();
  15595. }
  15596. });
  15597. me.addListener ('keydown' , function (type) {
  15598. if (type == "keydown") {
  15599. menu && !menu.isHidden && menu.hide ();
  15600. }
  15601. });
  15602. };
  15603. ///import core
  15604. ///commands 加粗,斜体,上标,下标
  15605. ///commandsName Bold,Italic,Subscript,Superscript
  15606. ///commandsTitle 加粗,加斜,下标,上标
  15607. /**
  15608. * b u i等基础功能实现
  15609. * @function
  15610. * @name baidu.editor.execCommands
  15611. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  15612. */
  15613. UE.plugins['basestyle'] = function(){
  15614. var basestyles = {
  15615. 'bold':['strong','b'],
  15616. 'italic':['em','i'],
  15617. 'subscript':['sub'],
  15618. 'superscript':['sup']
  15619. },
  15620. getObj = function(editor,tagNames){
  15621. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  15622. },
  15623. me = this;
  15624. //添加快捷键
  15625. me.addshortcutkey({
  15626. "Bold" : "ctrl+66",//^B
  15627. "Italic" : "ctrl+73", //^I
  15628. "Underline" : "ctrl+85"//^U
  15629. });
  15630. me.addInputRule(function(root){
  15631. utils.each(root.getNodesByTagName('b i'),function(node){
  15632. switch (node.tagName){
  15633. case 'b':
  15634. node.tagName = 'strong';
  15635. break;
  15636. case 'i':
  15637. node.tagName = 'em';
  15638. }
  15639. });
  15640. });
  15641. for ( var style in basestyles ) {
  15642. (function( cmd, tagNames ) {
  15643. me.commands[cmd] = {
  15644. execCommand : function( cmdName ) {
  15645. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  15646. if ( range.collapsed ) {
  15647. if ( obj ) {
  15648. var tmpText = me.document.createTextNode('');
  15649. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  15650. range.setStartBefore(tmpText);
  15651. domUtils.remove(tmpText);
  15652. } else {
  15653. var tmpNode = range.document.createElement( tagNames[0] );
  15654. if(cmdName == 'superscript' || cmdName == 'subscript'){
  15655. tmpText = me.document.createTextNode('');
  15656. range.insertNode(tmpText)
  15657. .removeInlineStyle(['sub','sup'])
  15658. .setStartBefore(tmpText)
  15659. .collapse(true);
  15660. }
  15661. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  15662. }
  15663. range.collapse( true );
  15664. } else {
  15665. if(cmdName == 'superscript' || cmdName == 'subscript'){
  15666. if(!obj || obj.tagName.toLowerCase() != cmdName){
  15667. range.removeInlineStyle(['sub','sup']);
  15668. }
  15669. }
  15670. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  15671. }
  15672. range.select();
  15673. },
  15674. queryCommandState : function() {
  15675. return getObj(this,tagNames) ? 1 : 0;
  15676. }
  15677. };
  15678. })( style, basestyles[style] );
  15679. }
  15680. };
  15681. ///import core
  15682. ///commands 选区路径
  15683. ///commandsName ElementPath,elementPathEnabled
  15684. ///commandsTitle 选区路径
  15685. /**
  15686. * 选区路径
  15687. * @function
  15688. * @name baidu.editor.execCommand
  15689. * @param {String} cmdName elementpath选区路径
  15690. */
  15691. UE.plugins['elementpath'] = function(){
  15692. var currentLevel,
  15693. tagNames,
  15694. me = this;
  15695. me.setOpt('elementPathEnabled',true);
  15696. if(!me.options.elementPathEnabled){
  15697. return;
  15698. }
  15699. me.commands['elementpath'] = {
  15700. execCommand : function( cmdName, level ) {
  15701. var start = tagNames[level],
  15702. range = me.selection.getRange();
  15703. currentLevel = level*1;
  15704. range.selectNode(start).select();
  15705. },
  15706. queryCommandValue : function() {
  15707. //产生一个副本,不能修改原来的startElementPath;
  15708. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  15709. names = [];
  15710. tagNames = parents;
  15711. for(var i=0,ci;ci=parents[i];i++){
  15712. if(ci.nodeType == 3) {
  15713. continue;
  15714. }
  15715. var name = ci.tagName.toLowerCase();
  15716. if(name == 'img' && ci.getAttribute('anchorname')){
  15717. name = 'anchor';
  15718. }
  15719. names[i] = name;
  15720. if(currentLevel == i){
  15721. currentLevel = -1;
  15722. break;
  15723. }
  15724. }
  15725. return names;
  15726. }
  15727. };
  15728. };
  15729. ///import core
  15730. ///import plugins\removeformat.js
  15731. ///commands 格式刷
  15732. ///commandsName FormatMatch
  15733. ///commandsTitle 格式刷
  15734. /**
  15735. * 格式刷,只格式inline的
  15736. * @function
  15737. * @name baidu.editor.execCommand
  15738. * @param {String} cmdName formatmatch执行格式刷
  15739. */
  15740. UE.plugins['formatmatch'] = function(){
  15741. var me = this,
  15742. list = [],img,
  15743. flag = 0;
  15744. me.addListener('reset',function(){
  15745. list = [];
  15746. flag = 0;
  15747. });
  15748. function addList(type,evt){
  15749. if(browser.webkit){
  15750. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  15751. }
  15752. function addFormat(range){
  15753. if(text){
  15754. range.selectNode(text);
  15755. }
  15756. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  15757. }
  15758. me.undoManger && me.undoManger.save();
  15759. var range = me.selection.getRange(),
  15760. imgT = target || range.getClosedNode();
  15761. if(img && imgT && imgT.tagName == 'IMG'){
  15762. //trace:964
  15763. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  15764. img = null;
  15765. }else{
  15766. if(!img){
  15767. var collapsed = range.collapsed;
  15768. if(collapsed){
  15769. var text = me.document.createTextNode('match');
  15770. range.insertNode(text).select();
  15771. }
  15772. me.__hasEnterExecCommand = true;
  15773. //不能把block上的属性干掉
  15774. //trace:1553
  15775. var removeFormatAttributes = me.options.removeFormatAttributes;
  15776. me.options.removeFormatAttributes = '';
  15777. me.execCommand('removeformat');
  15778. me.options.removeFormatAttributes = removeFormatAttributes;
  15779. me.__hasEnterExecCommand = false;
  15780. //trace:969
  15781. range = me.selection.getRange();
  15782. if(list.length){
  15783. addFormat(range);
  15784. }
  15785. if(text){
  15786. range.setStartBefore(text).collapse(true);
  15787. }
  15788. range.select();
  15789. text && domUtils.remove(text);
  15790. }
  15791. }
  15792. me.undoManger && me.undoManger.save();
  15793. me.removeListener('mouseup',addList);
  15794. flag = 0;
  15795. }
  15796. me.commands['formatmatch'] = {
  15797. execCommand : function( cmdName ) {
  15798. if(flag){
  15799. flag = 0;
  15800. list = [];
  15801. me.removeListener('mouseup',addList);
  15802. return;
  15803. }
  15804. var range = me.selection.getRange();
  15805. img = range.getClosedNode();
  15806. if(!img || img.tagName != 'IMG'){
  15807. range.collapse(true).shrinkBoundary();
  15808. var start = range.startContainer;
  15809. list = domUtils.findParents(start,true,function(node){
  15810. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  15811. });
  15812. //a不能加入格式刷, 并且克隆节点
  15813. for(var i=0,ci;ci=list[i];i++){
  15814. if(ci.tagName == 'A'){
  15815. list.splice(i,1);
  15816. break;
  15817. }
  15818. }
  15819. }
  15820. me.addListener('mouseup',addList);
  15821. flag = 1;
  15822. },
  15823. queryCommandState : function() {
  15824. return flag;
  15825. },
  15826. notNeedUndo : 1
  15827. };
  15828. };
  15829. ///import core
  15830. ///commands 查找替换
  15831. ///commandsName SearchReplace
  15832. ///commandsTitle 查询替换
  15833. ///commandsDialog dialogs\searchreplace
  15834. /**
  15835. * @description 查找替换
  15836. * @author zhanyi
  15837. */
  15838. UE.plugins['searchreplace'] = function(){
  15839. var currentRange,
  15840. first,
  15841. me = this;
  15842. me.addListener('reset',function(){
  15843. currentRange = null;
  15844. first = null;
  15845. });
  15846. me.commands['searchreplace'] = {
  15847. execCommand : function(cmdName,opt){
  15848. var me = this,
  15849. sel = me.selection,
  15850. range,
  15851. nativeRange,
  15852. num = 0,
  15853. opt = utils.extend(opt,{
  15854. all : false,
  15855. casesensitive : false,
  15856. dir : 1
  15857. },true);
  15858. var searchStr = opt.searchStr;
  15859. if(browser.ie){
  15860. me.focus();
  15861. while(1){
  15862. var tmpRange;
  15863. nativeRange = me.document.selection.createRange();
  15864. tmpRange = nativeRange.duplicate();
  15865. tmpRange.moveToElementText(me.document.body);
  15866. if(opt.all){
  15867. first = 0;
  15868. opt.dir = 1;
  15869. if(currentRange){
  15870. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',currentRange);
  15871. }else{
  15872. tmpRange.moveToElementText(me.document.body);
  15873. }
  15874. }else{
  15875. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',nativeRange);
  15876. if(opt.hasOwnProperty("replaceStr")){
  15877. tmpRange.setEndPoint(opt.dir == -1 ? 'StartToEnd' : 'EndToStart',nativeRange);
  15878. }
  15879. }
  15880. nativeRange = tmpRange.duplicate();
  15881. if(/^\/[^/]+\/\w*$/.test(opt.searchStr)){
  15882. var str = tmpRange.text,
  15883. reg = new RegExp(opt.searchStr.replace(/^\/|\/\w*$/g,''),'g' + (opt.casesensitive ? '':'i'));
  15884. var match = str.match(reg);
  15885. if(match && match.length){
  15886. searchStr = opt.dir < 0 ? match[match.length -1] : match[0];
  15887. }else{
  15888. currentRange = null;
  15889. return num;
  15890. }
  15891. }
  15892. if(!tmpRange.findText(searchStr,opt.dir,opt.casesensitive ? 4 : 0)){
  15893. currentRange = null;
  15894. tmpRange = me.document.selection.createRange();
  15895. tmpRange.scrollIntoView();
  15896. currentRange = null;
  15897. return num;
  15898. }
  15899. tmpRange.select();
  15900. //替换
  15901. if(opt.hasOwnProperty("replaceStr")){
  15902. range = sel.getRange();
  15903. range.deleteContents().insertNode(range.document.createTextNode(opt.replaceStr)).select();
  15904. currentRange = sel.getNative().createRange();
  15905. }
  15906. num++;
  15907. if(!opt.all){
  15908. break;
  15909. }
  15910. }
  15911. }else{
  15912. var w = me.window,nativeSel = sel.getNative();
  15913. while(1){
  15914. if(opt.all){
  15915. if(currentRange){
  15916. currentRange.collapse(false);
  15917. nativeRange = currentRange;
  15918. }else{
  15919. nativeRange = me.document.createRange();
  15920. nativeRange.setStart(me.document.body,0);
  15921. nativeRange.collapse(true);
  15922. }
  15923. nativeSel.removeAllRanges();
  15924. nativeSel.addRange( nativeRange );
  15925. first = 0;
  15926. opt.dir = 1;
  15927. }else{
  15928. //safari弹出层,原生已经找不到range了,所以需要先选回来,再取原生
  15929. if(browser.safari){
  15930. me.selection.getRange().select();
  15931. }
  15932. var nativeSel = w.getSelection();
  15933. if(!nativeSel.rangeCount){
  15934. nativeRange = currentRange || me._bakNativeRange;
  15935. }else{
  15936. nativeRange = nativeSel.getRangeAt(0);
  15937. }
  15938. if(opt.hasOwnProperty("replaceStr")){
  15939. nativeRange.collapse(opt.dir == 1 ? true : false);
  15940. }
  15941. }
  15942. //如果是第一次并且海选中了内容那就要清除,为find做准备
  15943. if(!first){
  15944. nativeRange.collapse( opt.dir <0 ? true : false);
  15945. nativeSel.removeAllRanges();
  15946. nativeSel.addRange( nativeRange );
  15947. }else{
  15948. nativeSel.removeAllRanges();
  15949. }
  15950. //是正则查找
  15951. if(/^\/[^/]+\/\w*$/.test(opt.searchStr)){
  15952. var tmpRange = nativeRange.cloneRange();
  15953. //向前查找
  15954. if(opt.dir < 0 ){
  15955. nativeRange.collapse(true);
  15956. nativeRange.setStart(me.body,0);
  15957. }else{
  15958. nativeRange.setEnd(me.body,me.body.childNodes.length);
  15959. }
  15960. var str = nativeRange + '',
  15961. reg = new RegExp(opt.searchStr.replace(/^\/|\/\w*$/g,''),'g' + (opt.casesensitive ? '':'i'));
  15962. var match = str.match(reg);
  15963. if(match && match.length){
  15964. searchStr = opt.dir < 0 ? match[match.length -1] : match[0];
  15965. }else{
  15966. currentRange = null;
  15967. return num;
  15968. }
  15969. nativeSel.removeAllRanges();
  15970. nativeRange = tmpRange;
  15971. nativeSel.addRange(nativeRange);
  15972. }
  15973. if(!w.find(searchStr,opt.casesensitive,opt.dir < 0 ? true : false) ) {
  15974. currentRange = null;
  15975. nativeSel.removeAllRanges();
  15976. return num;
  15977. }
  15978. first = 0;
  15979. range = w.getSelection().getRangeAt(0);
  15980. if(!range.collapsed){
  15981. if(opt.hasOwnProperty("replaceStr")){
  15982. range.deleteContents();
  15983. var text = w.document.createTextNode(opt.replaceStr);
  15984. range.insertNode(text);
  15985. range.selectNode(text);
  15986. nativeSel.addRange(range);
  15987. }
  15988. currentRange = range.cloneRange();
  15989. }
  15990. num++;
  15991. if(!opt.all){
  15992. break;
  15993. }
  15994. }
  15995. }
  15996. return true;
  15997. }
  15998. };
  15999. };
  16000. ///import core
  16001. ///commands 自定义样式
  16002. ///commandsName CustomStyle
  16003. ///commandsTitle 自定义样式
  16004. UE.plugins['customstyle'] = function() {
  16005. var me = this;
  16006. me.setOpt({ 'customstyle':[
  16007. {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;'},
  16008. {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;'},
  16009. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  16010. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  16011. ]});
  16012. me.commands['customstyle'] = {
  16013. execCommand : function(cmdName, obj) {
  16014. var me = this,
  16015. tagName = obj.tag,
  16016. node = domUtils.findParent(me.selection.getStart(), function(node) {
  16017. return node.getAttribute('label');
  16018. }, true),
  16019. range,bk,tmpObj = {};
  16020. for (var p in obj) {
  16021. if(obj[p]!==undefined)
  16022. tmpObj[p] = obj[p];
  16023. }
  16024. delete tmpObj.tag;
  16025. if (node && node.getAttribute('label') == obj.label) {
  16026. range = this.selection.getRange();
  16027. bk = range.createBookmark();
  16028. if (range.collapsed) {
  16029. //trace:1732 删掉自定义标签,要有p来回填站位
  16030. if(dtd.$block[node.tagName]){
  16031. var fillNode = me.document.createElement('p');
  16032. domUtils.moveChild(node, fillNode);
  16033. node.parentNode.insertBefore(fillNode, node);
  16034. domUtils.remove(node);
  16035. }else{
  16036. domUtils.remove(node,true);
  16037. }
  16038. } else {
  16039. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  16040. nodes = domUtils.getElementsByTagName(common, tagName);
  16041. if(new RegExp(tagName,'i').test(common.tagName)){
  16042. nodes.push(common);
  16043. }
  16044. for (var i = 0,ni; ni = nodes[i++];) {
  16045. if (ni.getAttribute('label') == obj.label) {
  16046. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  16047. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  16048. &&
  16049. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  16050. )
  16051. if (dtd.$block[tagName]) {
  16052. var fillNode = me.document.createElement('p');
  16053. domUtils.moveChild(ni, fillNode);
  16054. ni.parentNode.insertBefore(fillNode, ni);
  16055. }
  16056. domUtils.remove(ni, true);
  16057. }
  16058. }
  16059. node = domUtils.findParent(common, function(node) {
  16060. return node.getAttribute('label') == obj.label;
  16061. }, true);
  16062. if (node) {
  16063. domUtils.remove(node, true);
  16064. }
  16065. }
  16066. range.moveToBookmark(bk).select();
  16067. } else {
  16068. if (dtd.$block[tagName]) {
  16069. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  16070. range = me.selection.getRange();
  16071. if (!range.collapsed) {
  16072. range.collapse();
  16073. node = domUtils.findParent(me.selection.getStart(), function(node) {
  16074. return node.getAttribute('label') == obj.label;
  16075. }, true);
  16076. var pNode = me.document.createElement('p');
  16077. domUtils.insertAfter(node, pNode);
  16078. domUtils.fillNode(me.document, pNode);
  16079. range.setStart(pNode, 0).setCursor();
  16080. }
  16081. } else {
  16082. range = me.selection.getRange();
  16083. if (range.collapsed) {
  16084. node = me.document.createElement(tagName);
  16085. domUtils.setAttributes(node, tmpObj);
  16086. range.insertNode(node).setStart(node, 0).setCursor();
  16087. return;
  16088. }
  16089. bk = range.createBookmark();
  16090. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  16091. }
  16092. }
  16093. },
  16094. queryCommandValue : function() {
  16095. var parent = domUtils.filterNodeList(
  16096. this.selection.getStartElementPath(),
  16097. function(node){return node.getAttribute('label')}
  16098. );
  16099. return parent ? parent.getAttribute('label') : '';
  16100. }
  16101. };
  16102. //当去掉customstyle是,如果是块元素,用p代替
  16103. me.addListener('keyup', function(type, evt) {
  16104. var keyCode = evt.keyCode || evt.which;
  16105. if (keyCode == 32 || keyCode == 13) {
  16106. var range = me.selection.getRange();
  16107. if (range.collapsed) {
  16108. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  16109. return node.getAttribute('label');
  16110. }, true);
  16111. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  16112. var p = me.document.createElement('p');
  16113. domUtils.insertAfter(node, p);
  16114. domUtils.fillNode(me.document, p);
  16115. domUtils.remove(node);
  16116. range.setStart(p, 0).setCursor();
  16117. }
  16118. }
  16119. }
  16120. });
  16121. };
  16122. ///import core
  16123. ///commands 远程图片抓取
  16124. ///commandsName catchRemoteImage,catchremoteimageenable
  16125. ///commandsTitle 远程图片抓取
  16126. /**
  16127. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  16128. *
  16129. */
  16130. UE.plugins['catchremoteimage'] = function () {
  16131. if (this.options.catchRemoteImageEnable===false){
  16132. return;
  16133. }
  16134. var me = this;
  16135. this.setOpt({
  16136. localDomain:["127.0.0.1","localhost","img.baidu.com"],
  16137. separater:'ue_separate_ue',
  16138. catchFieldName:"upfile",
  16139. catchRemoteImageEnable:true
  16140. });
  16141. var ajax = UE.ajax,
  16142. localDomain = me.options.localDomain ,
  16143. catcherUrl = me.options.catcherUrl,
  16144. separater = me.options.separater;
  16145. function catchremoteimage(imgs, callbacks) {
  16146. var submitStr = imgs.join(separater);
  16147. var tmpOption = {
  16148. timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  16149. onsuccess:callbacks["success"],
  16150. onerror:callbacks["error"]
  16151. };
  16152. tmpOption[me.options.catchFieldName] = submitStr;
  16153. ajax.request(catcherUrl, tmpOption);
  16154. }
  16155. me.addListener("afterpaste", function () {
  16156. me.fireEvent("catchRemoteImage");
  16157. });
  16158. me.addListener("catchRemoteImage", function () {
  16159. var remoteImages = [];
  16160. var imgs = domUtils.getElementsByTagName(me.document, "img");
  16161. var test = function (src,urls) {
  16162. for (var j = 0, url; url = urls[j++];) {
  16163. if (src.indexOf(url) !== -1) {
  16164. return true;
  16165. }
  16166. }
  16167. return false;
  16168. };
  16169. for (var i = 0, ci; ci = imgs[i++];) {
  16170. if (ci.getAttribute("word_img")){
  16171. continue;
  16172. }
  16173. var src = ci.getAttribute("_src") || ci.src || "";
  16174. if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) {
  16175. remoteImages.push(src);
  16176. }
  16177. }
  16178. if (remoteImages.length) {
  16179. catchremoteimage(remoteImages, {
  16180. //成功抓取
  16181. success:function (xhr) {
  16182. try {
  16183. var info = eval("(" + xhr.responseText + ")");
  16184. } catch (e) {
  16185. return;
  16186. }
  16187. var srcUrls = info.srcUrl.split(separater),
  16188. urls = info.url.split(separater);
  16189. for (var i = 0, ci; ci = imgs[i++];) {
  16190. var src = ci.getAttribute("_src") || ci.src || "";
  16191. for (var j = 0, cj; cj = srcUrls[j++];) {
  16192. var url = urls[j - 1];
  16193. if (src == cj && url != "error") { //抓取失败时不做替换处理
  16194. //地址修正
  16195. var newSrc = me.options.catcherPath + url;
  16196. domUtils.setAttributes(ci, {
  16197. "src":newSrc,
  16198. "_src":newSrc
  16199. });
  16200. break;
  16201. }
  16202. }
  16203. }
  16204. me.fireEvent('catchremotesuccess')
  16205. },
  16206. //回调失败,本次请求超时
  16207. error:function () {
  16208. me.fireEvent("catchremoteerror");
  16209. }
  16210. });
  16211. }
  16212. });
  16213. };
  16214. ///import core
  16215. ///import plugins\inserthtml.js
  16216. ///import plugins\image.js
  16217. ///commandsName snapscreen
  16218. ///commandsTitle 截屏
  16219. /**
  16220. * 截屏插件
  16221. */
  16222. UE.plugins['snapscreen'] = function(){
  16223. var me = this,
  16224. doc,
  16225. snapplugin;
  16226. me.setOpt({
  16227. snapscreenServerPort: location.port //屏幕截图的server端端口
  16228. ,snapscreenImgAlign: '' //截图的图片默认的排版方式
  16229. ,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
  16230. });
  16231. me.commands['snapscreen'] = {
  16232. execCommand: function(){
  16233. var me = this,lang = me.getLang("snapScreen_plugin");
  16234. if(!snapplugin){
  16235. var container = me.container;
  16236. doc = container.ownerDocument || container.document;
  16237. snapplugin = doc.createElement("object");
  16238. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  16239. return;
  16240. }
  16241. snapplugin.style.cssText = "position:absolute;left:-9999px;";
  16242. snapplugin.setAttribute("width","0");
  16243. snapplugin.setAttribute("height","0");
  16244. container.appendChild(snapplugin);
  16245. }
  16246. var editorOptions = me.options;
  16247. var onSuccess = function(rs){
  16248. try{
  16249. rs = eval("("+ rs +")");
  16250. }catch(e){
  16251. alert(lang.callBackErrorMsg);
  16252. return;
  16253. }
  16254. if(rs.state != 'SUCCESS'){
  16255. alert(rs.state);
  16256. return;
  16257. }
  16258. me.execCommand('insertimage', {
  16259. src: editorOptions.snapscreenPath + rs.url,
  16260. floatStyle: editorOptions.snapscreenImgAlign,
  16261. _src:editorOptions.snapscreenPath + rs.url
  16262. });
  16263. };
  16264. var onStartUpload = function(){
  16265. //开始截图上传
  16266. };
  16267. var onError = function(){
  16268. alert(lang.uploadErrorMsg);
  16269. };
  16270. try{
  16271. var port = editorOptions.snapscreenServerPort + '';
  16272. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.split( editorOptions.snapscreenHost );
  16273. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl[1] || editorOptions.snapscreenServerUrl[0];
  16274. if( editorOptions.snapscreenServerUrl.indexOf(":"+port) === 0 ) {
  16275. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.substring( port.length+1 );
  16276. }
  16277. var ret =snapplugin.saveSnapshot(editorOptions.snapscreenHost, editorOptions.snapscreenServerUrl, port);
  16278. onSuccess(ret);
  16279. }catch(e){
  16280. me.ui._dialogs['snapscreenDialog'].open();
  16281. }
  16282. }
  16283. };
  16284. }
  16285. ///import core
  16286. ///commands 插入空行
  16287. ///commandsName insertparagraph
  16288. ///commandsTitle 插入空行
  16289. /**
  16290. * 插入空行
  16291. * @function
  16292. * @name baidu.editor.execCommand
  16293. * @param {String} cmdName insertparagraph
  16294. */
  16295. UE.commands['insertparagraph'] = {
  16296. execCommand : function( cmdName,front) {
  16297. var me = this,
  16298. range = me.selection.getRange(),
  16299. start = range.startContainer,tmpNode;
  16300. while(start ){
  16301. if(domUtils.isBody(start)){
  16302. break;
  16303. }
  16304. tmpNode = start;
  16305. start = start.parentNode;
  16306. }
  16307. if(tmpNode){
  16308. var p = me.document.createElement('p');
  16309. if(front){
  16310. tmpNode.parentNode.insertBefore(p,tmpNode)
  16311. }else{
  16312. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  16313. }
  16314. domUtils.fillNode(me.document,p);
  16315. range.setStart(p,0).setCursor(false,true);
  16316. }
  16317. }
  16318. };
  16319. ///import core
  16320. ///import plugins/inserthtml.js
  16321. ///commands 百度应用
  16322. ///commandsName webapp
  16323. ///commandsTitle 百度应用
  16324. ///commandsDialog dialogs\webapp
  16325. UE.plugins['webapp'] = function () {
  16326. var me = this;
  16327. function createInsertStr( obj, toIframe, addParagraph ) {
  16328. return !toIframe ?
  16329. (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  16330. ' 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 + '" />' +
  16331. (addParagraph ? '</p>' : '')
  16332. :
  16333. '<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>';
  16334. }
  16335. function switchImgAndIframe( img2frame ) {
  16336. var tmpdiv,
  16337. nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  16338. for ( var i = 0, node; node = nodes[i++]; ) {
  16339. if ( node.className != "edui-faked-webapp" ){
  16340. continue;
  16341. }
  16342. tmpdiv = me.document.createElement( "div" );
  16343. 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 );
  16344. node.parentNode.replaceChild( tmpdiv.firstChild, node );
  16345. }
  16346. }
  16347. me.addListener( "beforegetcontent", function () {
  16348. switchImgAndIframe( true );
  16349. } );
  16350. me.addListener( 'aftersetcontent', function () {
  16351. switchImgAndIframe( false );
  16352. } );
  16353. me.addListener( 'aftergetcontent', function ( cmdName ) {
  16354. if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  16355. return;
  16356. }
  16357. switchImgAndIframe( false );
  16358. } );
  16359. me.commands['webapp'] = {
  16360. execCommand:function ( cmd, obj ) {
  16361. me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  16362. }
  16363. };
  16364. };
  16365. ///import core
  16366. ///import plugins\inserthtml.js
  16367. ///import plugins\cleardoc.js
  16368. ///commands 模板
  16369. ///commandsName template
  16370. ///commandsTitle 模板
  16371. ///commandsDialog dialogs\template
  16372. UE.plugins['template'] = function () {
  16373. UE.commands['template'] = {
  16374. execCommand:function (cmd, obj) {
  16375. obj.html && this.execCommand("inserthtml", obj.html);
  16376. }
  16377. };
  16378. this.addListener("click", function (type, evt) {
  16379. var el = evt.target || evt.srcElement,
  16380. range = this.selection.getRange();
  16381. var tnode = domUtils.findParent(el, function (node) {
  16382. if (node.className && domUtils.hasClass(node, "ue_t")) {
  16383. return node;
  16384. }
  16385. }, true);
  16386. tnode && range.selectNode(tnode).shrinkBoundary().select();
  16387. });
  16388. this.addListener("keydown", function (type, evt) {
  16389. var range = this.selection.getRange();
  16390. if (!range.collapsed) {
  16391. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  16392. var tnode = domUtils.findParent(range.startContainer, function (node) {
  16393. if (node.className && domUtils.hasClass(node, "ue_t")) {
  16394. return node;
  16395. }
  16396. }, true);
  16397. if (tnode) {
  16398. domUtils.removeClasses(tnode, ["ue_t"]);
  16399. }
  16400. }
  16401. }
  16402. });
  16403. };
  16404. ///import core
  16405. ///import plugins/inserthtml.js
  16406. ///commands 音乐
  16407. ///commandsName Music
  16408. ///commandsTitle 插入音乐
  16409. ///commandsDialog dialogs\music
  16410. UE.plugins['music'] = function () {
  16411. var me = this,
  16412. div;
  16413. /**
  16414. * 创建插入音乐字符窜
  16415. * @param url 音乐地址
  16416. * @param width 音乐宽度
  16417. * @param height 音乐高度
  16418. * @param align 阴雨对齐
  16419. * @param toEmbed 是否以flash代替显示
  16420. * @param addParagraph 是否需要添加P标签
  16421. */
  16422. function creatInsertStr(url,width,height,align,toEmbed,addParagraph){
  16423. return !toEmbed ?
  16424. (addParagraph? ('<p '+ (align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') +
  16425. '<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  16426. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />' +
  16427. (addParagraph?'</p>':'')
  16428. :
  16429. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16430. ' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' +
  16431. ( align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) +
  16432. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16433. }
  16434. function switchImgAndEmbed(img2embed) {
  16435. var tmpdiv,
  16436. nodes = domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img");
  16437. for (var i = 0, node; node = nodes[i++];) {
  16438. if (node.className != "edui-faked-music") {
  16439. continue;
  16440. }
  16441. tmpdiv = me.document.createElement("div");
  16442. //先看float在看align,浮动有的是时候是在float上定义的
  16443. var align = domUtils.getComputedStyle(node,'float');
  16444. align = align == 'none' ? (node.getAttribute('align') || '') : align;
  16445. tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url") : node.getAttribute("src"), node.width, node.height, align, img2embed);
  16446. node.parentNode.replaceChild(tmpdiv.firstChild, node);
  16447. }
  16448. }
  16449. me.addListener("beforegetcontent", function () {
  16450. switchImgAndEmbed(true);
  16451. });
  16452. me.addListener('aftersetcontent', function () {
  16453. switchImgAndEmbed(false);
  16454. });
  16455. me.addListener('aftergetcontent', function (cmdName) {
  16456. if (cmdName == 'aftergetcontent' && me.queryCommandState('source')) {
  16457. return;
  16458. }
  16459. switchImgAndEmbed(false);
  16460. });
  16461. me.commands["music"] = {
  16462. execCommand:function (cmd, musicObj) {
  16463. var me = this,
  16464. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false, true);
  16465. me.execCommand("inserthtml",str);
  16466. },
  16467. queryCommandState:function () {
  16468. var me = this,
  16469. img = me.selection.getRange().getClosedNode(),
  16470. flag = img && (img.className == "edui-faked-music");
  16471. return flag ? 1 : 0;
  16472. }
  16473. };
  16474. };
  16475. var baidu = baidu || {};
  16476. baidu.editor = baidu.editor || {};
  16477. baidu.editor.ui = {};
  16478. (function (){
  16479. var browser = baidu.editor.browser,
  16480. domUtils = baidu.editor.dom.domUtils;
  16481. var magic = '$EDITORUI';
  16482. var root = window[magic] = {};
  16483. var uidMagic = 'ID' + magic;
  16484. var uidCount = 0;
  16485. var uiUtils = baidu.editor.ui.uiUtils = {
  16486. uid: function (obj){
  16487. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  16488. },
  16489. hook: function ( fn, callback ) {
  16490. var dg;
  16491. if (fn && fn._callbacks) {
  16492. dg = fn;
  16493. } else {
  16494. dg = function (){
  16495. var q;
  16496. if (fn) {
  16497. q = fn.apply(this, arguments);
  16498. }
  16499. var callbacks = dg._callbacks;
  16500. var k = callbacks.length;
  16501. while (k --) {
  16502. var r = callbacks[k].apply(this, arguments);
  16503. if (q === undefined) {
  16504. q = r;
  16505. }
  16506. }
  16507. return q;
  16508. };
  16509. dg._callbacks = [];
  16510. }
  16511. dg._callbacks.push(callback);
  16512. return dg;
  16513. },
  16514. createElementByHtml: function (html){
  16515. var el = document.createElement('div');
  16516. el.innerHTML = html;
  16517. el = el.firstChild;
  16518. el.parentNode.removeChild(el);
  16519. return el;
  16520. },
  16521. getViewportElement: function (){
  16522. return (browser.ie && browser.quirks) ?
  16523. document.body : document.documentElement;
  16524. },
  16525. getClientRect: function (element){
  16526. var bcr;
  16527. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  16528. try{
  16529. bcr = element.getBoundingClientRect();
  16530. }catch(e){
  16531. bcr={left:0,top:0,height:0,width:0}
  16532. }
  16533. var rect = {
  16534. left: Math.round(bcr.left),
  16535. top: Math.round(bcr.top),
  16536. height: Math.round(bcr.bottom - bcr.top),
  16537. width: Math.round(bcr.right - bcr.left)
  16538. };
  16539. var doc;
  16540. while ((doc = element.ownerDocument) !== document &&
  16541. (element = domUtils.getWindow(doc).frameElement)) {
  16542. bcr = element.getBoundingClientRect();
  16543. rect.left += bcr.left;
  16544. rect.top += bcr.top;
  16545. }
  16546. rect.bottom = rect.top + rect.height;
  16547. rect.right = rect.left + rect.width;
  16548. return rect;
  16549. },
  16550. getViewportRect: function (){
  16551. var viewportEl = uiUtils.getViewportElement();
  16552. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  16553. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  16554. return {
  16555. left: 0,
  16556. top: 0,
  16557. height: height,
  16558. width: width,
  16559. bottom: height,
  16560. right: width
  16561. };
  16562. },
  16563. setViewportOffset: function (element, offset){
  16564. var rect;
  16565. var fixedLayer = uiUtils.getFixedLayer();
  16566. if (element.parentNode === fixedLayer) {
  16567. element.style.left = offset.left + 'px';
  16568. element.style.top = offset.top + 'px';
  16569. } else {
  16570. domUtils.setViewportOffset(element, offset);
  16571. }
  16572. },
  16573. getEventOffset: function (evt){
  16574. var el = evt.target || evt.srcElement;
  16575. var rect = uiUtils.getClientRect(el);
  16576. var offset = uiUtils.getViewportOffsetByEvent(evt);
  16577. return {
  16578. left: offset.left - rect.left,
  16579. top: offset.top - rect.top
  16580. };
  16581. },
  16582. getViewportOffsetByEvent: function (evt){
  16583. var el = evt.target || evt.srcElement;
  16584. var frameEl = domUtils.getWindow(el).frameElement;
  16585. var offset = {
  16586. left: evt.clientX,
  16587. top: evt.clientY
  16588. };
  16589. if (frameEl && el.ownerDocument !== document) {
  16590. var rect = uiUtils.getClientRect(frameEl);
  16591. offset.left += rect.left;
  16592. offset.top += rect.top;
  16593. }
  16594. return offset;
  16595. },
  16596. setGlobal: function (id, obj){
  16597. root[id] = obj;
  16598. return magic + '["' + id + '"]';
  16599. },
  16600. unsetGlobal: function (id){
  16601. delete root[id];
  16602. },
  16603. copyAttributes: function (tgt, src){
  16604. var attributes = src.attributes;
  16605. var k = attributes.length;
  16606. while (k --) {
  16607. var attrNode = attributes[k];
  16608. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  16609. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  16610. }
  16611. }
  16612. if (src.className) {
  16613. domUtils.addClass(tgt,src.className);
  16614. }
  16615. if (src.style.cssText) {
  16616. tgt.style.cssText += ';' + src.style.cssText;
  16617. }
  16618. },
  16619. removeStyle: function (el, styleName){
  16620. if (el.style.removeProperty) {
  16621. el.style.removeProperty(styleName);
  16622. } else if (el.style.removeAttribute) {
  16623. el.style.removeAttribute(styleName);
  16624. } else throw '';
  16625. },
  16626. contains: function (elA, elB){
  16627. return elA && elB && (elA === elB ? false : (
  16628. elA.contains ? elA.contains(elB) :
  16629. elA.compareDocumentPosition(elB) & 16
  16630. ));
  16631. },
  16632. startDrag: function (evt, callbacks,doc){
  16633. var doc = doc || document;
  16634. var startX = evt.clientX;
  16635. var startY = evt.clientY;
  16636. function handleMouseMove(evt){
  16637. var x = evt.clientX - startX;
  16638. var y = evt.clientY - startY;
  16639. callbacks.ondragmove(x, y,evt);
  16640. if (evt.stopPropagation) {
  16641. evt.stopPropagation();
  16642. } else {
  16643. evt.cancelBubble = true;
  16644. }
  16645. }
  16646. if (doc.addEventListener) {
  16647. function handleMouseUp(evt){
  16648. doc.removeEventListener('mousemove', handleMouseMove, true);
  16649. doc.removeEventListener('mouseup', handleMouseUp, true);
  16650. window.removeEventListener('mouseup', handleMouseUp, true);
  16651. callbacks.ondragstop();
  16652. }
  16653. doc.addEventListener('mousemove', handleMouseMove, true);
  16654. doc.addEventListener('mouseup', handleMouseUp, true);
  16655. window.addEventListener('mouseup', handleMouseUp, true);
  16656. evt.preventDefault();
  16657. } else {
  16658. var elm = evt.srcElement;
  16659. elm.setCapture();
  16660. function releaseCaptrue(){
  16661. elm.releaseCapture();
  16662. elm.detachEvent('onmousemove', handleMouseMove);
  16663. elm.detachEvent('onmouseup', releaseCaptrue);
  16664. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  16665. callbacks.ondragstop();
  16666. }
  16667. elm.attachEvent('onmousemove', handleMouseMove);
  16668. elm.attachEvent('onmouseup', releaseCaptrue);
  16669. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  16670. evt.returnValue = false;
  16671. }
  16672. callbacks.ondragstart();
  16673. },
  16674. getFixedLayer: function (){
  16675. var layer = document.getElementById('edui_fixedlayer');
  16676. if (layer == null) {
  16677. layer = document.createElement('div');
  16678. layer.id = 'edui_fixedlayer';
  16679. document.body.appendChild(layer);
  16680. if (browser.ie && browser.version <= 8) {
  16681. layer.style.position = 'absolute';
  16682. bindFixedLayer();
  16683. setTimeout(updateFixedOffset);
  16684. } else {
  16685. layer.style.position = 'fixed';
  16686. }
  16687. layer.style.left = '0';
  16688. layer.style.top = '0';
  16689. layer.style.width = '0';
  16690. layer.style.height = '0';
  16691. }
  16692. return layer;
  16693. },
  16694. makeUnselectable: function (element){
  16695. if (browser.opera || (browser.ie && browser.version < 9)) {
  16696. element.unselectable = 'on';
  16697. if (element.hasChildNodes()) {
  16698. for (var i=0; i<element.childNodes.length; i++) {
  16699. if (element.childNodes[i].nodeType == 1) {
  16700. uiUtils.makeUnselectable(element.childNodes[i]);
  16701. }
  16702. }
  16703. }
  16704. } else {
  16705. if (element.style.MozUserSelect !== undefined) {
  16706. element.style.MozUserSelect = 'none';
  16707. } else if (element.style.WebkitUserSelect !== undefined) {
  16708. element.style.WebkitUserSelect = 'none';
  16709. } else if (element.style.KhtmlUserSelect !== undefined) {
  16710. element.style.KhtmlUserSelect = 'none';
  16711. }
  16712. }
  16713. }
  16714. };
  16715. function updateFixedOffset(){
  16716. var layer = document.getElementById('edui_fixedlayer');
  16717. uiUtils.setViewportOffset(layer, {
  16718. left: 0,
  16719. top: 0
  16720. });
  16721. // layer.style.display = 'none';
  16722. // layer.style.display = 'block';
  16723. //#trace: 1354
  16724. // setTimeout(updateFixedOffset);
  16725. }
  16726. function bindFixedLayer(adjOffset){
  16727. domUtils.on(window, 'scroll', updateFixedOffset);
  16728. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  16729. }
  16730. })();
  16731. (function () {
  16732. var utils = baidu.editor.utils,
  16733. uiUtils = baidu.editor.ui.uiUtils,
  16734. EventBase = baidu.editor.EventBase,
  16735. UIBase = baidu.editor.ui.UIBase = function () {
  16736. };
  16737. UIBase.prototype = {
  16738. className:'',
  16739. uiName:'',
  16740. initOptions:function (options) {
  16741. var me = this;
  16742. for (var k in options) {
  16743. me[k] = options[k];
  16744. }
  16745. this.id = this.id || 'edui' + uiUtils.uid();
  16746. },
  16747. initUIBase:function () {
  16748. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  16749. },
  16750. render:function (holder) {
  16751. var html = this.renderHtml();
  16752. var el = uiUtils.createElementByHtml(html);
  16753. //by xuheng 给每个node添加class
  16754. var list = domUtils.getElementsByTagName(el, "*");
  16755. var theme = "edui-" + (this.theme || this.editor.options.theme);
  16756. var layer = document.getElementById('edui_fixedlayer');
  16757. for (var i = 0, node; node = list[i++];) {
  16758. domUtils.addClass(node, theme);
  16759. }
  16760. domUtils.addClass(el, theme);
  16761. if(layer){
  16762. layer.className="";
  16763. domUtils.addClass(layer,theme);
  16764. }
  16765. var seatEl = this.getDom();
  16766. if (seatEl != null) {
  16767. seatEl.parentNode.replaceChild(el, seatEl);
  16768. uiUtils.copyAttributes(el, seatEl);
  16769. } else {
  16770. if (typeof holder == 'string') {
  16771. holder = document.getElementById(holder);
  16772. }
  16773. holder = holder || uiUtils.getFixedLayer();
  16774. domUtils.addClass(holder, theme);
  16775. holder.appendChild(el);
  16776. }
  16777. this.postRender();
  16778. },
  16779. getDom:function (name) {
  16780. if (!name) {
  16781. return document.getElementById(this.id);
  16782. } else {
  16783. return document.getElementById(this.id + '_' + name);
  16784. }
  16785. },
  16786. postRender:function () {
  16787. this.fireEvent('postrender');
  16788. },
  16789. getHtmlTpl:function () {
  16790. return '';
  16791. },
  16792. formatHtml:function (tpl) {
  16793. var prefix = 'edui-' + this.uiName;
  16794. return (tpl
  16795. .replace(/##/g, this.id)
  16796. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  16797. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  16798. .replace(/\$\$/g, this._globalKey));
  16799. },
  16800. renderHtml:function () {
  16801. return this.formatHtml(this.getHtmlTpl());
  16802. },
  16803. dispose:function () {
  16804. var box = this.getDom();
  16805. if (box) baidu.editor.dom.domUtils.remove(box);
  16806. uiUtils.unsetGlobal(this.id);
  16807. }
  16808. };
  16809. utils.inherits(UIBase, EventBase);
  16810. })();
  16811. (function (){
  16812. var utils = baidu.editor.utils,
  16813. UIBase = baidu.editor.ui.UIBase,
  16814. Separator = baidu.editor.ui.Separator = function (options){
  16815. this.initOptions(options);
  16816. this.initSeparator();
  16817. };
  16818. Separator.prototype = {
  16819. uiName: 'separator',
  16820. initSeparator: function (){
  16821. this.initUIBase();
  16822. },
  16823. getHtmlTpl: function (){
  16824. return '<div id="##" class="edui-box %%"></div>';
  16825. }
  16826. };
  16827. utils.inherits(Separator, UIBase);
  16828. })();
  16829. ///import core
  16830. ///import uicore
  16831. (function (){
  16832. var utils = baidu.editor.utils,
  16833. domUtils = baidu.editor.dom.domUtils,
  16834. UIBase = baidu.editor.ui.UIBase,
  16835. uiUtils = baidu.editor.ui.uiUtils;
  16836. var Mask = baidu.editor.ui.Mask = function (options){
  16837. this.initOptions(options);
  16838. this.initUIBase();
  16839. };
  16840. Mask.prototype = {
  16841. getHtmlTpl: function (){
  16842. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  16843. },
  16844. postRender: function (){
  16845. var me = this;
  16846. domUtils.on(window, 'resize', function (){
  16847. setTimeout(function (){
  16848. if (!me.isHidden()) {
  16849. me._fill();
  16850. }
  16851. });
  16852. });
  16853. },
  16854. show: function (zIndex){
  16855. this._fill();
  16856. this.getDom().style.display = '';
  16857. this.getDom().style.zIndex = zIndex;
  16858. },
  16859. hide: function (){
  16860. this.getDom().style.display = 'none';
  16861. this.getDom().style.zIndex = '';
  16862. },
  16863. isHidden: function (){
  16864. return this.getDom().style.display == 'none';
  16865. },
  16866. _onMouseDown: function (){
  16867. return false;
  16868. },
  16869. _fill: function (){
  16870. var el = this.getDom();
  16871. var vpRect = uiUtils.getViewportRect();
  16872. el.style.width = vpRect.width + 'px';
  16873. el.style.height = vpRect.height + 'px';
  16874. }
  16875. };
  16876. utils.inherits(Mask, UIBase);
  16877. })();
  16878. ///import core
  16879. ///import uicore
  16880. (function () {
  16881. var utils = baidu.editor.utils,
  16882. uiUtils = baidu.editor.ui.uiUtils,
  16883. domUtils = baidu.editor.dom.domUtils,
  16884. UIBase = baidu.editor.ui.UIBase,
  16885. Popup = baidu.editor.ui.Popup = function (options){
  16886. this.initOptions(options);
  16887. this.initPopup();
  16888. };
  16889. var allPopups = [];
  16890. function closeAllPopup( evt,el ){
  16891. for ( var i = 0; i < allPopups.length; i++ ) {
  16892. var pop = allPopups[i];
  16893. if (!pop.isHidden()) {
  16894. if (pop.queryAutoHide(el) !== false) {
  16895. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  16896. pop.hide();
  16897. }
  16898. }
  16899. }
  16900. if(allPopups.length)
  16901. pop.editor.fireEvent("afterhidepop");
  16902. }
  16903. Popup.postHide = closeAllPopup;
  16904. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  16905. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  16906. Popup.prototype = {
  16907. SHADOW_RADIUS: 5,
  16908. content: null,
  16909. _hidden: false,
  16910. autoRender: true,
  16911. canSideLeft: true,
  16912. canSideUp: true,
  16913. initPopup: function (){
  16914. this.initUIBase();
  16915. allPopups.push( this );
  16916. },
  16917. getHtmlTpl: function (){
  16918. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  16919. ' <div id="##_body" class="edui-popup-body">' +
  16920. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  16921. ' <div class="edui-shadow"></div>' +
  16922. ' <div id="##_content" class="edui-popup-content">' +
  16923. this.getContentHtmlTpl() +
  16924. ' </div>' +
  16925. ' </div>' +
  16926. '</div>';
  16927. },
  16928. getContentHtmlTpl: function (){
  16929. if(this.content){
  16930. if (typeof this.content == 'string') {
  16931. return this.content;
  16932. }
  16933. return this.content.renderHtml();
  16934. }else{
  16935. return ''
  16936. }
  16937. },
  16938. _UIBase_postRender: UIBase.prototype.postRender,
  16939. postRender: function (){
  16940. if (this.content instanceof UIBase) {
  16941. this.content.postRender();
  16942. }
  16943. //捕获鼠标滚轮
  16944. if( this.captureWheel && !this.captured ) {
  16945. this.captured = true;
  16946. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  16947. _height = this.getDom().offsetHeight,
  16948. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  16949. content = this.getDom('content'),
  16950. ifr = this.getDom('body').getElementsByTagName('iframe'),
  16951. me = this;
  16952. ifr.length && ( ifr = ifr[0] );
  16953. while( _top + _height > winHeight ) {
  16954. _height -= 30;
  16955. content.style.height = _height + 'px';
  16956. //同步更改iframe高度
  16957. ifr && ( ifr.style.height = _height + 'px' );
  16958. }
  16959. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  16960. if( window.XMLHttpRequest ) {
  16961. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  16962. if(e.preventDefault) {
  16963. e.preventDefault();
  16964. } else {
  16965. e.returnValue = false;
  16966. }
  16967. if( e.wheelDelta ) {
  16968. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  16969. } else {
  16970. content.scrollTop -= ( e.detail / -3 )*60;
  16971. }
  16972. });
  16973. } else {
  16974. //ie6
  16975. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  16976. e.returnValue = false;
  16977. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  16978. });
  16979. }
  16980. }
  16981. this.fireEvent('postRenderAfter');
  16982. this.hide(true);
  16983. this._UIBase_postRender();
  16984. },
  16985. _doAutoRender: function (){
  16986. if (!this.getDom() && this.autoRender) {
  16987. this.render();
  16988. }
  16989. },
  16990. mesureSize: function (){
  16991. var box = this.getDom('content');
  16992. return uiUtils.getClientRect(box);
  16993. },
  16994. fitSize: function (){
  16995. if( this.captureWheel && this.sized ) {
  16996. return this.__size;
  16997. }
  16998. this.sized = true;
  16999. var popBodyEl = this.getDom('body');
  17000. popBodyEl.style.width = '';
  17001. popBodyEl.style.height = '';
  17002. var size = this.mesureSize();
  17003. if( this.captureWheel ) {
  17004. popBodyEl.style.width = -(-20 -size.width) + 'px';
  17005. var height = parseInt( this.getDom('content').style.height, 10 );
  17006. !window.isNaN( height ) && ( size.height = height );
  17007. } else {
  17008. popBodyEl.style.width = size.width + 'px';
  17009. }
  17010. popBodyEl.style.height = size.height + 'px';
  17011. this.__size = size;
  17012. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  17013. return size;
  17014. },
  17015. showAnchor: function ( element, hoz ){
  17016. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  17017. },
  17018. showAnchorRect: function ( rect, hoz, adj ){
  17019. this._doAutoRender();
  17020. var vpRect = uiUtils.getViewportRect();
  17021. this._show();
  17022. var popSize = this.fitSize();
  17023. var sideLeft, sideUp, left, top;
  17024. if (hoz) {
  17025. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  17026. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  17027. left = (sideLeft ? rect.left - popSize.width : rect.right);
  17028. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  17029. } else {
  17030. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  17031. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  17032. left = (sideLeft ? rect.right - popSize.width : rect.left);
  17033. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  17034. }
  17035. var popEl = this.getDom();
  17036. uiUtils.setViewportOffset(popEl, {
  17037. left: left,
  17038. top: top
  17039. });
  17040. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  17041. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  17042. if(this.editor){
  17043. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  17044. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  17045. }
  17046. },
  17047. showAt: function (offset) {
  17048. var left = offset.left;
  17049. var top = offset.top;
  17050. var rect = {
  17051. left: left,
  17052. top: top,
  17053. right: left,
  17054. bottom: top,
  17055. height: 0,
  17056. width: 0
  17057. };
  17058. this.showAnchorRect(rect, false, true);
  17059. },
  17060. _show: function (){
  17061. if (this._hidden) {
  17062. var box = this.getDom();
  17063. box.style.display = '';
  17064. this._hidden = false;
  17065. // if (box.setActive) {
  17066. // box.setActive();
  17067. // }
  17068. this.fireEvent('show');
  17069. }
  17070. },
  17071. isHidden: function (){
  17072. return this._hidden;
  17073. },
  17074. show: function (){
  17075. this._doAutoRender();
  17076. this._show();
  17077. },
  17078. hide: function (notNofity){
  17079. if (!this._hidden && this.getDom()) {
  17080. this.getDom().style.display = 'none';
  17081. this._hidden = true;
  17082. if (!notNofity) {
  17083. this.fireEvent('hide');
  17084. }
  17085. }
  17086. },
  17087. queryAutoHide: function (el){
  17088. return !el || !uiUtils.contains(this.getDom(), el);
  17089. }
  17090. };
  17091. utils.inherits(Popup, UIBase);
  17092. domUtils.on( document, 'mousedown', function ( evt ) {
  17093. var el = evt.target || evt.srcElement;
  17094. closeAllPopup( evt,el );
  17095. } );
  17096. domUtils.on( window, 'scroll', function (evt,el) {
  17097. closeAllPopup( evt,el );
  17098. } );
  17099. })();
  17100. ///import core
  17101. ///import uicore
  17102. (function (){
  17103. var utils = baidu.editor.utils,
  17104. UIBase = baidu.editor.ui.UIBase,
  17105. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  17106. this.initOptions(options);
  17107. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  17108. this.initUIBase();
  17109. };
  17110. ColorPicker.prototype = {
  17111. getHtmlTpl: function (){
  17112. return genColorPicker(this.noColorText,this.editor);
  17113. },
  17114. _onTableClick: function (evt){
  17115. var tgt = evt.target || evt.srcElement;
  17116. var color = tgt.getAttribute('data-color');
  17117. if (color) {
  17118. this.fireEvent('pickcolor', color);
  17119. }
  17120. },
  17121. _onTableOver: function (evt){
  17122. var tgt = evt.target || evt.srcElement;
  17123. var color = tgt.getAttribute('data-color');
  17124. if (color) {
  17125. this.getDom('preview').style.backgroundColor = color;
  17126. }
  17127. },
  17128. _onTableOut: function (){
  17129. this.getDom('preview').style.backgroundColor = '';
  17130. },
  17131. _onPickNoColor: function (){
  17132. this.fireEvent('picknocolor');
  17133. }
  17134. };
  17135. utils.inherits(ColorPicker, UIBase);
  17136. var COLORS = (
  17137. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  17138. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  17139. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  17140. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  17141. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  17142. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  17143. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  17144. function genColorPicker(noColorText,editor){
  17145. var html = '<div id="##" class="edui-colorpicker %%">' +
  17146. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  17147. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  17148. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  17149. '</div>' +
  17150. '<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">' +
  17151. '<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>'+
  17152. '<tr class="edui-colorpicker-tablefirstrow" >';
  17153. for (var i=0; i<COLORS.length; i++) {
  17154. if (i && i%10 === 0) {
  17155. 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"':'')+'>';
  17156. }
  17157. 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"' +
  17158. ' data-color="#'+ COLORS[i] +'"'+
  17159. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  17160. (i<10 || i>=60?'border-width:1px;':
  17161. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  17162. 'border-width:0 1px 0 1px;')+
  17163. '"' +
  17164. '></a></td>':'';
  17165. }
  17166. html += '</tr></table></div>';
  17167. return html;
  17168. }
  17169. })();
  17170. ///import core
  17171. ///import uicore
  17172. (function (){
  17173. var utils = baidu.editor.utils,
  17174. uiUtils = baidu.editor.ui.uiUtils,
  17175. UIBase = baidu.editor.ui.UIBase;
  17176. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  17177. this.initOptions(options);
  17178. this.initTablePicker();
  17179. };
  17180. TablePicker.prototype = {
  17181. defaultNumRows: 10,
  17182. defaultNumCols: 10,
  17183. maxNumRows: 20,
  17184. maxNumCols: 20,
  17185. numRows: 10,
  17186. numCols: 10,
  17187. lengthOfCellSide: 22,
  17188. initTablePicker: function (){
  17189. this.initUIBase();
  17190. },
  17191. getHtmlTpl: function (){
  17192. var me = this;
  17193. return '<div id="##" class="edui-tablepicker %%">' +
  17194. '<div class="edui-tablepicker-body">' +
  17195. '<div class="edui-infoarea">' +
  17196. '<span id="##_label" class="edui-label"></span>' +
  17197. '</div>' +
  17198. '<div class="edui-pickarea"' +
  17199. ' onmousemove="$$._onMouseMove(event, this);"' +
  17200. ' onmouseover="$$._onMouseOver(event, this);"' +
  17201. ' onmouseout="$$._onMouseOut(event, this);"' +
  17202. ' onclick="$$._onClick(event, this);"' +
  17203. '>' +
  17204. '<div id="##_overlay" class="edui-overlay"></div>' +
  17205. '</div>' +
  17206. '</div>' +
  17207. '</div>';
  17208. },
  17209. _UIBase_render: UIBase.prototype.render,
  17210. render: function (holder){
  17211. this._UIBase_render(holder);
  17212. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  17213. },
  17214. _track: function (numCols, numRows){
  17215. var style = this.getDom('overlay').style;
  17216. var sideLen = this.lengthOfCellSide;
  17217. style.width = numCols * sideLen + 'px';
  17218. style.height = numRows * sideLen + 'px';
  17219. var label = this.getDom('label');
  17220. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  17221. this.numCols = numCols;
  17222. this.numRows = numRows;
  17223. },
  17224. _onMouseOver: function (evt, el){
  17225. var rel = evt.relatedTarget || evt.fromElement;
  17226. if (!uiUtils.contains(el, rel) && el !== rel) {
  17227. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  17228. this.getDom('overlay').style.visibility = '';
  17229. }
  17230. },
  17231. _onMouseOut: function (evt, el){
  17232. var rel = evt.relatedTarget || evt.toElement;
  17233. if (!uiUtils.contains(el, rel) && el !== rel) {
  17234. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  17235. this.getDom('overlay').style.visibility = 'hidden';
  17236. }
  17237. },
  17238. _onMouseMove: function (evt, el){
  17239. var style = this.getDom('overlay').style;
  17240. var offset = uiUtils.getEventOffset(evt);
  17241. var sideLen = this.lengthOfCellSide;
  17242. var numCols = Math.ceil(offset.left / sideLen);
  17243. var numRows = Math.ceil(offset.top / sideLen);
  17244. this._track(numCols, numRows);
  17245. },
  17246. _onClick: function (){
  17247. this.fireEvent('picktable', this.numCols, this.numRows);
  17248. }
  17249. };
  17250. utils.inherits(TablePicker, UIBase);
  17251. })();
  17252. (function (){
  17253. var browser = baidu.editor.browser,
  17254. domUtils = baidu.editor.dom.domUtils,
  17255. uiUtils = baidu.editor.ui.uiUtils;
  17256. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  17257. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  17258. ( browser.ie ? (
  17259. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  17260. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  17261. : (
  17262. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  17263. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  17264. baidu.editor.ui.Stateful = {
  17265. alwalysHoverable: false,
  17266. target:null,//目标元素和this指向dom不一样
  17267. Stateful_init: function (){
  17268. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  17269. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  17270. },
  17271. Stateful_getHtmlTpl: function (){
  17272. var tpl = this._Stateful_dGetHtmlTpl();
  17273. // 使用function避免$转义
  17274. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  17275. },
  17276. Stateful_onMouseEnter: function (evt, el){
  17277. this.target=el;
  17278. if (!this.isDisabled() || this.alwalysHoverable) {
  17279. this.addState('hover');
  17280. this.fireEvent('over');
  17281. }
  17282. },
  17283. Stateful_onMouseLeave: function (evt, el){
  17284. if (!this.isDisabled() || this.alwalysHoverable) {
  17285. this.removeState('hover');
  17286. this.removeState('active');
  17287. this.fireEvent('out');
  17288. }
  17289. },
  17290. Stateful_onMouseOver: function (evt, el){
  17291. var rel = evt.relatedTarget;
  17292. if (!uiUtils.contains(el, rel) && el !== rel) {
  17293. this.Stateful_onMouseEnter(evt, el);
  17294. }
  17295. },
  17296. Stateful_onMouseOut: function (evt, el){
  17297. var rel = evt.relatedTarget;
  17298. if (!uiUtils.contains(el, rel) && el !== rel) {
  17299. this.Stateful_onMouseLeave(evt, el);
  17300. }
  17301. },
  17302. Stateful_onMouseDown: function (evt, el){
  17303. if (!this.isDisabled()) {
  17304. this.addState('active');
  17305. }
  17306. },
  17307. Stateful_onMouseUp: function (evt, el){
  17308. if (!this.isDisabled()) {
  17309. this.removeState('active');
  17310. }
  17311. },
  17312. Stateful_postRender: function (){
  17313. if (this.disabled && !this.hasState('disabled')) {
  17314. this.addState('disabled');
  17315. }
  17316. },
  17317. hasState: function (state){
  17318. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  17319. },
  17320. addState: function (state){
  17321. if (!this.hasState(state)) {
  17322. this.getStateDom().className += ' edui-state-' + state;
  17323. }
  17324. },
  17325. removeState: function (state){
  17326. if (this.hasState(state)) {
  17327. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  17328. }
  17329. },
  17330. getStateDom: function (){
  17331. return this.getDom('state');
  17332. },
  17333. isChecked: function (){
  17334. return this.hasState('checked');
  17335. },
  17336. setChecked: function (checked){
  17337. if (!this.isDisabled() && checked) {
  17338. this.addState('checked');
  17339. } else {
  17340. this.removeState('checked');
  17341. }
  17342. },
  17343. isDisabled: function (){
  17344. return this.hasState('disabled');
  17345. },
  17346. setDisabled: function (disabled){
  17347. if (disabled) {
  17348. this.removeState('hover');
  17349. this.removeState('checked');
  17350. this.removeState('active');
  17351. this.addState('disabled');
  17352. } else {
  17353. this.removeState('disabled');
  17354. }
  17355. }
  17356. };
  17357. })();
  17358. ///import core
  17359. ///import uicore
  17360. ///import ui/stateful.js
  17361. (function (){
  17362. var utils = baidu.editor.utils,
  17363. UIBase = baidu.editor.ui.UIBase,
  17364. Stateful = baidu.editor.ui.Stateful,
  17365. Button = baidu.editor.ui.Button = function (options){
  17366. this.initOptions(options);
  17367. this.initButton();
  17368. };
  17369. Button.prototype = {
  17370. uiName: 'button',
  17371. label: '',
  17372. title: '',
  17373. showIcon: true,
  17374. showText: true,
  17375. initButton: function (){
  17376. this.initUIBase();
  17377. this.Stateful_init();
  17378. },
  17379. getHtmlTpl: function (){
  17380. return '<div id="##" class="edui-box %%">' +
  17381. '<div id="##_state" stateful>' +
  17382. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  17383. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  17384. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  17385. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  17386. '</div>' +
  17387. '</div>' +
  17388. '</div></div>';
  17389. },
  17390. postRender: function (){
  17391. this.Stateful_postRender();
  17392. this.setDisabled(this.disabled)
  17393. },
  17394. _onClick: function (){
  17395. if (!this.isDisabled()) {
  17396. this.fireEvent('click');
  17397. }
  17398. }
  17399. };
  17400. utils.inherits(Button, UIBase);
  17401. utils.extend(Button.prototype, Stateful);
  17402. })();
  17403. ///import core
  17404. ///import uicore
  17405. ///import ui/stateful.js
  17406. (function (){
  17407. var utils = baidu.editor.utils,
  17408. uiUtils = baidu.editor.ui.uiUtils,
  17409. domUtils = baidu.editor.dom.domUtils,
  17410. UIBase = baidu.editor.ui.UIBase,
  17411. Stateful = baidu.editor.ui.Stateful,
  17412. SplitButton = baidu.editor.ui.SplitButton = function (options){
  17413. this.initOptions(options);
  17414. this.initSplitButton();
  17415. };
  17416. SplitButton.prototype = {
  17417. popup: null,
  17418. uiName: 'splitbutton',
  17419. title: '',
  17420. initSplitButton: function (){
  17421. this.initUIBase();
  17422. this.Stateful_init();
  17423. var me = this;
  17424. if (this.popup != null) {
  17425. var popup = this.popup;
  17426. this.popup = null;
  17427. this.setPopup(popup);
  17428. }
  17429. },
  17430. _UIBase_postRender: UIBase.prototype.postRender,
  17431. postRender: function (){
  17432. this.Stateful_postRender();
  17433. this._UIBase_postRender();
  17434. },
  17435. setPopup: function (popup){
  17436. if (this.popup === popup) return;
  17437. if (this.popup != null) {
  17438. this.popup.dispose();
  17439. }
  17440. popup.addListener('show', utils.bind(this._onPopupShow, this));
  17441. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  17442. popup.addListener('postrender', utils.bind(function (){
  17443. popup.getDom('body').appendChild(
  17444. uiUtils.createElementByHtml('<div id="' +
  17445. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  17446. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  17447. );
  17448. popup.getDom().className += ' ' + this.className;
  17449. }, this));
  17450. this.popup = popup;
  17451. },
  17452. _onPopupShow: function (){
  17453. this.addState('opened');
  17454. },
  17455. _onPopupHide: function (){
  17456. this.removeState('opened');
  17457. },
  17458. getHtmlTpl: function (){
  17459. return '<div id="##" class="edui-box %%">' +
  17460. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  17461. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  17462. '<div class="edui-box edui-icon"></div>' +
  17463. '</div>' +
  17464. '<div class="edui-box edui-splitborder"></div>' +
  17465. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  17466. '</div></div></div>';
  17467. },
  17468. showPopup: function (){
  17469. // 当popup往上弹出的时候,做特殊处理
  17470. var rect = uiUtils.getClientRect(this.getDom());
  17471. rect.top -= this.popup.SHADOW_RADIUS;
  17472. rect.height += this.popup.SHADOW_RADIUS;
  17473. this.popup.showAnchorRect(rect);
  17474. },
  17475. _onArrowClick: function (event, el){
  17476. if (!this.isDisabled()) {
  17477. this.showPopup();
  17478. }
  17479. },
  17480. _onButtonClick: function (){
  17481. if (!this.isDisabled()) {
  17482. this.fireEvent('buttonclick');
  17483. }
  17484. }
  17485. };
  17486. utils.inherits(SplitButton, UIBase);
  17487. utils.extend(SplitButton.prototype, Stateful, true);
  17488. })();
  17489. ///import core
  17490. ///import uicore
  17491. ///import ui/colorpicker.js
  17492. ///import ui/popup.js
  17493. ///import ui/splitbutton.js
  17494. (function (){
  17495. var utils = baidu.editor.utils,
  17496. uiUtils = baidu.editor.ui.uiUtils,
  17497. ColorPicker = baidu.editor.ui.ColorPicker,
  17498. Popup = baidu.editor.ui.Popup,
  17499. SplitButton = baidu.editor.ui.SplitButton,
  17500. ColorButton = baidu.editor.ui.ColorButton = function (options){
  17501. this.initOptions(options);
  17502. this.initColorButton();
  17503. };
  17504. ColorButton.prototype = {
  17505. initColorButton: function (){
  17506. var me = this;
  17507. this.popup = new Popup({
  17508. content: new ColorPicker({
  17509. noColorText: me.editor.getLang("clearColor"),
  17510. editor:me.editor,
  17511. onpickcolor: function (t, color){
  17512. me._onPickColor(color);
  17513. },
  17514. onpicknocolor: function (t, color){
  17515. me._onPickNoColor(color);
  17516. }
  17517. }),
  17518. editor:me.editor
  17519. });
  17520. this.initSplitButton();
  17521. },
  17522. _SplitButton_postRender: SplitButton.prototype.postRender,
  17523. postRender: function (){
  17524. this._SplitButton_postRender();
  17525. this.getDom('button_body').appendChild(
  17526. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  17527. );
  17528. this.getDom().className += ' edui-colorbutton';
  17529. },
  17530. setColor: function (color){
  17531. this.getDom('colorlump').style.backgroundColor = color;
  17532. this.color = color;
  17533. },
  17534. _onPickColor: function (color){
  17535. if (this.fireEvent('pickcolor', color) !== false) {
  17536. this.setColor(color);
  17537. this.popup.hide();
  17538. }
  17539. },
  17540. _onPickNoColor: function (color){
  17541. if (this.fireEvent('picknocolor') !== false) {
  17542. this.popup.hide();
  17543. }
  17544. }
  17545. };
  17546. utils.inherits(ColorButton, SplitButton);
  17547. })();
  17548. ///import core
  17549. ///import uicore
  17550. ///import ui/popup.js
  17551. ///import ui/tablepicker.js
  17552. ///import ui/splitbutton.js
  17553. (function (){
  17554. var utils = baidu.editor.utils,
  17555. Popup = baidu.editor.ui.Popup,
  17556. TablePicker = baidu.editor.ui.TablePicker,
  17557. SplitButton = baidu.editor.ui.SplitButton,
  17558. TableButton = baidu.editor.ui.TableButton = function (options){
  17559. this.initOptions(options);
  17560. this.initTableButton();
  17561. };
  17562. TableButton.prototype = {
  17563. initTableButton: function (){
  17564. var me = this;
  17565. this.popup = new Popup({
  17566. content: new TablePicker({
  17567. editor:me.editor,
  17568. onpicktable: function (t, numCols, numRows){
  17569. me._onPickTable(numCols, numRows);
  17570. }
  17571. }),
  17572. 'editor':me.editor
  17573. });
  17574. this.initSplitButton();
  17575. },
  17576. _onPickTable: function (numCols, numRows){
  17577. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  17578. this.popup.hide();
  17579. }
  17580. }
  17581. };
  17582. utils.inherits(TableButton, SplitButton);
  17583. })();
  17584. ///import core
  17585. ///import uicore
  17586. (function () {
  17587. var utils = baidu.editor.utils,
  17588. UIBase = baidu.editor.ui.UIBase;
  17589. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  17590. this.initOptions(options);
  17591. this.initAutoTypeSetPicker();
  17592. };
  17593. AutoTypeSetPicker.prototype = {
  17594. initAutoTypeSetPicker:function () {
  17595. this.initUIBase();
  17596. },
  17597. getHtmlTpl:function () {
  17598. var me = this.editor,
  17599. opt = me.options.autotypeset,
  17600. lang = me.getLang("autoTypeSet");
  17601. var textAlignInputName = 'textAlignValue' + me.uid,
  17602. imageBlockInputName = 'imageBlockLineValue' + me.uid;
  17603. return '<div id="##" class="edui-autotypesetpicker %%">' +
  17604. '<div class="edui-autotypesetpicker-body">' +
  17605. '<table >' +
  17606. '<tr><td nowrap colspan="2"><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' +
  17607. '<tr><td nowrap colspan="2"><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' +
  17608. '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' +
  17609. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  17610. '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' +
  17611. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  17612. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  17613. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  17614. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  17615. '<tr><td nowrap colspan="2"><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' +
  17616. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  17617. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  17618. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  17619. '</table>' +
  17620. '</div>' +
  17621. '</div>';
  17622. },
  17623. _UIBase_render:UIBase.prototype.render
  17624. };
  17625. utils.inherits(AutoTypeSetPicker, UIBase);
  17626. })();
  17627. ///import core
  17628. ///import uicore
  17629. ///import ui/popup.js
  17630. ///import ui/autotypesetpicker.js
  17631. ///import ui/splitbutton.js
  17632. (function (){
  17633. var utils = baidu.editor.utils,
  17634. Popup = baidu.editor.ui.Popup,
  17635. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  17636. SplitButton = baidu.editor.ui.SplitButton,
  17637. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  17638. this.initOptions(options);
  17639. this.initAutoTypeSetButton();
  17640. };
  17641. function getPara(me){
  17642. var opt = me.editor.options.autotypeset,
  17643. cont = me.getDom(),
  17644. editorId = me.editor.uid,
  17645. inputType = null,
  17646. attrName = null,
  17647. ipts = domUtils.getElementsByTagName(cont,"input");
  17648. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  17649. inputType = ipt.getAttribute("type");
  17650. if(inputType=="checkbox"){
  17651. attrName = ipt.getAttribute("name");
  17652. opt[attrName] && delete opt[attrName];
  17653. if(ipt.checked){
  17654. var attrValue = document.getElementById( attrName+"Value" + editorId );
  17655. if(attrValue){
  17656. if(/input/ig.test(attrValue.tagName)){
  17657. opt[attrName] = attrValue.value;
  17658. }else{
  17659. var iptChilds = attrValue.getElementsByTagName("input");
  17660. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  17661. if(iptchild.checked){
  17662. opt[attrName] = iptchild.value;
  17663. break;
  17664. }
  17665. }
  17666. }
  17667. }else{
  17668. opt[attrName] = true;
  17669. }
  17670. }
  17671. }
  17672. }
  17673. var selects = domUtils.getElementsByTagName(cont,"select");
  17674. for(var i=0,si;si=selects[i++];){
  17675. var attr = si.getAttribute('name');
  17676. opt[attr] = opt[attr] ? si.value : '';
  17677. }
  17678. me.editor.options.autotypeset = opt;
  17679. }
  17680. AutoTypeSetButton.prototype = {
  17681. initAutoTypeSetButton: function (){
  17682. var me = this;
  17683. this.popup = new Popup({
  17684. //传入配置参数
  17685. content: new AutoTypeSetPicker({editor:me.editor}),
  17686. 'editor':me.editor,
  17687. hide : function(){
  17688. if (!this._hidden && this.getDom()) {
  17689. getPara(this);
  17690. this.getDom().style.display = 'none';
  17691. this._hidden = true;
  17692. this.fireEvent('hide');
  17693. }
  17694. }
  17695. });
  17696. var flag = 0;
  17697. this.popup.addListener('postRenderAfter',function(){
  17698. var popupUI = this;
  17699. if(flag)return;
  17700. var cont = this.getDom(),
  17701. btn = cont.getElementsByTagName('button')[0];
  17702. btn.onclick = function(){
  17703. getPara(popupUI);
  17704. me.editor.execCommand('autotypeset');
  17705. popupUI.hide()
  17706. };
  17707. flag = 1;
  17708. });
  17709. this.initSplitButton();
  17710. }
  17711. };
  17712. utils.inherits(AutoTypeSetButton, SplitButton);
  17713. })();
  17714. ///import core
  17715. ///import uicore
  17716. (function () {
  17717. var utils = baidu.editor.utils,
  17718. Popup = baidu.editor.ui.Popup,
  17719. Stateful = baidu.editor.ui.Stateful,
  17720. UIBase = baidu.editor.ui.UIBase;
  17721. /**
  17722. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  17723. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  17724. * @update 2013/4/2 hancong03@baidu.com
  17725. */
  17726. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  17727. this.initOptions(options);
  17728. this.initSelected();
  17729. this.initCellAlignPicker();
  17730. };
  17731. CellAlignPicker.prototype = {
  17732. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  17733. initSelected: function(){
  17734. var status = {
  17735. valign: {
  17736. top: 0,
  17737. middle: 1,
  17738. bottom: 2
  17739. },
  17740. align: {
  17741. left: 0,
  17742. center: 1,
  17743. right: 2
  17744. },
  17745. count: 3
  17746. },
  17747. result = -1;
  17748. if( this.selected ) {
  17749. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  17750. }
  17751. },
  17752. initCellAlignPicker:function () {
  17753. this.initUIBase();
  17754. this.Stateful_init();
  17755. },
  17756. getHtmlTpl:function () {
  17757. var alignType = [ 'left', 'center', 'right' ],
  17758. COUNT = 9,
  17759. tempClassName = null,
  17760. tempIndex = -1,
  17761. tmpl = [];
  17762. for( var i= 0; i<COUNT; i++ ) {
  17763. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  17764. tempIndex = i % 3;
  17765. tempIndex === 0 && tmpl.push('<tr>');
  17766. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  17767. tempIndex === 2 && tmpl.push('</tr>');
  17768. }
  17769. return '<div id="##" class="edui-cellalignpicker %%">' +
  17770. '<div class="edui-cellalignpicker-body">' +
  17771. '<table onclick="$$._onClick(event);">' +
  17772. tmpl.join('') +
  17773. '</table>' +
  17774. '</div>' +
  17775. '</div>';
  17776. },
  17777. getStateDom: function (){
  17778. return this.target;
  17779. },
  17780. _onClick: function (evt){
  17781. var target= evt.target || evt.srcElement;
  17782. if(/icon/.test(target.className)){
  17783. this.items[target.parentNode.getAttribute("index")].onclick();
  17784. Popup.postHide(evt);
  17785. }
  17786. },
  17787. _UIBase_render:UIBase.prototype.render
  17788. };
  17789. utils.inherits(CellAlignPicker, UIBase);
  17790. utils.extend(CellAlignPicker.prototype, Stateful,true);
  17791. })();
  17792. ///import core
  17793. ///import uicore
  17794. (function () {
  17795. var utils = baidu.editor.utils,
  17796. Stateful = baidu.editor.ui.Stateful,
  17797. uiUtils = baidu.editor.ui.uiUtils,
  17798. UIBase = baidu.editor.ui.UIBase;
  17799. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  17800. this.initOptions(options);
  17801. this.initPastePicker();
  17802. };
  17803. PastePicker.prototype = {
  17804. initPastePicker:function () {
  17805. this.initUIBase();
  17806. this.Stateful_init();
  17807. },
  17808. getHtmlTpl:function () {
  17809. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  17810. '<div class="edui-pastecontainer">' +
  17811. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  17812. '<div class="edui-button">' +
  17813. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  17814. '<div class="edui-richtxticon"></div></div>' +
  17815. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  17816. '<div class="edui-tagicon"></div></div>' +
  17817. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  17818. '<div class="edui-plaintxticon"></div></div>' +
  17819. '</div>' +
  17820. '</div>' +
  17821. '</div>'
  17822. },
  17823. getStateDom:function () {
  17824. return this.target;
  17825. },
  17826. format:function (param) {
  17827. this.editor.ui._isTransfer = true;
  17828. this.editor.fireEvent('pasteTransfer', param);
  17829. },
  17830. _onClick:function (cur) {
  17831. var node = domUtils.getNextDomNode(cur),
  17832. screenHt = uiUtils.getViewportRect().height,
  17833. subPop = uiUtils.getClientRect(node);
  17834. if ((subPop.top + subPop.height) > screenHt)
  17835. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  17836. else
  17837. node.style.top = "";
  17838. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  17839. node.style.visibility = "visible";
  17840. domUtils.addClass(cur, "edui-state-opened");
  17841. } else {
  17842. node.style.visibility = "hidden";
  17843. domUtils.removeClasses(cur, "edui-state-opened")
  17844. }
  17845. },
  17846. _UIBase_render:UIBase.prototype.render
  17847. };
  17848. utils.inherits(PastePicker, UIBase);
  17849. utils.extend(PastePicker.prototype, Stateful, true);
  17850. })();
  17851. (function (){
  17852. var utils = baidu.editor.utils,
  17853. uiUtils = baidu.editor.ui.uiUtils,
  17854. UIBase = baidu.editor.ui.UIBase,
  17855. Toolbar = baidu.editor.ui.Toolbar = function (options){
  17856. this.initOptions(options);
  17857. this.initToolbar();
  17858. };
  17859. Toolbar.prototype = {
  17860. items: null,
  17861. initToolbar: function (){
  17862. this.items = this.items || [];
  17863. this.initUIBase();
  17864. },
  17865. add: function (item){
  17866. this.items.push(item);
  17867. },
  17868. getHtmlTpl: function (){
  17869. var buff = [];
  17870. for (var i=0; i<this.items.length; i++) {
  17871. buff[i] = this.items[i].renderHtml();
  17872. }
  17873. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  17874. buff.join('') +
  17875. '</div>'
  17876. },
  17877. postRender: function (){
  17878. var box = this.getDom();
  17879. for (var i=0; i<this.items.length; i++) {
  17880. this.items[i].postRender();
  17881. }
  17882. uiUtils.makeUnselectable(box);
  17883. },
  17884. _onMouseDown: function (){
  17885. return false;
  17886. }
  17887. };
  17888. utils.inherits(Toolbar, UIBase);
  17889. })();
  17890. ///import core
  17891. ///import uicore
  17892. ///import ui\popup.js
  17893. ///import ui\stateful.js
  17894. (function () {
  17895. var utils = baidu.editor.utils,
  17896. domUtils = baidu.editor.dom.domUtils,
  17897. uiUtils = baidu.editor.ui.uiUtils,
  17898. UIBase = baidu.editor.ui.UIBase,
  17899. Popup = baidu.editor.ui.Popup,
  17900. Stateful = baidu.editor.ui.Stateful,
  17901. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  17902. Menu = baidu.editor.ui.Menu = function (options) {
  17903. this.initOptions(options);
  17904. this.initMenu();
  17905. };
  17906. var menuSeparator = {
  17907. renderHtml:function () {
  17908. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  17909. },
  17910. postRender:function () {
  17911. },
  17912. queryAutoHide:function () {
  17913. return true;
  17914. }
  17915. };
  17916. Menu.prototype = {
  17917. items:null,
  17918. uiName:'menu',
  17919. initMenu:function () {
  17920. this.items = this.items || [];
  17921. this.initPopup();
  17922. this.initItems();
  17923. },
  17924. initItems:function () {
  17925. for (var i = 0; i < this.items.length; i++) {
  17926. var item = this.items[i];
  17927. if (item == '-') {
  17928. this.items[i] = this.getSeparator();
  17929. } else if (!(item instanceof MenuItem)) {
  17930. item.editor = this.editor;
  17931. item.theme = this.editor.options.theme;
  17932. this.items[i] = this.createItem(item);
  17933. }
  17934. }
  17935. },
  17936. getSeparator:function () {
  17937. return menuSeparator;
  17938. },
  17939. createItem:function (item) {
  17940. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  17941. item.menu = this;
  17942. return new MenuItem(item);
  17943. },
  17944. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  17945. getContentHtmlTpl:function () {
  17946. if (this.items.length == 0) {
  17947. return this._Popup_getContentHtmlTpl();
  17948. }
  17949. var buff = [];
  17950. for (var i = 0; i < this.items.length; i++) {
  17951. var item = this.items[i];
  17952. buff[i] = item.renderHtml();
  17953. }
  17954. return ('<div class="%%-body">' + buff.join('') + '</div>');
  17955. },
  17956. _Popup_postRender:Popup.prototype.postRender,
  17957. postRender:function () {
  17958. var me = this;
  17959. for (var i = 0; i < this.items.length; i++) {
  17960. var item = this.items[i];
  17961. item.ownerMenu = this;
  17962. item.postRender();
  17963. }
  17964. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  17965. evt = evt || event;
  17966. var rel = evt.relatedTarget || evt.fromElement;
  17967. var el = me.getDom();
  17968. if (!uiUtils.contains(el, rel) && el !== rel) {
  17969. me.fireEvent('over');
  17970. }
  17971. });
  17972. this._Popup_postRender();
  17973. },
  17974. queryAutoHide:function (el) {
  17975. if (el) {
  17976. if (uiUtils.contains(this.getDom(), el)) {
  17977. return false;
  17978. }
  17979. for (var i = 0; i < this.items.length; i++) {
  17980. var item = this.items[i];
  17981. if (item.queryAutoHide(el) === false) {
  17982. return false;
  17983. }
  17984. }
  17985. }
  17986. },
  17987. clearItems:function () {
  17988. for (var i = 0; i < this.items.length; i++) {
  17989. var item = this.items[i];
  17990. clearTimeout(item._showingTimer);
  17991. clearTimeout(item._closingTimer);
  17992. if (item.subMenu) {
  17993. item.subMenu.destroy();
  17994. }
  17995. }
  17996. this.items = [];
  17997. },
  17998. destroy:function () {
  17999. if (this.getDom()) {
  18000. domUtils.remove(this.getDom());
  18001. }
  18002. this.clearItems();
  18003. },
  18004. dispose:function () {
  18005. this.destroy();
  18006. }
  18007. };
  18008. utils.inherits(Menu, Popup);
  18009. /**
  18010. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  18011. * @type {Function}
  18012. */
  18013. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  18014. this.initOptions(options);
  18015. this.initUIBase();
  18016. this.Stateful_init();
  18017. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  18018. if (options.className && options.className.indexOf("aligntd") != -1) {
  18019. var me = this;
  18020. //获取单元格对齐初始状态
  18021. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  18022. this.subMenu = new Popup({
  18023. content:new CellAlignPicker(this.subMenu),
  18024. parentMenu:me,
  18025. editor:me.editor,
  18026. destroy:function () {
  18027. if (this.getDom()) {
  18028. domUtils.remove(this.getDom());
  18029. }
  18030. }
  18031. });
  18032. this.subMenu.addListener("postRenderAfter", function () {
  18033. domUtils.on(this.getDom(), "mouseover", function () {
  18034. me.addState('opened');
  18035. });
  18036. });
  18037. } else {
  18038. this.subMenu = new Menu(this.subMenu);
  18039. }
  18040. }
  18041. };
  18042. MenuItem.prototype = {
  18043. label:'',
  18044. subMenu:null,
  18045. ownerMenu:null,
  18046. uiName:'menuitem',
  18047. alwalysHoverable:true,
  18048. getHtmlTpl:function () {
  18049. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  18050. '<div class="%%-body">' +
  18051. this.renderLabelHtml() +
  18052. '</div>' +
  18053. '</div>';
  18054. },
  18055. postRender:function () {
  18056. var me = this;
  18057. this.addListener('over', function () {
  18058. me.ownerMenu.fireEvent('submenuover', me);
  18059. if (me.subMenu) {
  18060. me.delayShowSubMenu();
  18061. }
  18062. });
  18063. if (this.subMenu) {
  18064. this.getDom().className += ' edui-hassubmenu';
  18065. this.subMenu.render();
  18066. this.addListener('out', function () {
  18067. me.delayHideSubMenu();
  18068. });
  18069. this.subMenu.addListener('over', function () {
  18070. clearTimeout(me._closingTimer);
  18071. me._closingTimer = null;
  18072. me.addState('opened');
  18073. });
  18074. this.ownerMenu.addListener('hide', function () {
  18075. me.hideSubMenu();
  18076. });
  18077. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  18078. if (subMenu !== me) {
  18079. me.delayHideSubMenu();
  18080. }
  18081. });
  18082. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  18083. this.subMenu.queryAutoHide = function (el) {
  18084. if (el && uiUtils.contains(me.getDom(), el)) {
  18085. return false;
  18086. }
  18087. return this._bakQueryAutoHide(el);
  18088. };
  18089. }
  18090. this.getDom().style.tabIndex = '-1';
  18091. uiUtils.makeUnselectable(this.getDom());
  18092. this.Stateful_postRender();
  18093. },
  18094. delayShowSubMenu:function () {
  18095. var me = this;
  18096. if (!me.isDisabled()) {
  18097. me.addState('opened');
  18098. clearTimeout(me._showingTimer);
  18099. clearTimeout(me._closingTimer);
  18100. me._closingTimer = null;
  18101. me._showingTimer = setTimeout(function () {
  18102. me.showSubMenu();
  18103. }, 250);
  18104. }
  18105. },
  18106. delayHideSubMenu:function () {
  18107. var me = this;
  18108. if (!me.isDisabled()) {
  18109. me.removeState('opened');
  18110. clearTimeout(me._showingTimer);
  18111. if (!me._closingTimer) {
  18112. me._closingTimer = setTimeout(function () {
  18113. if (!me.hasState('opened')) {
  18114. me.hideSubMenu();
  18115. }
  18116. me._closingTimer = null;
  18117. }, 400);
  18118. }
  18119. }
  18120. },
  18121. renderLabelHtml:function () {
  18122. return '<div class="edui-arrow"></div>' +
  18123. '<div class="edui-box edui-icon"></div>' +
  18124. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  18125. },
  18126. getStateDom:function () {
  18127. return this.getDom();
  18128. },
  18129. queryAutoHide:function (el) {
  18130. if (this.subMenu && this.hasState('opened')) {
  18131. return this.subMenu.queryAutoHide(el);
  18132. }
  18133. },
  18134. _onClick:function (event, this_) {
  18135. if (this.hasState('disabled')) return;
  18136. if (this.fireEvent('click', event, this_) !== false) {
  18137. if (this.subMenu) {
  18138. this.showSubMenu();
  18139. } else {
  18140. Popup.postHide(event);
  18141. }
  18142. }
  18143. },
  18144. showSubMenu:function () {
  18145. var rect = uiUtils.getClientRect(this.getDom());
  18146. rect.right -= 5;
  18147. rect.left += 2;
  18148. rect.width -= 7;
  18149. rect.top -= 4;
  18150. rect.bottom += 4;
  18151. rect.height += 8;
  18152. this.subMenu.showAnchorRect(rect, true, true);
  18153. },
  18154. hideSubMenu:function () {
  18155. this.subMenu.hide();
  18156. }
  18157. };
  18158. utils.inherits(MenuItem, UIBase);
  18159. utils.extend(MenuItem.prototype, Stateful, true);
  18160. })();
  18161. ///import core
  18162. ///import uicore
  18163. ///import ui/menu.js
  18164. ///import ui/splitbutton.js
  18165. (function (){
  18166. // todo: menu和item提成通用list
  18167. var utils = baidu.editor.utils,
  18168. uiUtils = baidu.editor.ui.uiUtils,
  18169. Menu = baidu.editor.ui.Menu,
  18170. SplitButton = baidu.editor.ui.SplitButton,
  18171. Combox = baidu.editor.ui.Combox = function (options){
  18172. this.initOptions(options);
  18173. this.initCombox();
  18174. };
  18175. Combox.prototype = {
  18176. uiName: 'combox',
  18177. initCombox: function (){
  18178. var me = this;
  18179. this.items = this.items || [];
  18180. for (var i=0; i<this.items.length; i++) {
  18181. var item = this.items[i];
  18182. item.uiName = 'listitem';
  18183. item.index = i;
  18184. item.onclick = function (){
  18185. me.selectByIndex(this.index);
  18186. };
  18187. }
  18188. this.popup = new Menu({
  18189. items: this.items,
  18190. uiName: 'list',
  18191. editor:this.editor,
  18192. captureWheel: true,
  18193. combox: this
  18194. });
  18195. this.initSplitButton();
  18196. },
  18197. _SplitButton_postRender: SplitButton.prototype.postRender,
  18198. postRender: function (){
  18199. this._SplitButton_postRender();
  18200. this.setLabel(this.label || '');
  18201. this.setValue(this.initValue || '');
  18202. },
  18203. showPopup: function (){
  18204. var rect = uiUtils.getClientRect(this.getDom());
  18205. rect.top += 1;
  18206. rect.bottom -= 1;
  18207. rect.height -= 2;
  18208. this.popup.showAnchorRect(rect);
  18209. },
  18210. getValue: function (){
  18211. return this.value;
  18212. },
  18213. setValue: function (value){
  18214. var index = this.indexByValue(value);
  18215. if (index != -1) {
  18216. this.selectedIndex = index;
  18217. this.setLabel(this.items[index].label);
  18218. this.value = this.items[index].value;
  18219. } else {
  18220. this.selectedIndex = -1;
  18221. this.setLabel(this.getLabelForUnknowValue(value));
  18222. this.value = value;
  18223. }
  18224. },
  18225. setLabel: function (label){
  18226. this.getDom('button_body').innerHTML = label;
  18227. this.label = label;
  18228. },
  18229. getLabelForUnknowValue: function (value){
  18230. return value;
  18231. },
  18232. indexByValue: function (value){
  18233. for (var i=0; i<this.items.length; i++) {
  18234. if (value == this.items[i].value) {
  18235. return i;
  18236. }
  18237. }
  18238. return -1;
  18239. },
  18240. getItem: function (index){
  18241. return this.items[index];
  18242. },
  18243. selectByIndex: function (index){
  18244. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  18245. this.selectedIndex = index;
  18246. this.value = this.items[index].value;
  18247. this.setLabel(this.items[index].label);
  18248. }
  18249. }
  18250. };
  18251. utils.inherits(Combox, SplitButton);
  18252. })();
  18253. ///import core
  18254. ///import uicore
  18255. ///import ui/mask.js
  18256. ///import ui/button.js
  18257. (function (){
  18258. var utils = baidu.editor.utils,
  18259. domUtils = baidu.editor.dom.domUtils,
  18260. uiUtils = baidu.editor.ui.uiUtils,
  18261. Mask = baidu.editor.ui.Mask,
  18262. UIBase = baidu.editor.ui.UIBase,
  18263. Button = baidu.editor.ui.Button,
  18264. Dialog = baidu.editor.ui.Dialog = function (options){
  18265. this.initOptions(utils.extend({
  18266. autoReset: true,
  18267. draggable: true,
  18268. onok: function (){},
  18269. oncancel: function (){},
  18270. onclose: function (t, ok){
  18271. return ok ? this.onok() : this.oncancel();
  18272. },
  18273. //是否控制dialog中的scroll事件, 默认为不阻止
  18274. holdScroll: false
  18275. },options));
  18276. this.initDialog();
  18277. };
  18278. var modalMask;
  18279. var dragMask;
  18280. Dialog.prototype = {
  18281. draggable: false,
  18282. uiName: 'dialog',
  18283. initDialog: function (){
  18284. var me = this,
  18285. theme=this.editor.options.theme;
  18286. this.initUIBase();
  18287. this.modalMask = (modalMask || (modalMask = new Mask({
  18288. className: 'edui-dialog-modalmask',
  18289. theme:theme
  18290. })));
  18291. this.dragMask = (dragMask || (dragMask = new Mask({
  18292. className: 'edui-dialog-dragmask',
  18293. theme:theme
  18294. })));
  18295. this.closeButton = new Button({
  18296. className: 'edui-dialog-closebutton',
  18297. title: me.closeDialog,
  18298. theme:theme,
  18299. onclick: function (){
  18300. me.close(false);
  18301. }
  18302. });
  18303. if (this.buttons) {
  18304. for (var i=0; i<this.buttons.length; i++) {
  18305. if (!(this.buttons[i] instanceof Button)) {
  18306. this.buttons[i] = new Button(this.buttons[i]);
  18307. }
  18308. }
  18309. }
  18310. },
  18311. fitSize: function (){
  18312. var popBodyEl = this.getDom('body');
  18313. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  18314. // uiUtils.removeStyle(popBodyEl, 'width');
  18315. // uiUtils.removeStyle(popBodyEl, 'height');
  18316. // }
  18317. var size = this.mesureSize();
  18318. popBodyEl.style.width = size.width + 'px';
  18319. popBodyEl.style.height = size.height + 'px';
  18320. return size;
  18321. },
  18322. safeSetOffset: function (offset){
  18323. var me = this;
  18324. var el = me.getDom();
  18325. var vpRect = uiUtils.getViewportRect();
  18326. var rect = uiUtils.getClientRect(el);
  18327. var left = offset.left;
  18328. if (left + rect.width > vpRect.right) {
  18329. left = vpRect.right - rect.width;
  18330. }
  18331. var top = offset.top;
  18332. if (top + rect.height > vpRect.bottom) {
  18333. top = vpRect.bottom - rect.height;
  18334. }
  18335. el.style.left = Math.max(left, 0) + 'px';
  18336. el.style.top = Math.max(top, 0) + 'px';
  18337. },
  18338. showAtCenter: function (){
  18339. this.getDom().style.display = '';
  18340. var vpRect = uiUtils.getViewportRect();
  18341. var popSize = this.fitSize();
  18342. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  18343. var left = vpRect.width / 2 - popSize.width / 2;
  18344. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  18345. var popEl = this.getDom();
  18346. this.safeSetOffset({
  18347. left: Math.max(left | 0, 0),
  18348. top: Math.max(top | 0, 0)
  18349. });
  18350. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  18351. popEl.className += ' edui-state-centered';
  18352. }
  18353. this._show();
  18354. },
  18355. getContentHtml: function (){
  18356. var contentHtml = '';
  18357. if (typeof this.content == 'string') {
  18358. contentHtml = this.content;
  18359. } else if (this.iframeUrl) {
  18360. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  18361. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  18362. }
  18363. return contentHtml;
  18364. },
  18365. getHtmlTpl: function (){
  18366. var footHtml = '';
  18367. if (this.buttons) {
  18368. var buff = [];
  18369. for (var i=0; i<this.buttons.length; i++) {
  18370. buff[i] = this.buttons[i].renderHtml();
  18371. }
  18372. footHtml = '<div class="%%-foot">' +
  18373. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  18374. '</div>';
  18375. }
  18376. return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' +
  18377. '<div class="%%-shadow"></div>' +
  18378. '<div id="##_titlebar" class="%%-titlebar">' +
  18379. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  18380. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  18381. '</div>' +
  18382. this.closeButton.renderHtml() +
  18383. '</div>' +
  18384. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  18385. footHtml +
  18386. '</div></div></div>';
  18387. },
  18388. postRender: function (){
  18389. // todo: 保持居中/记住上次关闭位置选项
  18390. if (!this.modalMask.getDom()) {
  18391. this.modalMask.render();
  18392. this.modalMask.hide();
  18393. }
  18394. if (!this.dragMask.getDom()) {
  18395. this.dragMask.render();
  18396. this.dragMask.hide();
  18397. }
  18398. var me = this;
  18399. this.addListener('show', function (){
  18400. me.modalMask.show(this.getDom().style.zIndex - 2);
  18401. });
  18402. this.addListener('hide', function (){
  18403. me.modalMask.hide();
  18404. });
  18405. if (this.buttons) {
  18406. for (var i=0; i<this.buttons.length; i++) {
  18407. this.buttons[i].postRender();
  18408. }
  18409. }
  18410. domUtils.on(window, 'resize', function (){
  18411. setTimeout(function (){
  18412. if (!me.isHidden()) {
  18413. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  18414. }
  18415. });
  18416. });
  18417. //hold住scroll事件,防止dialog的滚动影响页面
  18418. if( this.holdScroll ) {
  18419. if( !me.iframeUrl ) {
  18420. domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18421. domUtils.preventDefault(e);
  18422. } );
  18423. } else {
  18424. me.addListener('dialogafterreset', function(){
  18425. window.setTimeout(function(){
  18426. var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  18427. if( browser.ie ) {
  18428. var timer = window.setInterval(function(){
  18429. if( iframeWindow.document && iframeWindow.document.body ) {
  18430. window.clearInterval( timer );
  18431. timer = null;
  18432. domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18433. domUtils.preventDefault(e);
  18434. } );
  18435. }
  18436. }, 100);
  18437. } else {
  18438. domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  18439. domUtils.preventDefault(e);
  18440. } );
  18441. }
  18442. }, 1);
  18443. });
  18444. }
  18445. }
  18446. this._hide();
  18447. },
  18448. mesureSize: function (){
  18449. var body = this.getDom('body');
  18450. var width = uiUtils.getClientRect(this.getDom('content')).width;
  18451. var dialogBodyStyle = body.style;
  18452. dialogBodyStyle.width = width;
  18453. return uiUtils.getClientRect(body);
  18454. },
  18455. _onTitlebarMouseDown: function (evt, el){
  18456. if (this.draggable) {
  18457. var rect;
  18458. var vpRect = uiUtils.getViewportRect();
  18459. var me = this;
  18460. uiUtils.startDrag(evt, {
  18461. ondragstart: function (){
  18462. rect = uiUtils.getClientRect(me.getDom());
  18463. me.getDom('contmask').style.visibility = 'visible';
  18464. me.dragMask.show(me.getDom().style.zIndex - 1);
  18465. },
  18466. ondragmove: function (x, y){
  18467. var left = rect.left + x;
  18468. var top = rect.top + y;
  18469. me.safeSetOffset({
  18470. left: left,
  18471. top: top
  18472. });
  18473. },
  18474. ondragstop: function (){
  18475. me.getDom('contmask').style.visibility = 'hidden';
  18476. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  18477. me.dragMask.hide();
  18478. }
  18479. });
  18480. }
  18481. },
  18482. reset: function (){
  18483. this.getDom('content').innerHTML = this.getContentHtml();
  18484. this.fireEvent('dialogafterreset');
  18485. },
  18486. _show: function (){
  18487. if (this._hidden) {
  18488. this.getDom().style.display = '';
  18489. //要高过编辑器的zindxe
  18490. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  18491. this._hidden = false;
  18492. this.fireEvent('show');
  18493. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  18494. }
  18495. },
  18496. isHidden: function (){
  18497. return this._hidden;
  18498. },
  18499. _hide: function (){
  18500. if (!this._hidden) {
  18501. this.getDom().style.display = 'none';
  18502. this.getDom().style.zIndex = '';
  18503. this._hidden = true;
  18504. this.fireEvent('hide');
  18505. }
  18506. },
  18507. open: function (){
  18508. if (this.autoReset) {
  18509. //有可能还没有渲染
  18510. try{
  18511. this.reset();
  18512. }catch(e){
  18513. this.render();
  18514. this.open()
  18515. }
  18516. }
  18517. this.showAtCenter();
  18518. if (this.iframeUrl) {
  18519. try {
  18520. this.getDom('iframe').focus();
  18521. } catch(ex){}
  18522. }
  18523. },
  18524. _onCloseButtonClick: function (evt, el){
  18525. this.close(false);
  18526. },
  18527. close: function (ok){
  18528. if (this.fireEvent('close', ok) !== false) {
  18529. this._hide();
  18530. }
  18531. }
  18532. };
  18533. utils.inherits(Dialog, UIBase);
  18534. })();
  18535. ///import core
  18536. ///import uicore
  18537. ///import ui/menu.js
  18538. ///import ui/splitbutton.js
  18539. (function (){
  18540. var utils = baidu.editor.utils,
  18541. Menu = baidu.editor.ui.Menu,
  18542. SplitButton = baidu.editor.ui.SplitButton,
  18543. MenuButton = baidu.editor.ui.MenuButton = function (options){
  18544. this.initOptions(options);
  18545. this.initMenuButton();
  18546. };
  18547. MenuButton.prototype = {
  18548. initMenuButton: function (){
  18549. var me = this;
  18550. this.uiName = "menubutton";
  18551. this.popup = new Menu({
  18552. items: me.items,
  18553. className: me.className,
  18554. editor:me.editor
  18555. });
  18556. this.popup.addListener('show', function (){
  18557. var list = this;
  18558. for (var i=0; i<list.items.length; i++) {
  18559. list.items[i].removeState('checked');
  18560. if (list.items[i].value == me._value) {
  18561. list.items[i].addState('checked');
  18562. this.value = me._value;
  18563. }
  18564. }
  18565. });
  18566. this.initSplitButton();
  18567. },
  18568. setValue : function(value){
  18569. this._value = value;
  18570. }
  18571. };
  18572. utils.inherits(MenuButton, SplitButton);
  18573. })();
  18574. //ui跟编辑器的适配層
  18575. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  18576. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  18577. (function () {
  18578. var utils = baidu.editor.utils;
  18579. var editorui = baidu.editor.ui;
  18580. var _Dialog = editorui.Dialog;
  18581. editorui.buttons = {};
  18582. editorui.Dialog = function (options) {
  18583. var dialog = new _Dialog(options);
  18584. dialog.addListener('hide', function () {
  18585. if (dialog.editor) {
  18586. var editor = dialog.editor;
  18587. try {
  18588. if (browser.gecko) {
  18589. var y = editor.window.scrollY,
  18590. x = editor.window.scrollX;
  18591. editor.body.focus();
  18592. editor.window.scrollTo(x, y);
  18593. } else {
  18594. editor.focus();
  18595. }
  18596. } catch (ex) {
  18597. }
  18598. }
  18599. });
  18600. return dialog;
  18601. };
  18602. var iframeUrlMap = {
  18603. 'anchor':'~/dialogs/anchor/anchor.html',
  18604. 'insertimage':'~/dialogs/image/image.html',
  18605. 'link':'~/dialogs/link/link.html',
  18606. 'spechars':'~/dialogs/spechars/spechars.html',
  18607. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  18608. 'map':'~/dialogs/map/map.html',
  18609. 'gmap':'~/dialogs/gmap/gmap.html',
  18610. 'insertvideo':'~/dialogs/video/video.html',
  18611. 'help':'~/dialogs/help/help.html',
  18612. //'highlightcode':'~/dialogs/highlightcode/highlightcode.html',
  18613. 'emotion':'~/dialogs/emotion/emotion.html',
  18614. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  18615. 'attachment':'~/dialogs/attachment/attachment.html',
  18616. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  18617. 'edittip':'~/dialogs/table/edittip.html',
  18618. 'edittable':'~/dialogs/table/edittable.html',
  18619. 'edittd':'~/dialogs/table/edittd.html',
  18620. 'webapp':'~/dialogs/webapp/webapp.html',
  18621. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  18622. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  18623. 'music':'~/dialogs/music/music.html',
  18624. 'template':'~/dialogs/template/template.html',
  18625. 'background':'~/dialogs/background/background.html'
  18626. };
  18627. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  18628. var btnCmds = ['undo', 'redo', 'formatmatch',
  18629. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  18630. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  18631. 'blockquote', 'pasteplain', 'pagebreak',
  18632. 'selectall', 'print', 'preview', 'horizontal', 'removeformat', 'time', 'date', 'unlink',
  18633. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  18634. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable'];
  18635. for (var i = 0, ci; ci = btnCmds[i++];) {
  18636. ci = ci.toLowerCase();
  18637. editorui[ci] = function (cmd) {
  18638. return function (editor) {
  18639. var ui = new editorui.Button({
  18640. className:'edui-for-' + cmd,
  18641. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  18642. onclick:function () {
  18643. editor.execCommand(cmd);
  18644. },
  18645. theme:editor.options.theme,
  18646. showText:false
  18647. });
  18648. editorui.buttons[cmd] = ui;
  18649. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18650. var state = editor.queryCommandState(cmd);
  18651. if (state == -1) {
  18652. ui.setDisabled(true);
  18653. ui.setChecked(false);
  18654. } else {
  18655. if (!uiReady) {
  18656. ui.setDisabled(false);
  18657. ui.setChecked(state);
  18658. }
  18659. }
  18660. });
  18661. return ui;
  18662. };
  18663. }(ci);
  18664. }
  18665. //清除文档
  18666. editorui.cleardoc = function (editor) {
  18667. var ui = new editorui.Button({
  18668. className:'edui-for-cleardoc',
  18669. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  18670. theme:editor.options.theme,
  18671. onclick:function () {
  18672. if (confirm(editor.getLang("confirmClear"))) {
  18673. editor.execCommand('cleardoc');
  18674. }
  18675. }
  18676. });
  18677. editorui.buttons["cleardoc"] = ui;
  18678. editor.addListener('selectionchange', function () {
  18679. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  18680. });
  18681. return ui;
  18682. };
  18683. //排版,图片排版,文字方向
  18684. var typeset = {
  18685. 'justify':['left', 'right', 'center', 'justify'],
  18686. 'imagefloat':['none', 'left', 'center', 'right'],
  18687. 'directionality':['ltr', 'rtl']
  18688. };
  18689. for (var p in typeset) {
  18690. (function (cmd, val) {
  18691. for (var i = 0, ci; ci = val[i++];) {
  18692. (function (cmd2) {
  18693. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  18694. var ui = new editorui.Button({
  18695. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  18696. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  18697. theme:editor.options.theme,
  18698. onclick:function () {
  18699. editor.execCommand(cmd, cmd2);
  18700. }
  18701. });
  18702. editorui.buttons[cmd] = ui;
  18703. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18704. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  18705. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  18706. });
  18707. return ui;
  18708. };
  18709. })(ci)
  18710. }
  18711. })(p, typeset[p])
  18712. }
  18713. //字体颜色和背景颜色
  18714. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  18715. editorui[ci] = function (cmd) {
  18716. return function (editor) {
  18717. var ui = new editorui.ColorButton({
  18718. className:'edui-for-' + cmd,
  18719. color:'default',
  18720. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  18721. editor:editor,
  18722. onpickcolor:function (t, color) {
  18723. editor.execCommand(cmd, color);
  18724. },
  18725. onpicknocolor:function () {
  18726. editor.execCommand(cmd, 'default');
  18727. this.setColor('transparent');
  18728. this.color = 'default';
  18729. },
  18730. onbuttonclick:function () {
  18731. editor.execCommand(cmd, this.color);
  18732. }
  18733. });
  18734. editorui.buttons[cmd] = ui;
  18735. editor.addListener('selectionchange', function () {
  18736. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  18737. });
  18738. return ui;
  18739. };
  18740. }(ci);
  18741. }
  18742. var dialogBtns = {
  18743. noOk:['searchreplace', 'help', 'spechars', 'webapp'],
  18744. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  18745. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background']
  18746. };
  18747. for (var p in dialogBtns) {
  18748. (function (type, vals) {
  18749. for (var i = 0, ci; ci = vals[i++];) {
  18750. //todo opera下存在问题
  18751. if (browser.opera && ci === "searchreplace") {
  18752. continue;
  18753. }
  18754. (function (cmd) {
  18755. editorui[cmd] = function (editor, iframeUrl, title) {
  18756. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  18757. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  18758. var dialog;
  18759. //没有iframeUrl不创建dialog
  18760. if (iframeUrl) {
  18761. dialog = new editorui.Dialog(utils.extend({
  18762. iframeUrl:editor.ui.mapUrl(iframeUrl),
  18763. editor:editor,
  18764. className:'edui-for-' + cmd,
  18765. title:title,
  18766. holdScroll: cmd === 'insertimage',
  18767. closeDialog:editor.getLang("closeDialog")
  18768. }, type == 'ok' ? {
  18769. buttons:[
  18770. {
  18771. className:'edui-okbutton',
  18772. label:editor.getLang("ok"),
  18773. editor:editor,
  18774. onclick:function () {
  18775. dialog.close(true);
  18776. }
  18777. },
  18778. {
  18779. className:'edui-cancelbutton',
  18780. label:editor.getLang("cancel"),
  18781. editor:editor,
  18782. onclick:function () {
  18783. dialog.close(false);
  18784. }
  18785. }
  18786. ]
  18787. } : {}));
  18788. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  18789. }
  18790. var ui = new editorui.Button({
  18791. className:'edui-for-' + cmd,
  18792. title:title,
  18793. onclick:function () {
  18794. if (dialog) {
  18795. switch (cmd) {
  18796. case "wordimage":
  18797. editor.execCommand("wordimage", "word_img");
  18798. if (editor.word_img) {
  18799. dialog.render();
  18800. dialog.open();
  18801. }
  18802. break;
  18803. case "scrawl":
  18804. if (editor.queryCommandState("scrawl") != -1) {
  18805. dialog.render();
  18806. dialog.open();
  18807. }
  18808. break;
  18809. default:
  18810. dialog.render();
  18811. dialog.open();
  18812. }
  18813. }
  18814. },
  18815. theme:editor.options.theme,
  18816. disabled:cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1
  18817. });
  18818. editorui.buttons[cmd] = ui;
  18819. editor.addListener('selectionchange', function () {
  18820. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  18821. var unNeedCheckState = {'edittable':1};
  18822. if (cmd in unNeedCheckState)return;
  18823. var state = editor.queryCommandState(cmd);
  18824. if (ui.getDom()) {
  18825. ui.setDisabled(state == -1);
  18826. ui.setChecked(state);
  18827. }
  18828. });
  18829. return ui;
  18830. };
  18831. })(ci.toLowerCase())
  18832. }
  18833. })(p, dialogBtns[p])
  18834. }
  18835. editorui.snapscreen = function (editor, iframeUrl, title) {
  18836. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  18837. var ui = new editorui.Button({
  18838. className:'edui-for-snapscreen',
  18839. title:title,
  18840. onclick:function () {
  18841. editor.execCommand("snapscreen");
  18842. },
  18843. theme:editor.options.theme
  18844. });
  18845. editorui.buttons['snapscreen'] = ui;
  18846. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  18847. if (iframeUrl) {
  18848. var dialog = new editorui.Dialog({
  18849. iframeUrl:editor.ui.mapUrl(iframeUrl),
  18850. editor:editor,
  18851. className:'edui-for-snapscreen',
  18852. title:title,
  18853. buttons:[
  18854. {
  18855. className:'edui-okbutton',
  18856. label:editor.getLang("ok"),
  18857. editor:editor,
  18858. onclick:function () {
  18859. dialog.close(true);
  18860. }
  18861. },
  18862. {
  18863. className:'edui-cancelbutton',
  18864. label:editor.getLang("cancel"),
  18865. editor:editor,
  18866. onclick:function () {
  18867. dialog.close(false);
  18868. }
  18869. }
  18870. ]
  18871. });
  18872. dialog.render();
  18873. editor.ui._dialogs["snapscreenDialog"] = dialog;
  18874. }
  18875. editor.addListener('selectionchange', function () {
  18876. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  18877. });
  18878. return ui;
  18879. };
  18880. editorui.insertcode = function (editor, list, title) {
  18881. list = editor.options['insertcode'] || [];
  18882. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  18883. // if (!list.length) return;
  18884. var items = [];
  18885. utils.each(list,function(key,val){
  18886. items.push({
  18887. label:key,
  18888. value:val,
  18889. theme:editor.options.theme,
  18890. renderLabelHtml:function () {
  18891. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  18892. }
  18893. });
  18894. });
  18895. var ui = new editorui.Combox({
  18896. editor:editor,
  18897. items:items,
  18898. onselect:function (t, index) {
  18899. editor.execCommand('insertcode', this.items[index].value);
  18900. },
  18901. onbuttonclick:function () {
  18902. this.showPopup();
  18903. },
  18904. title:title,
  18905. initValue:title,
  18906. className:'edui-for-insertcode',
  18907. indexByValue:function (value) {
  18908. if (value) {
  18909. for (var i = 0, ci; ci = this.items[i]; i++) {
  18910. if (ci.value.indexOf(value) != -1)
  18911. return i;
  18912. }
  18913. }
  18914. return -1;
  18915. }
  18916. });
  18917. editorui.buttons['insertcode'] = ui;
  18918. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18919. if (!uiReady) {
  18920. var state = editor.queryCommandState('insertcode');
  18921. if (state == -1) {
  18922. ui.setDisabled(true);
  18923. } else {
  18924. ui.setDisabled(false);
  18925. var value = editor.queryCommandValue('insertcode');
  18926. if(!value){
  18927. ui.setValue(title);
  18928. return;
  18929. }
  18930. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  18931. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  18932. ui.setValue(value);
  18933. }
  18934. }
  18935. });
  18936. return ui;
  18937. };
  18938. editorui.fontfamily = function (editor, list, title) {
  18939. list = editor.options['fontfamily'] || [];
  18940. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  18941. if (!list.length) return;
  18942. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  18943. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  18944. (function (key, val) {
  18945. items.push({
  18946. label:key,
  18947. value:val,
  18948. theme:editor.options.theme,
  18949. renderLabelHtml:function () {
  18950. return '<div class="edui-label %%-label" style="font-family:' +
  18951. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  18952. }
  18953. });
  18954. })(ci.label || langLabel, ci.val)
  18955. }
  18956. var ui = new editorui.Combox({
  18957. editor:editor,
  18958. items:items,
  18959. onselect:function (t, index) {
  18960. editor.execCommand('FontFamily', this.items[index].value);
  18961. },
  18962. onbuttonclick:function () {
  18963. this.showPopup();
  18964. },
  18965. title:title,
  18966. initValue:title,
  18967. className:'edui-for-fontfamily',
  18968. indexByValue:function (value) {
  18969. if (value) {
  18970. for (var i = 0, ci; ci = this.items[i]; i++) {
  18971. if (ci.value.indexOf(value) != -1)
  18972. return i;
  18973. }
  18974. }
  18975. return -1;
  18976. }
  18977. });
  18978. editorui.buttons['fontfamily'] = ui;
  18979. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18980. if (!uiReady) {
  18981. var state = editor.queryCommandState('FontFamily');
  18982. if (state == -1) {
  18983. ui.setDisabled(true);
  18984. } else {
  18985. ui.setDisabled(false);
  18986. var value = editor.queryCommandValue('FontFamily');
  18987. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  18988. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  18989. ui.setValue(value);
  18990. }
  18991. }
  18992. });
  18993. return ui;
  18994. };
  18995. editorui.fontsize = function (editor, list, title) {
  18996. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  18997. list = list || editor.options['fontsize'] || [];
  18998. if (!list.length) return;
  18999. var items = [];
  19000. for (var i = 0; i < list.length; i++) {
  19001. var size = list[i] + 'px';
  19002. items.push({
  19003. label:size,
  19004. value:size,
  19005. theme:editor.options.theme,
  19006. renderLabelHtml:function () {
  19007. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  19008. this.value + '">' + (this.label || '') + '</div>';
  19009. }
  19010. });
  19011. }
  19012. var ui = new editorui.Combox({
  19013. editor:editor,
  19014. items:items,
  19015. title:title,
  19016. initValue:title,
  19017. onselect:function (t, index) {
  19018. editor.execCommand('FontSize', this.items[index].value);
  19019. },
  19020. onbuttonclick:function () {
  19021. this.showPopup();
  19022. },
  19023. className:'edui-for-fontsize'
  19024. });
  19025. editorui.buttons['fontsize'] = ui;
  19026. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19027. if (!uiReady) {
  19028. var state = editor.queryCommandState('FontSize');
  19029. if (state == -1) {
  19030. ui.setDisabled(true);
  19031. } else {
  19032. ui.setDisabled(false);
  19033. ui.setValue(editor.queryCommandValue('FontSize'));
  19034. }
  19035. }
  19036. });
  19037. return ui;
  19038. };
  19039. editorui.paragraph = function (editor, list, title) {
  19040. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  19041. list = editor.options['paragraph'] || [];
  19042. if (utils.isEmptyObject(list)) return;
  19043. var items = [];
  19044. for (var i in list) {
  19045. items.push({
  19046. value:i,
  19047. label:list[i] || editor.getLang("paragraph")[i],
  19048. theme:editor.options.theme,
  19049. renderLabelHtml:function () {
  19050. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  19051. }
  19052. })
  19053. }
  19054. var ui = new editorui.Combox({
  19055. editor:editor,
  19056. items:items,
  19057. title:title,
  19058. initValue:title,
  19059. className:'edui-for-paragraph',
  19060. onselect:function (t, index) {
  19061. editor.execCommand('Paragraph', this.items[index].value);
  19062. },
  19063. onbuttonclick:function () {
  19064. this.showPopup();
  19065. }
  19066. });
  19067. editorui.buttons['paragraph'] = ui;
  19068. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19069. if (!uiReady) {
  19070. var state = editor.queryCommandState('Paragraph');
  19071. if (state == -1) {
  19072. ui.setDisabled(true);
  19073. } else {
  19074. ui.setDisabled(false);
  19075. var value = editor.queryCommandValue('Paragraph');
  19076. var index = ui.indexByValue(value);
  19077. if (index != -1) {
  19078. ui.setValue(value);
  19079. } else {
  19080. ui.setValue(ui.initValue);
  19081. }
  19082. }
  19083. }
  19084. });
  19085. return ui;
  19086. };
  19087. //自定义标题
  19088. editorui.customstyle = function (editor) {
  19089. var list = editor.options['customstyle'] || [],
  19090. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  19091. if (!list.length)return;
  19092. var langCs = editor.getLang('customstyle');
  19093. for (var i = 0, items = [], t; t = list[i++];) {
  19094. (function (t) {
  19095. var ck = {};
  19096. ck.label = t.label ? t.label : langCs[t.name];
  19097. ck.style = t.style;
  19098. ck.className = t.className;
  19099. ck.tag = t.tag;
  19100. items.push({
  19101. label:ck.label,
  19102. value:ck,
  19103. theme:editor.options.theme,
  19104. renderLabelHtml:function () {
  19105. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  19106. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  19107. + '</div>';
  19108. }
  19109. });
  19110. })(t);
  19111. }
  19112. var ui = new editorui.Combox({
  19113. editor:editor,
  19114. items:items,
  19115. title:title,
  19116. initValue:title,
  19117. className:'edui-for-customstyle',
  19118. onselect:function (t, index) {
  19119. editor.execCommand('customstyle', this.items[index].value);
  19120. },
  19121. onbuttonclick:function () {
  19122. this.showPopup();
  19123. },
  19124. indexByValue:function (value) {
  19125. for (var i = 0, ti; ti = this.items[i++];) {
  19126. if (ti.label == value) {
  19127. return i - 1
  19128. }
  19129. }
  19130. return -1;
  19131. }
  19132. });
  19133. editorui.buttons['customstyle'] = ui;
  19134. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  19135. if (!uiReady) {
  19136. var state = editor.queryCommandState('customstyle');
  19137. if (state == -1) {
  19138. ui.setDisabled(true);
  19139. } else {
  19140. ui.setDisabled(false);
  19141. var value = editor.queryCommandValue('customstyle');
  19142. var index = ui.indexByValue(value);
  19143. if (index != -1) {
  19144. ui.setValue(value);
  19145. } else {
  19146. ui.setValue(ui.initValue);
  19147. }
  19148. }
  19149. }
  19150. });
  19151. return ui;
  19152. };
  19153. editorui.inserttable = function (editor, iframeUrl, title) {
  19154. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  19155. var ui = new editorui.TableButton({
  19156. editor:editor,
  19157. title:title,
  19158. className:'edui-for-inserttable',
  19159. onpicktable:function (t, numCols, numRows) {
  19160. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  19161. },
  19162. onbuttonclick:function () {
  19163. this.showPopup();
  19164. }
  19165. });
  19166. editorui.buttons['inserttable'] = ui;
  19167. editor.addListener('selectionchange', function () {
  19168. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  19169. });
  19170. return ui;
  19171. };
  19172. editorui.lineheight = function (editor) {
  19173. var val = editor.options.lineheight || [];
  19174. if (!val.length)return;
  19175. for (var i = 0, ci, items = []; ci = val[i++];) {
  19176. items.push({
  19177. //todo:写死了
  19178. label:ci,
  19179. value:ci,
  19180. theme:editor.options.theme,
  19181. onclick:function () {
  19182. editor.execCommand("lineheight", this.value);
  19183. }
  19184. })
  19185. }
  19186. var ui = new editorui.MenuButton({
  19187. editor:editor,
  19188. className:'edui-for-lineheight',
  19189. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  19190. items:items,
  19191. onbuttonclick:function () {
  19192. var value = editor.queryCommandValue('LineHeight') || this.value;
  19193. editor.execCommand("LineHeight", value);
  19194. }
  19195. });
  19196. editorui.buttons['lineheight'] = ui;
  19197. editor.addListener('selectionchange', function () {
  19198. var state = editor.queryCommandState('LineHeight');
  19199. if (state == -1) {
  19200. ui.setDisabled(true);
  19201. } else {
  19202. ui.setDisabled(false);
  19203. var value = editor.queryCommandValue('LineHeight');
  19204. value && ui.setValue((value + '').replace(/cm/, ''));
  19205. ui.setChecked(state)
  19206. }
  19207. });
  19208. return ui;
  19209. };
  19210. var rowspacings = ['top', 'bottom'];
  19211. for (var r = 0, ri; ri = rowspacings[r++];) {
  19212. (function (cmd) {
  19213. editorui['rowspacing' + cmd] = function (editor) {
  19214. var val = editor.options['rowspacing' + cmd] || [];
  19215. if (!val.length) return null;
  19216. for (var i = 0, ci, items = []; ci = val[i++];) {
  19217. items.push({
  19218. label:ci,
  19219. value:ci,
  19220. theme:editor.options.theme,
  19221. onclick:function () {
  19222. editor.execCommand("rowspacing", this.value, cmd);
  19223. }
  19224. })
  19225. }
  19226. var ui = new editorui.MenuButton({
  19227. editor:editor,
  19228. className:'edui-for-rowspacing' + cmd,
  19229. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  19230. items:items,
  19231. onbuttonclick:function () {
  19232. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  19233. editor.execCommand("rowspacing", value, cmd);
  19234. }
  19235. });
  19236. editorui.buttons[cmd] = ui;
  19237. editor.addListener('selectionchange', function () {
  19238. var state = editor.queryCommandState('rowspacing', cmd);
  19239. if (state == -1) {
  19240. ui.setDisabled(true);
  19241. } else {
  19242. ui.setDisabled(false);
  19243. var value = editor.queryCommandValue('rowspacing', cmd);
  19244. value && ui.setValue((value + '').replace(/%/, ''));
  19245. ui.setChecked(state)
  19246. }
  19247. });
  19248. return ui;
  19249. }
  19250. })(ri)
  19251. }
  19252. //有序,无序列表
  19253. var lists = ['insertorderedlist', 'insertunorderedlist'];
  19254. for (var l = 0, cl; cl = lists[l++];) {
  19255. (function (cmd) {
  19256. editorui[cmd] = function (editor) {
  19257. var vals = editor.options[cmd],
  19258. _onMenuClick = function () {
  19259. editor.execCommand(cmd, this.value);
  19260. }, items = [];
  19261. for (var i in vals) {
  19262. items.push({
  19263. label:vals[i] || editor.getLang()[cmd][i] || "",
  19264. value:i,
  19265. theme:editor.options.theme,
  19266. onclick:_onMenuClick
  19267. })
  19268. }
  19269. var ui = new editorui.MenuButton({
  19270. editor:editor,
  19271. className:'edui-for-' + cmd,
  19272. title:editor.getLang("labelMap." + cmd) || '',
  19273. 'items':items,
  19274. onbuttonclick:function () {
  19275. var value = editor.queryCommandValue(cmd) || this.value;
  19276. editor.execCommand(cmd, value);
  19277. }
  19278. });
  19279. editorui.buttons[cmd] = ui;
  19280. editor.addListener('selectionchange', function () {
  19281. var state = editor.queryCommandState(cmd);
  19282. if (state == -1) {
  19283. ui.setDisabled(true);
  19284. } else {
  19285. ui.setDisabled(false);
  19286. var value = editor.queryCommandValue(cmd);
  19287. ui.setValue(value);
  19288. ui.setChecked(state)
  19289. }
  19290. });
  19291. return ui;
  19292. };
  19293. })(cl)
  19294. }
  19295. editorui.fullscreen = function (editor, title) {
  19296. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  19297. var ui = new editorui.Button({
  19298. className:'edui-for-fullscreen',
  19299. title:title,
  19300. theme:editor.options.theme,
  19301. onclick:function () {
  19302. if (editor.ui) {
  19303. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  19304. }
  19305. this.setChecked(editor.ui.isFullScreen());
  19306. }
  19307. });
  19308. editorui.buttons['fullscreen'] = ui;
  19309. editor.addListener('selectionchange', function () {
  19310. var state = editor.queryCommandState('fullscreen');
  19311. ui.setDisabled(state == -1);
  19312. ui.setChecked(editor.ui.isFullScreen());
  19313. });
  19314. return ui;
  19315. };
  19316. // 表情
  19317. editorui["emotion"] = function (editor, iframeUrl) {
  19318. var cmd = "emotion";
  19319. var ui = new editorui.MultiMenuPop({
  19320. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  19321. editor:editor,
  19322. className:'edui-for-' + cmd,
  19323. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  19324. });
  19325. editorui.buttons[cmd] = ui;
  19326. editor.addListener('selectionchange', function () {
  19327. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  19328. });
  19329. return ui;
  19330. };
  19331. editorui.autotypeset = function (editor) {
  19332. var ui = new editorui.AutoTypeSetButton({
  19333. editor:editor,
  19334. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  19335. className:'edui-for-autotypeset',
  19336. onbuttonclick:function () {
  19337. editor.execCommand('autotypeset')
  19338. }
  19339. });
  19340. editorui.buttons['autotypeset'] = ui;
  19341. editor.addListener('selectionchange', function () {
  19342. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  19343. });
  19344. return ui;
  19345. };
  19346. })();
  19347. ///import core
  19348. ///commands 全屏
  19349. ///commandsName FullScreen
  19350. ///commandsTitle 全屏
  19351. (function () {
  19352. var utils = baidu.editor.utils,
  19353. uiUtils = baidu.editor.ui.uiUtils,
  19354. UIBase = baidu.editor.ui.UIBase,
  19355. domUtils = baidu.editor.dom.domUtils;
  19356. var nodeStack = [];
  19357. function EditorUI(options) {
  19358. this.initOptions(options);
  19359. this.initEditorUI();
  19360. }
  19361. EditorUI.prototype = {
  19362. uiName:'editor',
  19363. initEditorUI:function () {
  19364. this.editor.ui = this;
  19365. this._dialogs = {};
  19366. this.initUIBase();
  19367. this._initToolbars();
  19368. var editor = this.editor,
  19369. me = this;
  19370. editor.addListener('ready', function () {
  19371. //提供getDialog方法
  19372. editor.getDialog = function (name) {
  19373. return editor.ui._dialogs[name + "Dialog"];
  19374. };
  19375. domUtils.on(editor.window, 'scroll', function (evt) {
  19376. baidu.editor.ui.Popup.postHide(evt);
  19377. });
  19378. //提供编辑器实时宽高(全屏时宽高不变化)
  19379. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  19380. //display bottom-bar label based on config
  19381. if (editor.options.elementPathEnabled) {
  19382. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  19383. }
  19384. if (editor.options.wordCount) {
  19385. function countFn() {
  19386. setCount(editor,me);
  19387. domUtils.un(editor.document, "click", arguments.callee);
  19388. }
  19389. domUtils.on(editor.document, "click", countFn);
  19390. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  19391. }
  19392. editor.ui._scale();
  19393. if (editor.options.scaleEnabled) {
  19394. if (editor.autoHeightEnabled) {
  19395. editor.disableAutoHeight();
  19396. }
  19397. me.enableScale();
  19398. } else {
  19399. me.disableScale();
  19400. }
  19401. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  19402. editor.ui.getDom('elementpath').style.display = "none";
  19403. editor.ui.getDom('wordcount').style.display = "none";
  19404. editor.ui.getDom('scale').style.display = "none";
  19405. }
  19406. if (!editor.selection.isFocus())return;
  19407. editor.fireEvent('selectionchange', false, true);
  19408. });
  19409. editor.addListener('mousedown', function (t, evt) {
  19410. var el = evt.target || evt.srcElement;
  19411. baidu.editor.ui.Popup.postHide(evt, el);
  19412. baidu.editor.ui.ShortCutMenu.postHide(evt);
  19413. });
  19414. editor.addListener("delcells", function () {
  19415. if (UE.ui['edittip']) {
  19416. new UE.ui['edittip'](editor);
  19417. }
  19418. editor.getDialog('edittip').open();
  19419. });
  19420. var pastePop, isPaste = false, timer;
  19421. editor.addListener("afterpaste", function () {
  19422. if(editor.queryCommandState('pasteplain'))
  19423. return;
  19424. if(baidu.editor.ui.PastePicker){
  19425. pastePop = new baidu.editor.ui.Popup({
  19426. content:new baidu.editor.ui.PastePicker({editor:editor}),
  19427. editor:editor,
  19428. className:'edui-wordpastepop'
  19429. });
  19430. pastePop.render();
  19431. }
  19432. isPaste = true;
  19433. });
  19434. editor.addListener("afterinserthtml", function () {
  19435. clearTimeout(timer);
  19436. timer = setTimeout(function () {
  19437. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  19438. if(pastePop.isHidden()){
  19439. var span = domUtils.createElement(editor.document, 'span', {
  19440. 'style':"line-height:0px;",
  19441. 'innerHTML':'\ufeff'
  19442. }),
  19443. range = editor.selection.getRange();
  19444. range.insertNode(span);
  19445. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  19446. pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  19447. domUtils.remove(span);
  19448. }else{
  19449. pastePop.show();
  19450. }
  19451. delete editor.ui._isTransfer;
  19452. isPaste = false;
  19453. }
  19454. }, 200)
  19455. });
  19456. editor.addListener('contextmenu', function (t, evt) {
  19457. baidu.editor.ui.Popup.postHide(evt);
  19458. });
  19459. editor.addListener('keydown', function (t, evt) {
  19460. if (pastePop) pastePop.dispose(evt);
  19461. var keyCode = evt.keyCode || evt.which;
  19462. if(evt.altKey&&keyCode==90){
  19463. UE.ui.buttons['fullscreen'].onclick();
  19464. }
  19465. });
  19466. editor.addListener('wordcount', function (type) {
  19467. setCount(this,me);
  19468. });
  19469. function setCount(editor,ui) {
  19470. editor.setOpt({
  19471. wordCount:true,
  19472. maximumWords:10000,
  19473. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  19474. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  19475. });
  19476. var opt = editor.options,
  19477. max = opt.maximumWords,
  19478. msg = opt.wordCountMsg ,
  19479. errMsg = opt.wordOverFlowMsg,
  19480. countDom = ui.getDom('wordcount');
  19481. if (!opt.wordCount) {
  19482. return;
  19483. }
  19484. var count = editor.getContentLength(true);
  19485. if (count > max) {
  19486. countDom.innerHTML = errMsg;
  19487. editor.fireEvent("wordcountoverflow");
  19488. } else {
  19489. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  19490. }
  19491. }
  19492. editor.addListener('selectionchange', function () {
  19493. if (editor.options.elementPathEnabled) {
  19494. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  19495. }
  19496. if (editor.options.scaleEnabled) {
  19497. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  19498. }
  19499. });
  19500. var popup = new baidu.editor.ui.Popup({
  19501. editor:editor,
  19502. content:'',
  19503. className:'edui-bubble',
  19504. _onEditButtonClick:function () {
  19505. this.hide();
  19506. editor.ui._dialogs.linkDialog.open();
  19507. },
  19508. _onImgEditButtonClick:function (name) {
  19509. this.hide();
  19510. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  19511. },
  19512. _onImgSetFloat:function (value) {
  19513. this.hide();
  19514. editor.execCommand("imagefloat", value);
  19515. },
  19516. _setIframeAlign:function (value) {
  19517. var frame = popup.anchorEl;
  19518. var newFrame = frame.cloneNode(true);
  19519. switch (value) {
  19520. case -2:
  19521. newFrame.setAttribute("align", "");
  19522. break;
  19523. case -1:
  19524. newFrame.setAttribute("align", "left");
  19525. break;
  19526. case 1:
  19527. newFrame.setAttribute("align", "right");
  19528. break;
  19529. }
  19530. frame.parentNode.insertBefore(newFrame, frame);
  19531. domUtils.remove(frame);
  19532. popup.anchorEl = newFrame;
  19533. popup.showAnchor(popup.anchorEl);
  19534. },
  19535. _updateIframe:function () {
  19536. editor._iframe = popup.anchorEl;
  19537. editor.ui._dialogs.insertframeDialog.open();
  19538. popup.hide();
  19539. },
  19540. _onRemoveButtonClick:function (cmdName) {
  19541. editor.execCommand(cmdName);
  19542. this.hide();
  19543. },
  19544. queryAutoHide:function (el) {
  19545. if (el && el.ownerDocument == editor.document) {
  19546. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  19547. return el !== popup.anchorEl;
  19548. }
  19549. }
  19550. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  19551. }
  19552. });
  19553. popup.render();
  19554. if (editor.options.imagePopup) {
  19555. editor.addListener('mouseover', function (t, evt) {
  19556. evt = evt || window.event;
  19557. var el = evt.target || evt.srcElement;
  19558. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  19559. var html = popup.formatHtml(
  19560. '<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;' +
  19561. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  19562. if (html) {
  19563. popup.getDom('content').innerHTML = html;
  19564. popup.anchorEl = el;
  19565. popup.showAnchor(popup.anchorEl);
  19566. } else {
  19567. popup.hide();
  19568. }
  19569. }
  19570. });
  19571. editor.addListener('selectionchange', function (t, causeByUi) {
  19572. if (!causeByUi) return;
  19573. var html = '', str = "",
  19574. img = editor.selection.getRange().getClosedNode(),
  19575. dialogs = editor.ui._dialogs;
  19576. if (img && img.tagName == 'IMG') {
  19577. var dialogName = 'insertimageDialog';
  19578. if (img.className.indexOf("edui-faked-video") != -1) {
  19579. dialogName = "insertvideoDialog"
  19580. }
  19581. if (img.className.indexOf("edui-faked-webapp") != -1) {
  19582. dialogName = "webappDialog"
  19583. }
  19584. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  19585. dialogName = "mapDialog"
  19586. }
  19587. if (img.className.indexOf("edui-faked-music") != -1) {
  19588. dialogName = "musicDialog"
  19589. }
  19590. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  19591. dialogName = "gmapDialog"
  19592. }
  19593. if (img.getAttribute("anchorname")) {
  19594. dialogName = "anchorDialog";
  19595. html = popup.formatHtml(
  19596. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  19597. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  19598. }
  19599. if (img.getAttribute("word_img")) {
  19600. //todo 放到dialog去做查询
  19601. editor.word_img = [img.getAttribute("word_img")];
  19602. dialogName = "wordimageDialog"
  19603. }
  19604. if (!dialogs[dialogName]) {
  19605. return;
  19606. }
  19607. str = '<nobr>' + editor.getLang("property") + ': '+
  19608. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  19609. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  19610. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  19611. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  19612. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  19613. !html && (html = popup.formatHtml(str))
  19614. }
  19615. if (editor.ui._dialogs.linkDialog) {
  19616. var link = editor.queryCommandValue('link');
  19617. var url;
  19618. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  19619. var txt = url;
  19620. if (url.length > 30) {
  19621. txt = url.substring(0, 20) + "...";
  19622. }
  19623. if (html) {
  19624. html += '<div style="height:5px;"></div>'
  19625. }
  19626. html += popup.formatHtml(
  19627. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  19628. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  19629. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  19630. popup.showAnchor(link);
  19631. }
  19632. }
  19633. if (html) {
  19634. popup.getDom('content').innerHTML = html;
  19635. popup.anchorEl = img || link;
  19636. popup.showAnchor(popup.anchorEl);
  19637. } else {
  19638. popup.hide();
  19639. }
  19640. });
  19641. }
  19642. },
  19643. _initToolbars:function () {
  19644. var editor = this.editor;
  19645. var toolbars = this.toolbars || [];
  19646. var toolbarUis = [];
  19647. for (var i = 0; i < toolbars.length; i++) {
  19648. var toolbar = toolbars[i];
  19649. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  19650. for (var j = 0; j < toolbar.length; j++) {
  19651. var toolbarItem = toolbar[j];
  19652. var toolbarItemUi = null;
  19653. if (typeof toolbarItem == 'string') {
  19654. toolbarItem = toolbarItem.toLowerCase();
  19655. if (toolbarItem == '|') {
  19656. toolbarItem = 'Separator';
  19657. }
  19658. if(toolbarItem == '||'){
  19659. toolbarItem = 'Breakline';
  19660. }
  19661. if (baidu.editor.ui[toolbarItem]) {
  19662. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  19663. }
  19664. //fullscreen这里单独处理一下,放到首行去
  19665. if (toolbarItem == 'fullscreen') {
  19666. if (toolbarUis && toolbarUis[0]) {
  19667. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  19668. } else {
  19669. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  19670. }
  19671. continue;
  19672. }
  19673. } else {
  19674. toolbarItemUi = toolbarItem;
  19675. }
  19676. if (toolbarItemUi && toolbarItemUi.id) {
  19677. toolbarUi.add(toolbarItemUi);
  19678. }
  19679. }
  19680. toolbarUis[i] = toolbarUi;
  19681. }
  19682. this.toolbars = toolbarUis;
  19683. },
  19684. getHtmlTpl:function () {
  19685. return '<div id="##" class="%%">' +
  19686. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  19687. (this.toolbars.length ?
  19688. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  19689. this.renderToolbarBoxHtml() +
  19690. '</div></div>' : '') +
  19691. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  19692. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  19693. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  19694. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  19695. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  19696. '</div>' +
  19697. '</div>' +
  19698. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  19699. //modify wdcount by matao
  19700. '<div id="##_bottombar" style="display:none;" class="%%-bottomContainer"><table><tr>' +
  19701. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  19702. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  19703. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  19704. '</tr></table></div>' +
  19705. '<div id="##_scalelayer"></div>' +
  19706. '</div>';
  19707. },
  19708. showWordImageDialog:function () {
  19709. this.editor.execCommand("wordimage", "word_img");
  19710. this._dialogs['wordimageDialog'].open();
  19711. },
  19712. renderToolbarBoxHtml:function () {
  19713. var buff = [];
  19714. for (var i = 0; i < this.toolbars.length; i++) {
  19715. buff.push(this.toolbars[i].renderHtml());
  19716. }
  19717. return buff.join('');
  19718. },
  19719. setFullScreen:function (fullscreen) {
  19720. var editor = this.editor,
  19721. container = editor.container.parentNode.parentNode;
  19722. if (this._fullscreen != fullscreen) {
  19723. this._fullscreen = fullscreen;
  19724. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  19725. if (baidu.editor.browser.gecko) {
  19726. var bk = editor.selection.getRange().createBookmark();
  19727. }
  19728. if (fullscreen) {
  19729. while (container.tagName != "BODY") {
  19730. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  19731. nodeStack.push(position);
  19732. container.style.position = "static";
  19733. container = container.parentNode;
  19734. }
  19735. this._bakHtmlOverflow = document.documentElement.style.overflow;
  19736. this._bakBodyOverflow = document.body.style.overflow;
  19737. this._bakAutoHeight = this.editor.autoHeightEnabled;
  19738. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  19739. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  19740. if (this._bakAutoHeight) {
  19741. //当全屏时不能执行自动长高
  19742. editor.autoHeightEnabled = false;
  19743. this.editor.disableAutoHeight();
  19744. }
  19745. document.documentElement.style.overflow = 'hidden';
  19746. document.body.style.overflow = 'hidden';
  19747. this._bakCssText = this.getDom().style.cssText;
  19748. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  19749. editor.iframe.parentNode.style.width = '';
  19750. this._updateFullScreen();
  19751. } else {
  19752. while (container.tagName != "BODY") {
  19753. container.style.position = nodeStack.shift();
  19754. container = container.parentNode;
  19755. }
  19756. this.getDom().style.cssText = this._bakCssText;
  19757. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  19758. if (this._bakAutoHeight) {
  19759. editor.autoHeightEnabled = true;
  19760. this.editor.enableAutoHeight();
  19761. }
  19762. document.documentElement.style.overflow = this._bakHtmlOverflow;
  19763. document.body.style.overflow = this._bakBodyOverflow;
  19764. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  19765. window.scrollTo(0, this._bakScrollTop);
  19766. }
  19767. if (browser.gecko && editor.body.contentEditable === 'true') {
  19768. var input = document.createElement('input');
  19769. document.body.appendChild(input);
  19770. editor.body.contentEditable = false;
  19771. setTimeout(function () {
  19772. input.focus();
  19773. setTimeout(function () {
  19774. editor.body.contentEditable = true;
  19775. editor.fireEvent('fullscreenchanged', fullscreen);
  19776. editor.selection.getRange().moveToBookmark(bk).select(true);
  19777. baidu.editor.dom.domUtils.remove(input);
  19778. fullscreen && window.scroll(0, 0);
  19779. }, 0)
  19780. }, 0)
  19781. }
  19782. if(editor.body.contentEditable === 'true'){
  19783. this.editor.fireEvent('fullscreenchanged', fullscreen);
  19784. this.triggerLayout();
  19785. }
  19786. }
  19787. },
  19788. _updateFullScreen:function () {
  19789. if (this._fullscreen) {
  19790. var vpRect = uiUtils.getViewportRect();
  19791. 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);
  19792. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  19793. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  19794. //不手动调一下,会导致全屏失效
  19795. if(browser.gecko){
  19796. try{
  19797. window.onresize();
  19798. }catch(e){
  19799. }
  19800. }
  19801. }
  19802. },
  19803. _updateElementPath:function () {
  19804. var bottom = this.getDom('elementpath'), list;
  19805. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  19806. var buff = [];
  19807. for (var i = 0, ci; ci = list[i]; i++) {
  19808. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  19809. }
  19810. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  19811. } else {
  19812. bottom.style.display = 'none'
  19813. }
  19814. },
  19815. disableElementPath:function () {
  19816. var bottom = this.getDom('elementpath');
  19817. bottom.innerHTML = '';
  19818. bottom.style.display = 'none';
  19819. this.elementPathEnabled = false;
  19820. },
  19821. enableElementPath:function () {
  19822. var bottom = this.getDom('elementpath');
  19823. bottom.style.display = '';
  19824. this.elementPathEnabled = true;
  19825. this._updateElementPath();
  19826. },
  19827. _scale:function () {
  19828. var doc = document,
  19829. editor = this.editor,
  19830. editorHolder = editor.container,
  19831. editorDocument = editor.document,
  19832. toolbarBox = this.getDom("toolbarbox"),
  19833. bottombar = this.getDom("bottombar"),
  19834. scale = this.getDom("scale"),
  19835. scalelayer = this.getDom("scalelayer");
  19836. var isMouseMove = false,
  19837. position = null,
  19838. minEditorHeight = 0,
  19839. minEditorWidth = editor.options.minFrameWidth,
  19840. pageX = 0,
  19841. pageY = 0,
  19842. scaleWidth = 0,
  19843. scaleHeight = 0;
  19844. function down() {
  19845. position = domUtils.getXY(editorHolder);
  19846. if (!minEditorHeight) {
  19847. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  19848. }
  19849. 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:"
  19850. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  19851. domUtils.on(doc, "mousemove", move);
  19852. domUtils.on(editorDocument, "mouseup", up);
  19853. domUtils.on(doc, "mouseup", up);
  19854. }
  19855. var me = this;
  19856. //by xuheng 全屏时关掉缩放
  19857. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  19858. if (fullScreen) {
  19859. me.disableScale();
  19860. } else {
  19861. if (me.editor.options.scaleEnabled) {
  19862. me.enableScale();
  19863. var tmpNode = me.editor.document.createElement('span');
  19864. me.editor.body.appendChild(tmpNode);
  19865. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  19866. domUtils.remove(tmpNode)
  19867. }
  19868. }
  19869. });
  19870. function move(event) {
  19871. clearSelection();
  19872. var e = event || window.event;
  19873. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  19874. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  19875. scaleWidth = pageX - position.x;
  19876. scaleHeight = pageY - position.y;
  19877. if (scaleWidth >= minEditorWidth) {
  19878. isMouseMove = true;
  19879. scalelayer.style.width = scaleWidth + 'px';
  19880. }
  19881. if (scaleHeight >= minEditorHeight) {
  19882. isMouseMove = true;
  19883. scalelayer.style.height = scaleHeight + "px";
  19884. }
  19885. }
  19886. function up() {
  19887. if (isMouseMove) {
  19888. isMouseMove = false;
  19889. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  19890. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  19891. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  19892. }
  19893. if (scalelayer) {
  19894. scalelayer.style.display = "none";
  19895. }
  19896. clearSelection();
  19897. domUtils.un(doc, "mousemove", move);
  19898. domUtils.un(editorDocument, "mouseup", up);
  19899. domUtils.un(doc, "mouseup", up);
  19900. }
  19901. function clearSelection() {
  19902. if (browser.ie)
  19903. doc.selection.clear();
  19904. else
  19905. window.getSelection().removeAllRanges();
  19906. }
  19907. this.enableScale = function () {
  19908. //trace:2868
  19909. if (editor.queryCommandState("source") == 1) return;
  19910. scale.style.display = "";
  19911. this.scaleEnabled = true;
  19912. domUtils.on(scale, "mousedown", down);
  19913. };
  19914. this.disableScale = function () {
  19915. scale.style.display = "none";
  19916. this.scaleEnabled = false;
  19917. domUtils.un(scale, "mousedown", down);
  19918. };
  19919. },
  19920. isFullScreen:function () {
  19921. return this._fullscreen;
  19922. },
  19923. postRender:function () {
  19924. UIBase.prototype.postRender.call(this);
  19925. for (var i = 0; i < this.toolbars.length; i++) {
  19926. this.toolbars[i].postRender();
  19927. }
  19928. var me = this;
  19929. var timerId,
  19930. domUtils = baidu.editor.dom.domUtils,
  19931. updateFullScreenTime = function () {
  19932. clearTimeout(timerId);
  19933. timerId = setTimeout(function () {
  19934. me._updateFullScreen();
  19935. });
  19936. };
  19937. domUtils.on(window, 'resize', updateFullScreenTime);
  19938. me.addListener('destroy', function () {
  19939. domUtils.un(window, 'resize', updateFullScreenTime);
  19940. clearTimeout(timerId);
  19941. })
  19942. },
  19943. showToolbarMsg:function (msg, flag) {
  19944. this.getDom('toolbarmsg_label').innerHTML = msg;
  19945. this.getDom('toolbarmsg').style.display = '';
  19946. //
  19947. if (!flag) {
  19948. var w = this.getDom('upload_dialog');
  19949. w.style.display = 'none';
  19950. }
  19951. },
  19952. hideToolbarMsg:function () {
  19953. this.getDom('toolbarmsg').style.display = 'none';
  19954. },
  19955. mapUrl:function (url) {
  19956. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  19957. },
  19958. triggerLayout:function () {
  19959. var dom = this.getDom();
  19960. if (dom.style.zoom == '1') {
  19961. dom.style.zoom = '100%';
  19962. } else {
  19963. dom.style.zoom = '1';
  19964. }
  19965. }
  19966. };
  19967. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  19968. var instances = {};
  19969. UE.ui.Editor = function (options) {
  19970. var editor = new UE.Editor(options);
  19971. editor.options.editor = editor;
  19972. utils.loadFile(document, {
  19973. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  19974. tag:"link",
  19975. type:"text/css",
  19976. rel:"stylesheet"
  19977. });
  19978. var oldRender = editor.render;
  19979. editor.render = function (holder) {
  19980. if (holder.constructor === String) {
  19981. editor.key = holder;
  19982. instances[holder] = editor;
  19983. }
  19984. utils.domReady(function () {
  19985. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  19986. function renderUI() {
  19987. editor.setOpt({
  19988. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  19989. });
  19990. new EditorUI(editor.options);
  19991. if (holder) {
  19992. if (holder.constructor === String) {
  19993. holder = document.getElementById(holder);
  19994. }
  19995. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  19996. if (holder && /script|textarea/ig.test(holder.tagName)) {
  19997. var newDiv = document.createElement('div');
  19998. holder.parentNode.insertBefore(newDiv, holder);
  19999. var cont = holder.value || holder.innerHTML;
  20000. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  20001. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  20002. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  20003. .replace(/>[\n\r\t]+</g, '><');
  20004. holder.className && (newDiv.className = holder.className);
  20005. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  20006. if (/textarea/i.test(holder.tagName)) {
  20007. editor.textarea = holder;
  20008. editor.textarea.style.display = 'none';
  20009. } else {
  20010. holder.parentNode.removeChild(holder);
  20011. holder.id && (newDiv.id = holder.id);
  20012. }
  20013. holder = newDiv;
  20014. holder.innerHTML = '';
  20015. }
  20016. }
  20017. domUtils.addClass(holder, "edui-" + editor.options.theme);
  20018. editor.ui.render(holder);
  20019. var opt = editor.options;
  20020. //给实例添加一个编辑器的容器引用
  20021. editor.container = editor.ui.getDom();
  20022. var parents = domUtils.findParents(holder,true);
  20023. var displays = [];
  20024. for(var i = 0 ,ci;ci=parents[i];i++){
  20025. displays[i] = ci.style.display;
  20026. ci.style.display = 'block'
  20027. }
  20028. if (opt.initialFrameWidth) {
  20029. opt.minFrameWidth = opt.initialFrameWidth;
  20030. } else {
  20031. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  20032. }
  20033. if (opt.initialFrameHeight) {
  20034. opt.minFrameHeight = opt.initialFrameHeight;
  20035. } else {
  20036. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  20037. }
  20038. for(var i = 0 ,ci;ci=parents[i];i++){
  20039. ci.style.display = displays[i]
  20040. }
  20041. //编辑器最外容器设置了高度,会导致,编辑器不占位
  20042. //todo 先去掉,没有找到原因
  20043. if(holder.style.height){
  20044. holder.style.height = ''
  20045. }
  20046. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  20047. editor.container.style.zIndex = opt.zIndex;
  20048. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  20049. }
  20050. })
  20051. };
  20052. return editor;
  20053. };
  20054. /**
  20055. * @file
  20056. * @name UE
  20057. * @short UE
  20058. * @desc UEditor的顶部命名空间
  20059. */
  20060. /**
  20061. * @name getEditor
  20062. * @since 1.2.4+
  20063. * @grammar UE.getEditor(id,[opt]) => Editor实例
  20064. * @desc 提供一个全局的方法得到编辑器实例
  20065. *
  20066. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  20067. * * ''opt'' 编辑器的可选参数
  20068. * @example
  20069. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  20070. * this.setContent('hello')
  20071. * }});
  20072. * UE.getEditor('containerId'); //返回刚创建的实例
  20073. *
  20074. */
  20075. UE.getEditor = function (id, opt) {
  20076. var editor = instances[id];
  20077. if (!editor) {
  20078. editor = instances[id] = new UE.ui.Editor(opt);
  20079. editor.render(id);
  20080. }
  20081. return editor;
  20082. };
  20083. UE.delEditor = function (id) {
  20084. var editor;
  20085. if (editor = instances[id]) {
  20086. editor.key && editor.destroy();
  20087. delete instances[id]
  20088. }
  20089. }
  20090. })();
  20091. ///import core
  20092. ///import uicore
  20093. ///commands 表情
  20094. (function(){
  20095. var utils = baidu.editor.utils,
  20096. Popup = baidu.editor.ui.Popup,
  20097. SplitButton = baidu.editor.ui.SplitButton,
  20098. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  20099. this.initOptions(options);
  20100. this.initMultiMenu();
  20101. };
  20102. MultiMenuPop.prototype = {
  20103. initMultiMenu: function (){
  20104. var me = this;
  20105. this.popup = new Popup({
  20106. content: '',
  20107. editor : me.editor,
  20108. iframe_rendered: false,
  20109. onshow: function (){
  20110. if (!this.iframe_rendered) {
  20111. this.iframe_rendered = true;
  20112. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  20113. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  20114. }
  20115. }
  20116. // canSideUp:false,
  20117. // canSideLeft:false
  20118. });
  20119. this.onbuttonclick = function(){
  20120. this.showPopup();
  20121. };
  20122. this.initSplitButton();
  20123. }
  20124. };
  20125. utils.inherits(MultiMenuPop, SplitButton);
  20126. })();
  20127. (function () {
  20128. var UI = baidu.editor.ui,
  20129. UIBase = UI.UIBase,
  20130. uiUtils = UI.uiUtils,
  20131. utils = baidu.editor.utils,
  20132. domUtils = baidu.editor.dom.domUtils;
  20133. var allMenus = [],//存储所有快捷菜单
  20134. timeID,
  20135. isSubMenuShow = false;//是否有子pop显示
  20136. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  20137. this.initOptions (options);
  20138. this.initShortCutMenu ();
  20139. };
  20140. ShortCutMenu.postHide = hideAllMenu;
  20141. ShortCutMenu.prototype = {
  20142. isHidden : true ,
  20143. SPACE : 5 ,
  20144. initShortCutMenu : function () {
  20145. this.items = this.items || [];
  20146. this.initUIBase ();
  20147. this.initItems ();
  20148. this.initEvent ();
  20149. allMenus.push (this);
  20150. } ,
  20151. initEvent : function () {
  20152. var me = this,
  20153. doc = me.editor.document;
  20154. domUtils.on (doc , "mousemove" , function (e) {
  20155. if (me.isHidden === false) {
  20156. //有pop显示就不隐藏快捷菜单
  20157. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  20158. var flag = true,
  20159. el = me.getDom (),
  20160. wt = el.offsetWidth,
  20161. ht = el.offsetHeight,
  20162. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  20163. distanceY = ht / 2,//距离中心Y标准
  20164. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  20165. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  20166. clearTimeout (timeID);
  20167. timeID = setTimeout (function () {
  20168. if (y > 0 && y < distanceY) {
  20169. me.setOpacity (el , "1");
  20170. } else if (y > distanceY && y < distanceY + 70) {
  20171. me.setOpacity (el , "0.5");
  20172. flag = false;
  20173. } else if (y > distanceY + 70 && y < distanceY + 140) {
  20174. me.hide ();
  20175. }
  20176. if (flag && x > 0 && x < distanceX) {
  20177. me.setOpacity (el , "1")
  20178. } else if (x > distanceX && x < distanceX + 70) {
  20179. me.setOpacity (el , "0.5")
  20180. } else if (x > distanceX + 70 && x < distanceX + 140) {
  20181. me.hide ();
  20182. }
  20183. });
  20184. }
  20185. });
  20186. //ie\ff下 mouseout不准
  20187. if (browser.chrome) {
  20188. domUtils.on (doc , "mouseout" , function (e) {
  20189. var relatedTgt = e.relatedTarget || e.toElement;
  20190. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  20191. me.hide ();
  20192. }
  20193. });
  20194. }
  20195. me.editor.addListener ("afterhidepop" , function () {
  20196. if (!me.isHidden) {
  20197. isSubMenuShow = true;
  20198. }
  20199. });
  20200. } ,
  20201. initItems : function () {
  20202. if (utils.isArray (this.items)) {
  20203. for (var i = 0, len = this.items.length ; i < len ; i++) {
  20204. var item = this.items[i].toLowerCase ();
  20205. if (UI[item]) {
  20206. this.items[i] = new UI[item] (this.editor);
  20207. this.items[i].className += " edui-shortcutsubmenu ";
  20208. }
  20209. }
  20210. }
  20211. } ,
  20212. setOpacity : function (el , value) {
  20213. if (browser.ie && browser.version < 9) {
  20214. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  20215. } else {
  20216. el.style.opacity = value;
  20217. }
  20218. } ,
  20219. getSubMenuMark : function () {
  20220. isSubMenuShow = false;
  20221. var layerEle = uiUtils.getFixedLayer ();
  20222. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  20223. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  20224. });
  20225. for (var i = 0, node ; node = list[i++] ;) {
  20226. if (node.style.display != "none") {
  20227. isSubMenuShow = true;
  20228. }
  20229. }
  20230. return isSubMenuShow;
  20231. } ,
  20232. show : function (e , hasContextmenu) {
  20233. var me = this,
  20234. offset = {},
  20235. el = this.getDom (),
  20236. fixedlayer = uiUtils.getFixedLayer ();
  20237. function setPos (offset) {
  20238. if (offset.left < 0) {
  20239. offset.left = 0;
  20240. }
  20241. if (offset.top < 0) {
  20242. offset.top = 0;
  20243. }
  20244. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  20245. }
  20246. function setPosByCxtMenu (menu) {
  20247. if (!menu.tagName) {
  20248. menu = menu.getDom ();
  20249. }
  20250. offset.left = parseInt (menu.style.left);
  20251. offset.top = parseInt (menu.style.top);
  20252. offset.top -= el.offsetHeight + 15;
  20253. setPos (offset);
  20254. }
  20255. me.eventType = e.type;
  20256. el.style.cssText = "display:block;left:-9999px";
  20257. if (e.type == "contextmenu" && hasContextmenu) {
  20258. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  20259. if (menu) {
  20260. setPosByCxtMenu (menu)
  20261. } else {
  20262. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  20263. setPosByCxtMenu (menu);
  20264. });
  20265. }
  20266. } else {
  20267. offset = uiUtils.getViewportOffsetByEvent (e);
  20268. offset.top -= el.offsetHeight + me.SPACE;
  20269. offset.left += me.SPACE + 20;
  20270. setPos (offset);
  20271. me.setOpacity (el , 0.2);
  20272. }
  20273. me.isHidden = false;
  20274. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  20275. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  20276. if (me.editor) {
  20277. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  20278. fixedlayer.style.zIndex = el.style.zIndex - 1;
  20279. }
  20280. } ,
  20281. hide : function () {
  20282. if (this.getDom ()) {
  20283. this.getDom ().style.display = "none";
  20284. }
  20285. this.isHidden = true;
  20286. } ,
  20287. postRender : function () {
  20288. if (utils.isArray (this.items)) {
  20289. for (var i = 0, item ; item = this.items[i++] ;) {
  20290. item.postRender ();
  20291. }
  20292. }
  20293. } ,
  20294. getHtmlTpl : function () {
  20295. var buff;
  20296. if (utils.isArray (this.items)) {
  20297. buff = [];
  20298. for (var i = 0 ; i < this.items.length ; i++) {
  20299. buff[i] = this.items[i].renderHtml ();
  20300. }
  20301. buff = buff.join ("");
  20302. } else {
  20303. buff = this.items;
  20304. }
  20305. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  20306. buff +
  20307. '</div>';
  20308. }
  20309. };
  20310. utils.inherits (ShortCutMenu , UIBase);
  20311. function hideAllMenu (e) {
  20312. var tgt = e.target || e.srcElement,
  20313. cur = domUtils.findParent (tgt , function (node) {
  20314. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  20315. } , true);
  20316. if (!cur) {
  20317. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  20318. menu.hide ()
  20319. }
  20320. }
  20321. }
  20322. domUtils.on (document , 'mousedown' , function (e) {
  20323. hideAllMenu (e);
  20324. });
  20325. domUtils.on (window , 'scroll' , function (e) {
  20326. hideAllMenu (e);
  20327. });
  20328. }) ();
  20329. (function (){
  20330. var utils = baidu.editor.utils,
  20331. UIBase = baidu.editor.ui.UIBase,
  20332. Breakline = baidu.editor.ui.Breakline = function (options){
  20333. this.initOptions(options);
  20334. this.initSeparator();
  20335. };
  20336. Breakline.prototype = {
  20337. uiName: 'Breakline',
  20338. initSeparator: function (){
  20339. this.initUIBase();
  20340. },
  20341. getHtmlTpl: function (){
  20342. return '<br/>';
  20343. }
  20344. };
  20345. utils.inherits(Breakline, UIBase);
  20346. })();
  20347. })()